convert.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. #!/usr/bin/env python3
  2. import gguf
  3. import argparse
  4. import concurrent.futures
  5. import copy
  6. import enum
  7. import faulthandler
  8. import functools
  9. import io
  10. import itertools
  11. import json
  12. import math
  13. import mmap
  14. import pickle
  15. import re
  16. import signal
  17. import struct
  18. import sys
  19. import zipfile
  20. import numpy as np
  21. from abc import ABCMeta, abstractmethod
  22. from dataclasses import dataclass
  23. from pathlib import Path
  24. from typing import (IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Optional, Sequence, Tuple, TypeVar, Union)
  25. from sentencepiece import SentencePieceProcessor # type: ignore
  26. if TYPE_CHECKING:
  27. from typing_extensions import TypeAlias
  28. if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
  29. faulthandler.register(signal.SIGUSR1)
  30. NDArray: 'TypeAlias' = 'np.ndarray[Any, Any]'
  31. ARCH=gguf.MODEL_ARCH.LLAMA
  32. NAMES=gguf.MODEL_TENSOR_NAMES[ARCH]
  33. #
  34. # data types
  35. #
  36. @dataclass(frozen=True)
  37. class UnquantizedDataType:
  38. name: str
  39. DT_F16 = UnquantizedDataType('F16')
  40. DT_F32 = UnquantizedDataType('F32')
  41. DT_I32 = UnquantizedDataType('I32')
  42. DT_BF16 = UnquantizedDataType('BF16')
  43. DataType = Union[UnquantizedDataType]
  44. DATA_TYPE_TO_NUMPY: Dict[DataType, 'np.dtype[Any]'] = {
  45. DT_BF16: np.dtype(np.uint16),
  46. DT_F16: np.dtype(np.float16),
  47. DT_F32: np.dtype(np.float32),
  48. DT_I32: np.dtype(np.int32),
  49. }
  50. NUMPY_TYPE_TO_DATA_TYPE: Dict['np.dtype[Any]', DataType] = \
  51. {dtype: data_type for (data_type, dtype) in DATA_TYPE_TO_NUMPY.items()}
  52. SAFETENSORS_DATA_TYPES: Dict[str, DataType] = {
  53. 'BF16': DT_BF16,
  54. 'F16': DT_F16,
  55. 'F32': DT_F32,
  56. 'I32': DT_I32,
  57. }
  58. # TODO: match this with `llama_ftype`
  59. # TODO: rename to LLAMAFileType
  60. # TODO: move to `gguf.py`
  61. class GGMLFileType(enum.IntEnum):
  62. AllF32 = 0
  63. MostlyF16 = 1 # except 1d tensors
  64. def type_for_tensor(self, name: str, tensor: 'LazyTensor') -> DataType:
  65. if len(tensor.shape) == 1:
  66. # 1D tensors are always F32.
  67. return DT_F32
  68. elif self == GGMLFileType.AllF32:
  69. return DT_F32
  70. elif self == GGMLFileType.MostlyF16:
  71. return DT_F16
  72. else:
  73. raise ValueError(self)
  74. #
  75. # hparams loading
  76. #
  77. @dataclass
  78. class Params:
  79. n_vocab: int
  80. n_embd: int
  81. n_mult: int
  82. n_layer: int
  83. n_ctx: int
  84. n_ff: int
  85. n_head: int
  86. n_head_kv: int
  87. f_norm_eps: float
  88. f_rope_freq_base: Optional[float] = None
  89. ftype: Optional[GGMLFileType] = None
  90. # path to the directory containing the model files
  91. path_model: Optional['Path'] = None
  92. @staticmethod
  93. def find_n_mult(n_ff: int, n_embd: int) -> int:
  94. # hardcoded magic range
  95. for n_mult in range(8192, 1, -1):
  96. calc_ff = (((8*n_embd) // 3 + n_mult - 1) // n_mult)*n_mult
  97. if calc_ff == n_ff:
  98. return n_mult
  99. raise Exception(f"failed to find n_mult for (n_ff={n_ff}, n_embd={n_embd}).")
  100. @staticmethod
  101. def guessed(model: 'LazyModel') -> 'Params':
  102. # try transformer naming first
  103. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  104. # try transformer naming first
  105. if "model.layers.0.self_attn.q_proj.weight" in model:
  106. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  107. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  108. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  109. else:
  110. n_layer=next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  111. if n_layer < 1:
  112. raise Exception("failed to guess 'n_layer'. This model is unknown or unsupported.\n"
  113. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  114. n_head = n_embd // 128 # guessed
  115. n_mult = 256 # guessed
  116. # TODO: verify this
  117. n_ff = int(2 * (4 * n_embd) / 3)
  118. n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
  119. return Params(
  120. n_vocab = n_vocab,
  121. n_embd = n_embd,
  122. n_mult = n_mult,
  123. n_layer = n_layer,
  124. n_ctx = -1,
  125. n_ff = n_ff,
  126. n_head = n_head,
  127. n_head_kv = n_head,
  128. f_norm_eps = 1e-5,
  129. )
  130. @staticmethod
  131. def loadHFTransformerJson(model: 'LazyModel', config_path: 'Path') -> 'Params':
  132. config = json.load(open(config_path))
  133. n_vocab = config["vocab_size"]
  134. n_embd = config["hidden_size"]
  135. n_layer = config["num_hidden_layers"]
  136. n_ff = config["intermediate_size"]
  137. n_head = config["num_attention_heads"]
  138. n_head_kv = config["num_key_value_heads"] if "num_key_value_heads" in config else n_head
  139. f_norm_eps = config["rms_norm_eps"]
  140. n_mult = Params.find_n_mult(n_ff, n_embd)
  141. if "max_sequence_length" in config:
  142. n_ctx = config["max_sequence_length"]
  143. elif "max_position_embeddings" in config:
  144. n_ctx = config["max_position_embeddings"]
  145. else:
  146. raise Exception("failed to guess 'n_ctx'. This model is unknown or unsupported.\n"
  147. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  148. return Params(
  149. n_vocab = n_vocab,
  150. n_embd = n_embd,
  151. n_mult = n_mult,
  152. n_layer = n_layer,
  153. n_ctx = n_ctx,
  154. n_ff = n_ff,
  155. n_head = n_head,
  156. n_head_kv = n_head_kv,
  157. f_norm_eps = f_norm_eps,
  158. )
  159. # LLaMA v2 70B params.json
  160. # {"dim": 8192, "multiple_of": 4096, "ffn_dim_multiplier": 1.3, "n_heads": 64, "n_kv_heads": 8, "n_layers": 80, "norm_eps": 1e-05, "vocab_size": -1
  161. @staticmethod
  162. def loadOriginalParamsJson(model: 'LazyModel', config_path: 'Path') -> 'Params':
  163. config = json.load(open(config_path))
  164. n_vocab = config["vocab_size"] if "vocab_size" in config else -1
  165. n_embd = config["dim"]
  166. n_layer = config["n_layers"]
  167. n_mult = config["multiple_of"]
  168. n_ctx = 2048 if config["norm_eps"] == 1e-06 else 4096 # hack to determine LLaMA v1 vs v2
  169. n_ff = -1
  170. n_head = config["n_heads"]
  171. n_head_kv = config["n_kv_heads"] if "n_kv_heads" in config else n_head
  172. f_norm_eps = config["norm_eps"]
  173. f_rope_freq_base = config["rope_theta"] if "rope_theta" in config else None
  174. if n_vocab == -1:
  175. n_vocab = model["tok_embeddings.weight"].shape[0]
  176. if n_ff == -1:
  177. n_ff = model["layers.0.feed_forward.w1.weight"].shape[0]
  178. return Params(
  179. n_vocab = n_vocab,
  180. n_embd = n_embd,
  181. n_mult = n_mult,
  182. n_layer = n_layer,
  183. n_ctx = n_ctx,
  184. n_ff = n_ff,
  185. n_head = n_head,
  186. n_head_kv = n_head_kv,
  187. f_norm_eps = f_norm_eps,
  188. f_rope_freq_base = f_rope_freq_base,
  189. )
  190. @staticmethod
  191. def load(model_plus: 'ModelPlus') -> 'Params':
  192. hf_config_path = model_plus.paths[0].parent / "config.json"
  193. orig_config_path = model_plus.paths[0].parent / "params.json"
  194. if hf_config_path.exists():
  195. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  196. elif orig_config_path.exists():
  197. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  198. else:
  199. params = Params.guessed(model_plus.model)
  200. params.path_model = model_plus.paths[0].parent
  201. return params
  202. #
  203. # vocab
  204. #
  205. class BpeVocab:
  206. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
  207. self.bpe_tokenizer = json.loads(open(str(fname_tokenizer), encoding="utf-8").read())
  208. added_tokens: Dict[str, int]
  209. if fname_added_tokens is not None:
  210. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  211. else:
  212. added_tokens = {}
  213. vocab_size: int = len(self.bpe_tokenizer)
  214. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  215. actual_ids = sorted(added_tokens.values())
  216. if expected_ids != actual_ids:
  217. raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
  218. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  219. self.added_tokens_list = [text for (text, idx) in items]
  220. self.vocab_size_base: int = vocab_size
  221. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  222. self.fname_tokenizer = fname_tokenizer
  223. self.fname_added_tokens = fname_added_tokens
  224. def bpe_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  225. tokenizer = self.bpe_tokenizer
  226. from transformers.models.gpt2 import tokenization_gpt2
  227. byte_encoder = tokenization_gpt2.bytes_to_unicode()
  228. byte_decoder = {v: k for k, v in byte_encoder.items()}
  229. for i, item in enumerate(tokenizer):
  230. text: bytes = item.encode("utf-8")
  231. score: float = -i
  232. yield text, score, gguf.TokenType.USER_DEFINED
  233. def added_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  234. for text in self.added_tokens_list:
  235. score = -1000.0
  236. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  237. def all_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  238. yield from self.bpe_tokens()
  239. yield from self.added_tokens()
  240. def __repr__(self) -> str:
  241. return f"BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  242. class SentencePieceVocab:
  243. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
  244. self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
  245. added_tokens: Dict[str, int]
  246. if fname_added_tokens is not None:
  247. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  248. else:
  249. added_tokens = {}
  250. vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
  251. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  252. actual_ids = sorted(added_tokens.values())
  253. if expected_ids != actual_ids:
  254. raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
  255. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  256. self.added_tokens_list = [text for (text, idx) in items]
  257. self.vocab_size_base: int = vocab_size
  258. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  259. self.fname_tokenizer = fname_tokenizer
  260. self.fname_added_tokens = fname_added_tokens
  261. def sentencepiece_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  262. tokenizer = self.sentencepiece_tokenizer
  263. for i in range(tokenizer.vocab_size()):
  264. piece = tokenizer.id_to_piece(i)
  265. text: bytes = piece.encode("utf-8")
  266. score: float = tokenizer.get_score(i)
  267. toktype = gguf.TokenType.NORMAL
  268. if tokenizer.is_unknown(i):
  269. toktype = gguf.TokenType.UNKNOWN
  270. if tokenizer.is_control(i):
  271. toktype = gguf.TokenType.CONTROL
  272. # NOTE: I think added_tokens are user defined.
  273. # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
  274. # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
  275. if tokenizer.is_unused(i):
  276. toktype = gguf.TokenType.UNUSED
  277. if tokenizer.is_byte(i):
  278. toktype = gguf.TokenType.BYTE
  279. yield text, score, toktype
  280. def added_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  281. for text in self.added_tokens_list:
  282. score = -1000.0
  283. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  284. def all_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  285. yield from self.sentencepiece_tokens()
  286. yield from self.added_tokens()
  287. def __repr__(self) -> str:
  288. return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  289. Vocab = Union[BpeVocab, SentencePieceVocab]
  290. #
  291. # data loading
  292. # TODO: reuse (probably move to gguf.py?)
  293. #
  294. def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
  295. #print( "permute debug " + str(weights.shape[0]) + " x " + str(weights.shape[1]) + " nhead " + str(n_head) + " nheadkv " + str(n_kv_head) )
  296. if n_head_kv is not None and n_head != n_head_kv:
  297. n_head //= n_head_kv
  298. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  299. .swapaxes(1, 2)
  300. .reshape(weights.shape))
  301. class Tensor(metaclass=ABCMeta):
  302. data_type: DataType
  303. @abstractmethod
  304. def astype(self, data_type: DataType) -> 'Tensor': ...
  305. @abstractmethod
  306. def permute(self, n_head: int, n_head_kv: int) -> 'Tensor': ...
  307. @abstractmethod
  308. def permute_part(self, n_part: int, n_head: int) -> 'UnquantizedTensor': ...
  309. @abstractmethod
  310. def part(self, n_part: int) -> 'UnquantizedTensor': ...
  311. @abstractmethod
  312. def to_ggml(self) -> 'GGMLCompatibleTensor': ...
  313. def bf16_to_fp32(bf16_arr: np.ndarray) -> np.ndarray:
  314. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  315. fp32_arr = bf16_arr.astype(np.uint32) << 16
  316. return fp32_arr.view(np.float32)
  317. class UnquantizedTensor(Tensor):
  318. def __init__(self, ndarray: NDArray) -> None:
  319. assert isinstance(ndarray, np.ndarray)
  320. self.ndarray = ndarray
  321. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  322. def astype(self, data_type: DataType) -> Tensor:
  323. dtype = DATA_TYPE_TO_NUMPY[data_type]
  324. if self.data_type == DT_BF16:
  325. self.ndarray = bf16_to_fp32(self.ndarray)
  326. return UnquantizedTensor(self.ndarray.astype(dtype))
  327. def to_ggml(self) -> 'UnquantizedTensor':
  328. return self
  329. def permute_part(self, n_part: int, n_head: int) -> 'UnquantizedTensor':
  330. r = self.ndarray.shape[0] // 3
  331. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head))
  332. def part(self, n_part: int) -> 'UnquantizedTensor':
  333. r = self.ndarray.shape[0] // 3
  334. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  335. def permute(self, n_head: int, n_head_kv: int) -> 'UnquantizedTensor':
  336. return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
  337. def load_unquantized(lazy_tensor: 'LazyTensor', expected_dtype: Any = None, convert: bool = False) -> NDArray:
  338. tensor = lazy_tensor.load()
  339. assert isinstance(tensor, UnquantizedTensor)
  340. # double-check:
  341. actual_shape = list(tensor.ndarray.shape)
  342. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  343. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  344. if convert:
  345. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  346. else:
  347. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  348. return tensor.ndarray
  349. GGMLCompatibleTensor = Union[UnquantizedTensor]
  350. class DeferredPermutedTensor(Tensor):
  351. def __init__(self, base: Tensor, n_head: int, n_head_kv: int) -> None:
  352. self.base = base
  353. self.n_head = n_head
  354. self.data_type = self.base.data_type
  355. def astype(self, data_type: DataType) -> Tensor:
  356. return self.base.astype(data_type).permute(self.n_head, self.n_head_kv)
  357. def to_ggml(self) -> GGMLCompatibleTensor:
  358. return self.base.to_ggml().permute(self.n_head, self.n_head_kv)
  359. def permute(self, n_head: int, n_head_kv: int) -> Tensor:
  360. raise Exception("shouldn't permute twice")
  361. @dataclass
  362. class LazyTensor:
  363. _load: Callable[[], Tensor]
  364. shape: List[int]
  365. data_type: DataType
  366. description: str
  367. def load(self) -> Tensor:
  368. ret = self._load()
  369. assert ret.data_type == self.data_type, (self.data_type, ret.data_type, self.description)
  370. return ret
  371. def astype(self, data_type: DataType) -> 'LazyTensor':
  372. self.validate_conversion_to(data_type)
  373. def load() -> Tensor:
  374. return self.load().astype(data_type)
  375. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  376. def validate_conversion_to(self, data_type: DataType) -> None:
  377. if data_type == self.data_type:
  378. return
  379. LazyModel = Dict[str, LazyTensor]
  380. @dataclass
  381. class ModelPlus:
  382. model: LazyModel
  383. paths: List[Path] # Where this was read from.
  384. format: Literal['ggml', 'torch', 'safetensors']
  385. vocab: Optional[Vocab] # For GGML models (which have vocab built in), the vocab.
  386. def merge_sharded(models: List[LazyModel]) -> LazyModel:
  387. # Original LLaMA models have each file contain one part of each tensor.
  388. # Use a dict instead of a set to preserve order.
  389. names = {name: None for model in models for name in model}
  390. def convert(name: str) -> LazyTensor:
  391. lazy_tensors: List[LazyTensor] = [model[name] for model in models]
  392. if len(lazy_tensors) == 1:
  393. # only one file; don't go through this procedure since there might
  394. # be quantized tensors
  395. return lazy_tensors[0]
  396. if len(lazy_tensors[0].shape) == 1:
  397. # the tensor is just duplicated in every file
  398. return lazy_tensors[0]
  399. if name.startswith('tok_embeddings.') or \
  400. name.endswith('.attention.wo.weight') or \
  401. name.endswith('.feed_forward.w2.weight'):
  402. # split by columns
  403. axis = 1
  404. else:
  405. # split by rows
  406. axis = 0
  407. concatenated_shape = list(lazy_tensors[0].shape)
  408. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  409. def load() -> UnquantizedTensor:
  410. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  411. concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
  412. return UnquantizedTensor(concatenated)
  413. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  414. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  415. return {name: convert(name) for name in names}
  416. def merge_multifile_models(models_plus: List[ModelPlus]) -> ModelPlus:
  417. formats = set(mp.format for mp in models_plus)
  418. assert len(formats) == 1, "different formats?"
  419. format = formats.pop()
  420. paths = [path for mp in models_plus for path in mp.paths]
  421. # Use the first non-None vocab, if any.
  422. try:
  423. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  424. except StopIteration:
  425. vocab = None
  426. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  427. # Transformers models put different tensors in different files, but
  428. # don't split indivdual tensors between files.
  429. model: LazyModel = {}
  430. for mp in models_plus:
  431. model.update(mp.model)
  432. else:
  433. model = merge_sharded([mp.model for mp in models_plus])
  434. return ModelPlus(model, paths, format, vocab)
  435. def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
  436. def load() -> Tensor:
  437. return lazy_tensor.load().permute(n_head, n_head_kv)
  438. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  439. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int) -> LazyTensor:
  440. def load() -> Tensor:
  441. return lazy_tensor.load().permute_part(n_part, n_head)
  442. s = lazy_tensor.shape.copy()
  443. s[0] = s[0] // 3
  444. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}) ' + lazy_tensor.description)
  445. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  446. def load() -> Tensor:
  447. return lazy_tensor.load().part(n_part)
  448. s = lazy_tensor.shape.copy()
  449. s[0] = s[0] // 3
  450. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  451. # Functionality that simulates `torch.load` but where individual tensors are
  452. # only loaded into memory on demand, not all at once.
  453. # PyTorch can't do this natively as of time of writing:
  454. # - https://github.com/pytorch/pytorch/issues/64327
  455. # This allows us to de-shard without multiplying RAM usage, and also
  456. # conveniently drops the PyTorch dependency (though we still need numpy).
  457. @dataclass
  458. class LazyStorageKind:
  459. data_type: DataType
  460. @dataclass
  461. class LazyStorage:
  462. load: Callable[[int, int], NDArray]
  463. kind: LazyStorageKind
  464. description: str
  465. class LazyUnpickler(pickle.Unpickler):
  466. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  467. super().__init__(fp)
  468. self.data_base_path = data_base_path
  469. self.zip_file = zip_file
  470. def persistent_load(self, pid: Any) -> Any:
  471. assert pid[0] == 'storage'
  472. assert isinstance(pid[1], LazyStorageKind)
  473. data_type = pid[1].data_type
  474. filename_stem = pid[2]
  475. filename = self.data_base_path + '/' + filename_stem
  476. info = self.zip_file.getinfo(filename)
  477. def load(offset: int, elm_count: int) -> NDArray:
  478. dtype = DATA_TYPE_TO_NUMPY.get(data_type)
  479. if dtype is None:
  480. raise Exception("tensor stored in unsupported format")
  481. fp = self.zip_file.open(info)
  482. fp.seek(offset * dtype.itemsize)
  483. size = elm_count * dtype.itemsize
  484. data = fp.read(size)
  485. assert len(data) == size
  486. return np.frombuffer(data, dtype)
  487. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  488. return LazyStorage(load=load, kind=pid[1], description=description)
  489. # @staticmethod
  490. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  491. # pyright: ignore[reportSelfClsParameterName]
  492. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  493. assert isinstance(storage, LazyStorage)
  494. def load() -> UnquantizedTensor:
  495. elm_count = stride[0] * size[0]
  496. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  497. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  498. return LazyTensor(load, list(size), storage.kind.data_type, description)
  499. # @staticmethod
  500. def rebuild_from_type_v2(func, new_type, args, state):
  501. return func(*args)
  502. CLASSES: Dict[Any, Any] = {
  503. ('torch._tensor', '_rebuild_from_type_v2'): rebuild_from_type_v2,
  504. ('torch._utils', '_rebuild_tensor_v2'): lazy_rebuild_tensor_v2,
  505. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  506. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  507. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  508. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  509. ('torch', 'Tensor'): LazyTensor,
  510. }
  511. def find_class(self, module: str, name: str) -> Any:
  512. if not module.startswith('torch'):
  513. return super().find_class(module, name)
  514. return self.CLASSES[(module, name)]
  515. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  516. zf = zipfile.ZipFile(outer_fp)
  517. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  518. assert len(pickle_paths) == 1, pickle_paths
  519. pickle_fp = zf.open(pickle_paths[0], 'r')
  520. unpickler = LazyUnpickler(pickle_fp,
  521. data_base_path=pickle_paths[0][:-4],
  522. zip_file=zf)
  523. model = unpickler.load()
  524. as_dict = dict(model.items())
  525. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  526. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  527. header_size, = struct.unpack('<Q', fp.read(8))
  528. header: Dict[str, Dict[str, Any]] = json.loads(fp.read(header_size))
  529. # Use mmap for the actual data to avoid race conditions with the file offset.
  530. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  531. byte_buf = mapped[8 + header_size:]
  532. def convert(info: Dict[str, Any]) -> LazyTensor:
  533. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  534. numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
  535. shape: List[int] = info['shape']
  536. begin, end = info['data_offsets']
  537. assert 0 <= begin <= end <= len(byte_buf)
  538. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  539. buf = byte_buf[begin:end]
  540. def load() -> UnquantizedTensor:
  541. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  542. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  543. return LazyTensor(load, shape, data_type, description)
  544. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  545. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  546. def must_read(fp: IO[bytes], length: int) -> bytes:
  547. ret = fp.read(length)
  548. if len(ret) < length:
  549. raise Exception("unexpectedly reached end of file")
  550. return ret
  551. @functools.lru_cache(maxsize=None)
  552. def lazy_load_file(path: Path) -> ModelPlus:
  553. fp = open(path, 'rb')
  554. first8 = fp.read(8)
  555. fp.seek(0)
  556. if first8[:2] == b'PK':
  557. # A zip file, i.e. PyTorch format
  558. return lazy_load_torch_file(fp, path)
  559. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  560. # Probably safetensors
  561. return lazy_load_safetensors_file(fp, path)
  562. else:
  563. raise ValueError(f"unknown format: {path}")
  564. In = TypeVar('In')
  565. Out = TypeVar('Out')
  566. def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int) -> Iterable[Out]:
  567. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  568. fast enough, this will stop calling `func` at some point rather than
  569. letting results pile up in memory. Specifically, there is a max of one
  570. output value buffered per thread.'''
  571. with concurrent.futures.ThreadPoolExecutor() as executor:
  572. futures: List[concurrent.futures.Future[Out]] = []
  573. items_rev = list(iterable)[::-1]
  574. for i in range(min(concurrency, len(items_rev))):
  575. futures.append(executor.submit(func, items_rev.pop()))
  576. while futures:
  577. result = futures.pop(0).result()
  578. if items_rev:
  579. futures.append(executor.submit(func, items_rev.pop()))
  580. yield result
  581. def check_vocab_size(params: Params, vocab: Vocab) -> None:
  582. if params.n_vocab != vocab.vocab_size:
  583. assert isinstance(vocab, BpeVocab) or isinstance(vocab, SentencePieceVocab)
  584. if params.n_vocab == vocab.vocab_size_base:
  585. print("Ignoring added_tokens.json since model matches vocab size without it.")
  586. vocab.added_tokens_list = []
  587. vocab.vocab_size = vocab.vocab_size_base
  588. return
  589. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
  590. if vocab.fname_added_tokens is not None:
  591. msg += f" combined with {vocab.fname_added_tokens}"
  592. msg += f" has {vocab.vocab_size})."
  593. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
  594. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  595. raise Exception(msg)
  596. class OutputFile:
  597. def __init__(self, fname_out: Path) -> None:
  598. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
  599. def add_meta_arch(self, params: Params) -> None:
  600. name = "LLaMA"
  601. if (params.n_ctx == 4096):
  602. name = "LLaMA v2"
  603. if params.path_model:
  604. name = str(params.path_model.parent).split('/')[-1]
  605. self.gguf.add_name (name)
  606. self.gguf.add_context_length (params.n_ctx)
  607. self.gguf.add_embedding_length (params.n_embd)
  608. self.gguf.add_block_count (params.n_layer)
  609. self.gguf.add_feed_forward_length (params.n_ff)
  610. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  611. self.gguf.add_head_count (params.n_head)
  612. self.gguf.add_head_count_kv (params.n_head_kv)
  613. self.gguf.add_layer_norm_rms_eps (params.f_norm_eps)
  614. if params.f_rope_freq_base:
  615. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  616. if params.ftype:
  617. self.gguf.add_file_type(params.ftype)
  618. def add_meta_vocab(self, vocab: Vocab) -> None:
  619. tokens = []
  620. scores = []
  621. toktypes = []
  622. # NOTE: `all_tokens` returns the the base vocabulary and added tokens
  623. # TODO: add special tokens?
  624. for text, score, toktype in vocab.all_tokens():
  625. tokens.append(text)
  626. scores.append(score)
  627. toktypes.append(toktype)
  628. self.gguf.add_tokenizer_model("llama")
  629. self.gguf.add_token_list(tokens)
  630. self.gguf.add_token_scores(scores)
  631. self.gguf.add_token_types(toktypes)
  632. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  633. n_elements = 1
  634. for dim in tensor.shape:
  635. n_elements *= dim
  636. data_type = DATA_TYPE_TO_NUMPY[tensor.data_type]
  637. data_nbytes = n_elements * data_type.itemsize
  638. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes)
  639. def write_meta(self) -> None:
  640. self.gguf.write_header_to_file()
  641. self.gguf.write_kv_data_to_file()
  642. def write_tensor_info(self) -> None:
  643. self.gguf.write_ti_data_to_file()
  644. def close(self) -> None:
  645. self.gguf.close()
  646. @staticmethod
  647. def write_vocab_only(fname_out: Path, params: Params, vocab: Vocab) -> None:
  648. check_vocab_size(params, vocab)
  649. of = OutputFile(fname_out)
  650. # meta data
  651. of.add_meta_arch(params)
  652. of.add_meta_vocab(vocab)
  653. of.write_meta()
  654. of.close()
  655. @staticmethod
  656. def write_all(fname_out: Path, params: Params, model: LazyModel, vocab: Vocab) -> None:
  657. check_vocab_size(params, vocab)
  658. of = OutputFile(fname_out)
  659. # meta data
  660. of.add_meta_arch(params)
  661. of.add_meta_vocab(vocab)
  662. # tensor info
  663. for name, lazy_tensor in model.items():
  664. of.add_tensor_info(name, lazy_tensor)
  665. of.write_meta()
  666. of.write_tensor_info()
  667. def do_item(item: Tuple[str, LazyTensor]) -> NDArray:
  668. name, lazy_tensor = item
  669. return lazy_tensor.load().to_ggml().ndarray
  670. # tensor data
  671. ndarrays = bounded_parallel_map(do_item, model.items(), concurrency=8)
  672. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  673. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  674. padi = len(str(len(model)))
  675. print(f"[{i+1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type}")
  676. of.gguf.write_tensor_data(ndarray)
  677. of.close()
  678. def pick_output_type(model: LazyModel, output_type_str: Optional[str]) -> GGMLFileType:
  679. wq_type = model[NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0)+".weight"].data_type
  680. if output_type_str == "f32" or (output_type_str is None and wq_type == DT_F32):
  681. return GGMLFileType.AllF32
  682. if output_type_str == "f16" or (output_type_str is None and wq_type in (DT_F16, DT_BF16)):
  683. return GGMLFileType.MostlyF16
  684. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  685. raise Exception(f"Unexpected combination of types: {name_to_type}")
  686. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  687. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  688. for (name, tensor) in model.items()}
  689. def convert_model_names(model: LazyModel, params: Params) -> LazyModel:
  690. tmap = gguf.get_tensor_name_map(ARCH, params.n_layer)
  691. tmp = model
  692. # HF models permut or pack some of the tensors, so we need to undo that
  693. for i in itertools.count():
  694. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  695. print(f"Permuting layer {i}")
  696. tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.q_proj.weight"], params.n_head, params.n_head)
  697. tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.k_proj.weight"], params.n_head, params.n_head_kv)
  698. #tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  699. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  700. print(f"Unpacking and permuting layer {i}")
  701. tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 0, params.n_head, params.n_head)
  702. tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 1, params.n_head, params.n_head_kv)
  703. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  704. else:
  705. break
  706. out: LazyModel = {}
  707. for name, lazy_tensor in model.items():
  708. name_new = name
  709. if name in tmap:
  710. name_new = tmap[name]
  711. elif name.endswith(".weight") and name[:-7] in tmap:
  712. name_new = tmap[name[:-7]] + ".weight"
  713. elif name.endswith(".bias") and name[:-5] in tmap:
  714. name_new = tmap[name[:-5]] + ".bias"
  715. else:
  716. raise Exception(f"Unexpected tensor name: {name}")
  717. if gguf.should_skip_tensor_TMP(ARCH, params.n_layer, name_new):
  718. print(f"skipping tensor {name_new}")
  719. continue
  720. else:
  721. print(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type} | {lazy_tensor.shape}")
  722. out[name_new] = lazy_tensor
  723. return out
  724. def nth_multifile_path(path: Path, n: int) -> Optional[Path]:
  725. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  726. the nth path in the model.
  727. '''
  728. # Support the following patterns:
  729. patterns: List[Tuple[str, str]] = [
  730. # - x.00.pth, x.01.pth, etc.
  731. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  732. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  733. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  734. # x.bin, x.bin.1, etc.
  735. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  736. ]
  737. for regex, replacement in patterns:
  738. if re.search(regex, path.name):
  739. new_path = path.with_name(re.sub(regex, replacement, path.name))
  740. if new_path.exists():
  741. return new_path
  742. return None
  743. def find_multifile_paths(path: Path) -> List[Path]:
  744. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  745. the whole list of paths in the model.
  746. '''
  747. ret: List[Path] = []
  748. for i in itertools.count():
  749. nth_path = nth_multifile_path(path, i)
  750. if nth_path is None:
  751. break
  752. ret.append(nth_path)
  753. if not ret:
  754. # No matches. This should only happen if the file was named, e.g.,
  755. # foo.0, and there was no file named foo. Oh well, try to process it
  756. # as a single file.
  757. return [path]
  758. return ret
  759. def load_some_model(path: Path) -> ModelPlus:
  760. '''Load a model of any supported format.'''
  761. # Be extra-friendly and accept either a file or a directory:
  762. if path.is_dir():
  763. # Check if it's a set of safetensors files first
  764. files = list(path.glob("model-00001-of-*.safetensors"))
  765. if not files:
  766. # Try the PyTorch patterns too, with lower priority
  767. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  768. files = [file for glob in globs for file in path.glob(glob)]
  769. if not files:
  770. raise Exception(f"Can't find model in directory {path}")
  771. if len(files) > 1:
  772. raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
  773. path = files[0]
  774. paths = find_multifile_paths(path)
  775. models_plus: List[ModelPlus] = []
  776. for path in paths:
  777. print(f"Loading model file {path}")
  778. models_plus.append(lazy_load_file(path))
  779. model_plus = merge_multifile_models(models_plus)
  780. return model_plus
  781. def load_vocab(path: Path, vocabtype: Optional[str]) -> Union[BpeVocab, SentencePieceVocab]:
  782. # Be extra-friendly and accept either a file or a directory. Also, if it's
  783. # a directory, it might be the model directory, and tokenizer.model might
  784. # be in the parent of that.
  785. if path.is_dir():
  786. vocab_file = "tokenizer.model"
  787. if vocabtype == 'bpe':
  788. vocab_file = "vocab.json"
  789. path2 = path / vocab_file
  790. # Use `.parent` instead of /.. to handle the symlink case better.
  791. path3 = path.parent / vocab_file
  792. if path2.exists():
  793. path = path2
  794. elif path3.exists():
  795. path = path3
  796. else:
  797. raise FileNotFoundError(
  798. f"Could not find {vocab_file} in {path} or its parent; "
  799. "if it's in another directory, pass the directory as --vocab-dir")
  800. print(f"Loading vocab file '{path}', type '{vocabtype}'")
  801. added_tokens_path = path.parent / "added_tokens.json"
  802. if vocabtype == "bpe":
  803. return BpeVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  804. elif vocabtype == "spm":
  805. return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  806. else:
  807. raise ValueError(f"Unsupported vocabulary type {vocabtype}")
  808. def default_outfile(model_paths: List[Path], file_type: GGMLFileType) -> Path:
  809. namestr = {
  810. GGMLFileType.AllF32: "f32",
  811. GGMLFileType.MostlyF16: "f16",
  812. }[file_type]
  813. ret = model_paths[0].parent / f"ggml-model-{namestr}.gguf"
  814. if ret in model_paths:
  815. sys.stderr.write(
  816. f"Error: Default output path ({ret}) would overwrite the input. "
  817. "Please explicitly specify a path using --outfile.\n")
  818. sys.exit(1)
  819. return ret
  820. def do_dump_model(model_plus: ModelPlus) -> None:
  821. print(f"model_plus.paths = {model_plus.paths!r}")
  822. print(f"model_plus.format = {model_plus.format!r}")
  823. print(f"model_plus.vocab = {model_plus.vocab!r}")
  824. for name, lazy_tensor in model_plus.model.items():
  825. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
  826. def main(args_in: Optional[List[str]] = None) -> None:
  827. parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
  828. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  829. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  830. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  831. parser.add_argument("--outtype", choices=["f32", "f16"], help="output format (default: based on input)")
  832. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  833. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  834. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
  835. parser.add_argument("--vocabtype", choices=["spm", "bpe"], help="vocab format (default: spm)", default="spm")
  836. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  837. args = parser.parse_args(args_in)
  838. if args.dump_single:
  839. model_plus = lazy_load_file(args.model)
  840. do_dump_model(model_plus)
  841. model_plus = load_some_model(args.model)
  842. params = Params.load(model_plus)
  843. if params.n_ctx == -1:
  844. if args.ctx is None:
  845. raise Exception("The model doesn't have a context size, and you didn't specify one with --ctx\n"
  846. "Please specify one with --ctx:\n"
  847. " - LLaMA v1: --ctx 2048\n"
  848. " - LLaMA v2: --ctx 4096\n")
  849. params.n_ctx = args.ctx
  850. if args.outtype:
  851. params.ftype = {
  852. "f32": GGMLFileType.AllF32,
  853. "f16": GGMLFileType.MostlyF16,
  854. }[args.outtype]
  855. print(f"params = {params}")
  856. vocab: Vocab
  857. if args.vocab_only:
  858. vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype)
  859. assert args.outfile, "need --outfile if using --vocab-only"
  860. outfile = args.outfile
  861. OutputFile.write_vocab_only(outfile, params, vocab)
  862. print(f"Wrote {outfile}")
  863. else:
  864. if args.dump:
  865. do_dump_model(model_plus)
  866. return
  867. if model_plus.vocab is not None and args.vocab_dir is None:
  868. vocab = model_plus.vocab
  869. else:
  870. vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
  871. vocab = load_vocab(vocab_dir, args.vocabtype)
  872. model = model_plus.model
  873. model = convert_model_names(model, params)
  874. ftype = pick_output_type(model, args.outtype)
  875. model = convert_to_output_type(model, ftype)
  876. outfile = args.outfile or default_outfile(model_plus.paths, ftype)
  877. params.ftype = ftype
  878. print(f"Writing {outfile}, format {ftype}")
  879. OutputFile.write_all(outfile, params, model, vocab)
  880. print(f"Wrote {outfile}")
  881. if __name__ == '__main__':
  882. main()