convert.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import logging
  4. import argparse
  5. import concurrent.futures
  6. import enum
  7. import faulthandler
  8. import functools
  9. import itertools
  10. import json
  11. import math
  12. import mmap
  13. import os
  14. import pickle
  15. import re
  16. import signal
  17. import struct
  18. import sys
  19. import textwrap
  20. import time
  21. import zipfile
  22. from abc import ABC, abstractmethod
  23. from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
  24. from dataclasses import dataclass
  25. from pathlib import Path
  26. from typing import TYPE_CHECKING, Any, Callable, ClassVar, IO, Iterable, Literal, Protocol, TypeVar, runtime_checkable
  27. import numpy as np
  28. from sentencepiece import SentencePieceProcessor
  29. if 'NO_LOCAL_GGUF' not in os.environ:
  30. sys.path.insert(1, str(Path(__file__).parent / 'gguf-py'))
  31. import gguf
  32. if TYPE_CHECKING:
  33. from typing_extensions import Self, TypeAlias
  34. logger = logging.getLogger("convert")
  35. if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
  36. faulthandler.register(signal.SIGUSR1)
  37. NDArray: TypeAlias = 'np.ndarray[Any, Any]'
  38. ARCH = gguf.MODEL_ARCH.LLAMA
  39. DEFAULT_CONCURRENCY = 8
  40. ADDED_TOKENS_FILE = 'added_tokens.json'
  41. FAST_TOKENIZER_FILE = 'tokenizer.json'
  42. #
  43. # data types
  44. #
  45. @dataclass(frozen=True)
  46. class DataType:
  47. name: str
  48. dtype: np.dtype[Any]
  49. valid_conversions: list[str]
  50. def elements_to_bytes(self, n_elements: int) -> int:
  51. return n_elements * self.dtype.itemsize
  52. @dataclass(frozen=True)
  53. class UnquantizedDataType(DataType):
  54. pass
  55. DT_F16 = UnquantizedDataType('F16', dtype = np.dtype(np.float16), valid_conversions = ['F32', 'Q8_0'])
  56. DT_F32 = UnquantizedDataType('F32', dtype = np.dtype(np.float32), valid_conversions = ['F16', 'Q8_0'])
  57. DT_I32 = UnquantizedDataType('I32', dtype = np.dtype(np.int16), valid_conversions = [])
  58. DT_BF16 = UnquantizedDataType('BF16', dtype = np.dtype(np.uint16), valid_conversions = ['F32', 'F16', 'Q8_0'])
  59. @dataclass(frozen=True)
  60. class QuantizedDataType(DataType):
  61. block_size: int
  62. quantized_dtype: np.dtype[Any]
  63. ggml_type: gguf.GGMLQuantizationType
  64. def quantize(self, arr: NDArray) -> NDArray:
  65. raise NotImplementedError(f'Quantization for {self.name} not implemented')
  66. def elements_to_bytes(self, n_elements: int) -> int:
  67. assert n_elements % self.block_size == 0, f'Invalid number of elements {n_elements} for {self.name} with block size {self.block_size}'
  68. return self.quantized_dtype.itemsize * (n_elements // self.block_size)
  69. @dataclass(frozen=True)
  70. class Q8_0QuantizedDataType(QuantizedDataType):
  71. # Mini Q8_0 quantization in Python!
  72. def quantize(self, arr: NDArray) -> NDArray:
  73. assert arr.size % self.block_size == 0 and arr.size != 0, f'Bad array size {arr.size}'
  74. assert arr.dtype == np.float32, f'Bad array type {arr.dtype}'
  75. n_blocks = arr.size // self.block_size
  76. blocks = arr.reshape((n_blocks, self.block_size))
  77. # Much faster implementation of block quantization contributed by @Cebtenzzre
  78. def quantize_blocks_q8_0(blocks: NDArray) -> Iterable[tuple[Any, Any]]:
  79. d = abs(blocks).max(axis = 1) / np.float32(127)
  80. with np.errstate(divide = 'ignore'):
  81. qs = (blocks / d[:, None]).round()
  82. qs[d == 0] = 0
  83. yield from zip(d, qs)
  84. return np.fromiter(quantize_blocks_q8_0(blocks), count = n_blocks, dtype = self.quantized_dtype)
  85. DT_Q8_0 = Q8_0QuantizedDataType('Q8_0',
  86. dtype = np.dtype(np.float32), valid_conversions = [],
  87. ggml_type = gguf.GGMLQuantizationType.Q8_0, block_size = 32,
  88. quantized_dtype = np.dtype([('d', '<f2'), ('qs', 'i1', (32,))]))
  89. # Quantized types skipped here because they may also map to np.float32
  90. NUMPY_TYPE_TO_DATA_TYPE: dict[np.dtype[Any], DataType] = {}
  91. for dt in (DT_BF16, DT_F16, DT_F32, DT_I32):
  92. if dt.dtype in NUMPY_TYPE_TO_DATA_TYPE:
  93. raise ValueError(f'Invalid duplicate data type {dt}')
  94. NUMPY_TYPE_TO_DATA_TYPE[dt.dtype] = dt
  95. SAFETENSORS_DATA_TYPES: dict[str, DataType] = {
  96. 'BF16': DT_BF16,
  97. 'F16': DT_F16,
  98. 'F32': DT_F32,
  99. 'I32': DT_I32,
  100. }
  101. # TODO: match this with `llama_ftype`
  102. # TODO: rename to LLAMAFileType
  103. # TODO: move to `gguf.py`
  104. class GGMLFileType(enum.IntEnum):
  105. AllF32 = 0
  106. MostlyF16 = 1 # except 1d tensors
  107. MostlyQ8_0 = 7 # except 1d tensors
  108. def type_for_tensor(self, name: str, tensor: LazyTensor) -> DataType:
  109. dt = GGML_FILE_TYPE_TO_DATA_TYPE.get(self)
  110. if dt is None:
  111. raise ValueError(self)
  112. # Convert all 1D tensors to F32. Most of the codebase that takes in 1D tensors only handles F32 tensors, and most of the outputs tensors are F32.
  113. # Also The 1d tensors aren't much of a performance/size issue. So instead of having to have separate F32 and F16 implementations of both, just convert everything to F32 for now.
  114. return dt if len(tensor.shape) > 1 else DT_F32
  115. GGML_FILE_TYPE_TO_DATA_TYPE: dict[GGMLFileType, DataType] = {
  116. GGMLFileType.AllF32 : DT_F32,
  117. GGMLFileType.MostlyF16 : DT_F16,
  118. GGMLFileType.MostlyQ8_0: DT_Q8_0,
  119. }
  120. #
  121. # hparams loading
  122. #
  123. @dataclass
  124. class Params:
  125. n_vocab: int
  126. n_embd: int
  127. n_layer: int
  128. n_ctx: int
  129. n_ff: int
  130. n_head: int
  131. n_head_kv: int
  132. n_experts: int | None = None
  133. n_experts_used: int | None = None
  134. f_norm_eps: float | None = None
  135. rope_scaling_type: gguf.RopeScalingType | None = None
  136. f_rope_freq_base: float | None = None
  137. f_rope_scale: float | None = None
  138. n_orig_ctx: int | None = None
  139. rope_finetuned: bool | None = None
  140. ftype: GGMLFileType | None = None
  141. # path to the directory containing the model files
  142. path_model: Path | None = None
  143. @staticmethod
  144. def guessed(model: LazyModel) -> Params:
  145. # try transformer naming first
  146. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  147. # try transformer naming first
  148. if "model.layers.0.self_attn.q_proj.weight" in model:
  149. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  150. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  151. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  152. else:
  153. n_layer = next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  154. if n_layer < 1:
  155. msg = """\
  156. failed to guess 'n_layer'. This model is unknown or unsupported.
  157. Suggestion: provide 'config.json' of the model in the same directory containing model files."""
  158. raise KeyError(textwrap.dedent(msg))
  159. n_head = n_embd // 128 # guessed
  160. n_mult = 256 # guessed
  161. # TODO: verify this
  162. n_ff = int(2 * (4 * n_embd) / 3)
  163. n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
  164. return Params(
  165. n_vocab = n_vocab,
  166. n_embd = n_embd,
  167. n_layer = n_layer,
  168. n_ctx = -1,
  169. n_ff = n_ff,
  170. n_head = n_head,
  171. n_head_kv = n_head,
  172. f_norm_eps = 1e-5,
  173. )
  174. @staticmethod
  175. def loadHFTransformerJson(model: LazyModel, config_path: Path) -> Params:
  176. with open(config_path) as f:
  177. config = json.load(f)
  178. rope_scaling_type = f_rope_scale = n_orig_ctx = rope_finetuned = None
  179. rope_scaling = config.get("rope_scaling")
  180. if rope_scaling is not None and (typ := rope_scaling.get("type")):
  181. rope_factor = rope_scaling.get("factor")
  182. f_rope_scale = rope_factor
  183. if typ == "linear":
  184. rope_scaling_type = gguf.RopeScalingType.LINEAR
  185. elif typ == "yarn":
  186. rope_scaling_type = gguf.RopeScalingType.YARN
  187. n_orig_ctx = rope_scaling['original_max_position_embeddings']
  188. rope_finetuned = rope_scaling['finetuned']
  189. else:
  190. raise NotImplementedError(f'Unknown rope scaling type: {typ}')
  191. if "max_sequence_length" in config:
  192. n_ctx = config["max_sequence_length"]
  193. elif "max_position_embeddings" in config:
  194. n_ctx = config["max_position_embeddings"]
  195. else:
  196. msg = """\
  197. failed to guess 'n_ctx'. This model is unknown or unsupported.
  198. Suggestion: provide 'config.json' of the model in the same directory containing model files."""
  199. raise KeyError(textwrap.dedent(msg))
  200. n_experts = None
  201. n_experts_used = None
  202. if "num_local_experts" in config:
  203. n_experts = config["num_local_experts"]
  204. n_experts_used = config["num_experts_per_tok"]
  205. return Params(
  206. n_vocab = config["vocab_size"],
  207. n_embd = config["hidden_size"],
  208. n_layer = config["num_hidden_layers"],
  209. n_ctx = n_ctx,
  210. n_ff = config["intermediate_size"],
  211. n_head = (n_head := config["num_attention_heads"]),
  212. n_head_kv = config.get("num_key_value_heads", n_head),
  213. n_experts = n_experts,
  214. n_experts_used = n_experts_used,
  215. f_norm_eps = config["rms_norm_eps"],
  216. f_rope_freq_base = config.get("rope_theta"),
  217. rope_scaling_type = rope_scaling_type,
  218. f_rope_scale = f_rope_scale,
  219. n_orig_ctx = n_orig_ctx,
  220. rope_finetuned = rope_finetuned,
  221. )
  222. # LLaMA v2 70B params.json
  223. # {"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}
  224. @staticmethod
  225. def loadOriginalParamsJson(model: LazyModel, config_path: Path) -> Params:
  226. with open(config_path) as f:
  227. config = json.load(f)
  228. n_experts = None
  229. n_experts_used = None
  230. f_rope_freq_base = None
  231. n_ff = None
  232. # hack to determine LLaMA v1 vs v2 vs CodeLlama
  233. if config.get("moe"):
  234. # Mixtral
  235. n_ctx = 32768
  236. elif config.get("rope_theta") == 1000000:
  237. # CodeLlama
  238. n_ctx = 16384
  239. elif config["norm_eps"] == 1e-05:
  240. # LLaMA v2
  241. n_ctx = 4096
  242. else:
  243. # LLaMA v1
  244. n_ctx = 2048
  245. if "layers.0.feed_forward.w1.weight" in model:
  246. n_ff = model["layers.0.feed_forward.w1.weight"].shape[0]
  247. if config.get("moe"):
  248. n_ff = model["layers.0.feed_forward.experts.0.w1.weight"].shape[0]
  249. n_experts = config["moe"]["num_experts"]
  250. n_experts_used = config["moe"]["num_experts_per_tok"]
  251. f_rope_freq_base = 1e6
  252. assert n_ff is not None
  253. return Params(
  254. n_vocab = model["tok_embeddings.weight"].shape[0],
  255. n_embd = config["dim"],
  256. n_layer = config["n_layers"],
  257. n_ctx = n_ctx,
  258. n_ff = n_ff,
  259. n_head = (n_head := config["n_heads"]),
  260. n_head_kv = config.get("n_kv_heads", n_head),
  261. n_experts = n_experts,
  262. n_experts_used = n_experts_used,
  263. f_norm_eps = config["norm_eps"],
  264. f_rope_freq_base = config.get("rope_theta", f_rope_freq_base),
  265. )
  266. @staticmethod
  267. def load(model_plus: ModelPlus) -> Params:
  268. hf_config_path = model_plus.paths[0].parent / "config.json"
  269. orig_config_path = model_plus.paths[0].parent / "params.json"
  270. if hf_config_path.exists():
  271. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  272. elif orig_config_path.exists():
  273. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  274. elif model_plus.format != 'none':
  275. params = Params.guessed(model_plus.model)
  276. else:
  277. raise ValueError('Cannot guess params when model format is none')
  278. params.path_model = model_plus.paths[0].parent
  279. return params
  280. #
  281. # vocab
  282. #
  283. @runtime_checkable
  284. class BaseVocab(Protocol):
  285. tokenizer_model: ClassVar[str]
  286. name: ClassVar[str]
  287. class NoVocab(BaseVocab):
  288. tokenizer_model = "no_vocab"
  289. name = "no_vocab"
  290. def __repr__(self) -> str:
  291. return "<NoVocab for a model without integrated vocabulary>"
  292. @runtime_checkable
  293. class Vocab(BaseVocab, Protocol):
  294. vocab_size: int
  295. added_tokens_dict: dict[str, int]
  296. added_tokens_list: list[str]
  297. fname_tokenizer: Path
  298. def __init__(self, base_path: Path): ...
  299. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]: ...
  300. class BpeVocab(Vocab):
  301. tokenizer_model = "gpt2"
  302. name = "bpe"
  303. def __init__(self, base_path: Path):
  304. added_tokens: dict[str, int] = {}
  305. if (fname_tokenizer := base_path / 'vocab.json').exists():
  306. # "slow" tokenizer
  307. with open(fname_tokenizer, encoding="utf-8") as f:
  308. self.vocab = json.load(f)
  309. try:
  310. # FIXME: Verify that added tokens here _cannot_ overlap with the main vocab.
  311. with open(base_path / ADDED_TOKENS_FILE, encoding="utf-8") as f:
  312. added_tokens = json.load(f)
  313. except FileNotFoundError:
  314. pass
  315. else:
  316. # "fast" tokenizer
  317. fname_tokenizer = base_path / FAST_TOKENIZER_FILE
  318. # if this fails, FileNotFoundError propagates to caller
  319. with open(fname_tokenizer, encoding="utf-8") as f:
  320. tokenizer_json = json.load(f)
  321. tokenizer_model: dict[str, Any] = tokenizer_json['model']
  322. if (
  323. tokenizer_model['type'] != 'BPE' or tokenizer_model.get('byte_fallback', False)
  324. or tokenizer_json['decoder']['type'] != 'ByteLevel'
  325. ):
  326. raise FileNotFoundError('Cannot find GPT-2 BPE tokenizer')
  327. self.vocab = tokenizer_model["vocab"]
  328. if (added := tokenizer_json.get('added_tokens')) is not None:
  329. # Added tokens here can be duplicates of the main vocabulary.
  330. added_tokens = {item['content']: item['id']
  331. for item in added
  332. if item['content'] not in self.vocab}
  333. vocab_size = len(self.vocab)
  334. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  335. actual_ids = sorted(added_tokens.values())
  336. if expected_ids != actual_ids:
  337. expected_end_id = vocab_size + len(actual_ids) - 1
  338. raise ValueError(f"Expected the {len(actual_ids)} added token ID(s) to be sequential in the range "
  339. f"{vocab_size} - {expected_end_id}; got {actual_ids}")
  340. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  341. self.added_tokens_dict = added_tokens
  342. self.added_tokens_list = [text for (text, idx) in items]
  343. self.vocab_size_base = vocab_size
  344. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  345. self.fname_tokenizer = fname_tokenizer
  346. def bpe_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  347. reverse_vocab = {id: encoded_tok for encoded_tok, id in self.vocab.items()}
  348. for i, _ in enumerate(self.vocab):
  349. yield reverse_vocab[i], 0.0, gguf.TokenType.NORMAL
  350. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  351. for text in self.added_tokens_list:
  352. score = -1000.0
  353. yield text.encode("utf-8"), score, gguf.TokenType.CONTROL
  354. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  355. yield from self.bpe_tokens()
  356. yield from self.added_tokens()
  357. def __repr__(self) -> str:
  358. return f"<BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  359. class SentencePieceVocab(Vocab):
  360. tokenizer_model = "llama"
  361. name = "spm"
  362. def __init__(self, base_path: Path):
  363. added_tokens: dict[str, int] = {}
  364. if (fname_tokenizer := base_path / 'tokenizer.model').exists():
  365. # normal location
  366. try:
  367. with open(base_path / ADDED_TOKENS_FILE, encoding="utf-8") as f:
  368. added_tokens = json.load(f)
  369. except FileNotFoundError:
  370. pass
  371. elif not (fname_tokenizer := base_path.parent / 'tokenizer.model').exists():
  372. # not found in alternate location either
  373. raise FileNotFoundError('Cannot find tokenizer.model')
  374. self.sentencepiece_tokenizer = SentencePieceProcessor()
  375. self.sentencepiece_tokenizer.LoadFromFile(str(fname_tokenizer))
  376. vocab_size = self.sentencepiece_tokenizer.vocab_size()
  377. new_tokens = {id: piece for piece, id in added_tokens.items() if id >= vocab_size}
  378. expected_new_ids = list(range(vocab_size, vocab_size + len(new_tokens)))
  379. actual_new_ids = sorted(new_tokens.keys())
  380. if expected_new_ids != actual_new_ids:
  381. raise ValueError(f"Expected new token IDs {expected_new_ids} to be sequential; got {actual_new_ids}")
  382. # Token pieces that were added to the base vocabulary.
  383. self.added_tokens_dict = added_tokens
  384. self.added_tokens_list = [new_tokens[id] for id in actual_new_ids]
  385. self.vocab_size_base = vocab_size
  386. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  387. self.fname_tokenizer = fname_tokenizer
  388. def sentencepiece_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  389. tokenizer = self.sentencepiece_tokenizer
  390. for i in range(tokenizer.vocab_size()):
  391. piece = tokenizer.IdToPiece(i)
  392. text = piece.encode("utf-8")
  393. score: float = tokenizer.GetScore(i)
  394. toktype = gguf.TokenType.NORMAL
  395. if tokenizer.IsUnknown(i):
  396. toktype = gguf.TokenType.UNKNOWN
  397. if tokenizer.IsControl(i):
  398. toktype = gguf.TokenType.CONTROL
  399. # NOTE: I think added_tokens are user defined.
  400. # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
  401. # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
  402. if tokenizer.IsUnused(i):
  403. toktype = gguf.TokenType.UNUSED
  404. if tokenizer.IsByte(i):
  405. toktype = gguf.TokenType.BYTE
  406. yield text, score, toktype
  407. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  408. for text in self.added_tokens_list:
  409. score = -1000.0
  410. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  411. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  412. yield from self.sentencepiece_tokens()
  413. yield from self.added_tokens()
  414. def __repr__(self) -> str:
  415. return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  416. class LlamaHfVocab(Vocab):
  417. tokenizer_model = "llama"
  418. name = "hfft"
  419. def __init__(self, base_path: Path):
  420. fname_tokenizer = base_path / FAST_TOKENIZER_FILE
  421. # if this fails, FileNotFoundError propagates to caller
  422. with open(fname_tokenizer, encoding='utf-8') as f:
  423. tokenizer_json = json.load(f)
  424. # pre-check so we know if we need transformers
  425. tokenizer_model: dict[str, Any] = tokenizer_json['model']
  426. is_llama3 = (
  427. tokenizer_model['type'] == 'BPE' and tokenizer_model.get('ignore_merges', False)
  428. and not tokenizer_model.get('byte_fallback', True)
  429. )
  430. if is_llama3:
  431. raise TypeError('Llama 3 must be converted with BpeVocab')
  432. if not is_llama3 and (
  433. tokenizer_model['type'] != 'BPE' or not tokenizer_model.get('byte_fallback', False)
  434. or tokenizer_json['decoder']['type'] != 'Sequence'
  435. ):
  436. raise FileNotFoundError('Cannot find Llama BPE tokenizer')
  437. try:
  438. from transformers import AutoTokenizer
  439. except ImportError as e:
  440. raise ImportError(
  441. "To use LlamaHfVocab, please install the `transformers` package. "
  442. "You can install it with `pip install transformers`."
  443. ) from e
  444. # Allow the tokenizer to default to slow or fast versions.
  445. # Explicitly set tokenizer to use local paths.
  446. self.tokenizer = AutoTokenizer.from_pretrained(
  447. base_path,
  448. cache_dir=base_path,
  449. local_files_only=True,
  450. )
  451. assert self.tokenizer.is_fast # assume tokenizer.json is used
  452. # Initialize lists and dictionaries for added tokens
  453. self.added_tokens_list = []
  454. self.added_tokens_dict = dict()
  455. self.added_tokens_ids = set()
  456. # Process added tokens
  457. for tok, tokidx in sorted(
  458. self.tokenizer.get_added_vocab().items(), key=lambda x: x[1]
  459. ):
  460. # Only consider added tokens that are not in the base vocabulary
  461. if tokidx >= self.tokenizer.vocab_size:
  462. self.added_tokens_list.append(tok)
  463. self.added_tokens_dict[tok] = tokidx
  464. self.added_tokens_ids.add(tokidx)
  465. # Store special tokens and their IDs
  466. self.specials = {
  467. tok: self.tokenizer.get_vocab()[tok]
  468. for tok in self.tokenizer.all_special_tokens
  469. }
  470. self.special_ids = set(self.tokenizer.all_special_ids)
  471. # Set vocabulary sizes
  472. self.vocab_size_base = self.tokenizer.vocab_size
  473. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  474. self.fname_tokenizer = fname_tokenizer
  475. def hf_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  476. reverse_vocab = {
  477. id: encoded_tok for encoded_tok, id in self.tokenizer.get_vocab().items()
  478. }
  479. for token_id in range(self.vocab_size_base):
  480. # Skip processing added tokens here
  481. if token_id in self.added_tokens_ids:
  482. continue
  483. # Convert token text to bytes
  484. token_text = reverse_vocab[token_id].encode("utf-8")
  485. # Yield token text, score, and type
  486. yield token_text, self.get_token_score(token_id), self.get_token_type(
  487. token_id, token_text, self.special_ids # Reuse already stored special IDs
  488. )
  489. def get_token_type(self, token_id: int, token_text: bytes, special_ids: set[int]) -> gguf.TokenType:
  490. # Special case for byte tokens
  491. if re.fullmatch(br"<0x[0-9A-Fa-f]{2}>", token_text):
  492. return gguf.TokenType.BYTE
  493. # Determine token type based on whether it's a special token
  494. return gguf.TokenType.CONTROL if token_id in special_ids else gguf.TokenType.NORMAL
  495. def get_token_score(self, token_id: int) -> float:
  496. # Placeholder for actual logic to determine the token's score
  497. # This needs to be implemented based on specific requirements
  498. return -1000.0 # Default score
  499. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  500. for text in self.added_tokens_list:
  501. if text in self.specials:
  502. toktype = self.get_token_type(self.specials[text], b'', self.special_ids)
  503. score = self.get_token_score(self.specials[text])
  504. else:
  505. toktype = gguf.TokenType.USER_DEFINED
  506. score = -1000.0
  507. yield text.encode("utf-8"), score, toktype
  508. def has_newline_token(self):
  509. return "<0x0A>" in self.tokenizer.vocab or "\n" in self.tokenizer.vocab
  510. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  511. yield from self.hf_tokens()
  512. yield from self.added_tokens()
  513. def __repr__(self) -> str:
  514. return f"<LlamaHfVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  515. #
  516. # data loading
  517. # TODO: reuse (probably move to gguf.py?)
  518. #
  519. def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
  520. if n_head_kv is not None and n_head != n_head_kv:
  521. n_head = n_head_kv
  522. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  523. .swapaxes(1, 2)
  524. .reshape(weights.shape))
  525. class Tensor(ABC):
  526. ndarray: NDArray
  527. data_type: DataType
  528. @abstractmethod
  529. def astype(self, data_type: DataType) -> Self: ...
  530. @abstractmethod
  531. def permute(self, n_head: int, n_head_kv: int) -> Self: ...
  532. @abstractmethod
  533. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> Self: ...
  534. @abstractmethod
  535. def part(self, n_part: int) -> Self: ...
  536. @abstractmethod
  537. def to_ggml(self) -> GGMLCompatibleTensor: ...
  538. def bf16_to_fp32(bf16_arr: np.ndarray[Any, np.dtype[np.uint16]]) -> NDArray:
  539. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  540. fp32_arr = bf16_arr.astype(np.uint32) << 16
  541. return fp32_arr.view(np.float32)
  542. class UnquantizedTensor(Tensor):
  543. def __init__(self, ndarray: NDArray):
  544. assert isinstance(ndarray, np.ndarray)
  545. self.ndarray = ndarray
  546. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  547. def astype(self, data_type: DataType) -> UnquantizedTensor:
  548. dtype = data_type.dtype
  549. if self.data_type == DT_BF16:
  550. self.ndarray = bf16_to_fp32(self.ndarray)
  551. return UnquantizedTensor(self.ndarray.astype(dtype))
  552. def to_ggml(self) -> Self:
  553. return self
  554. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  555. r = self.ndarray.shape[0] // 3
  556. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head, n_head_kv))
  557. def part(self, n_part: int) -> UnquantizedTensor:
  558. r = self.ndarray.shape[0] // 3
  559. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  560. def permute(self, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  561. return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
  562. def load_unquantized(lazy_tensor: LazyTensor, expected_dtype: Any = None, convert: bool = False) -> NDArray:
  563. tensor = lazy_tensor.load()
  564. assert isinstance(tensor, UnquantizedTensor)
  565. # double-check:
  566. actual_shape = list(tensor.ndarray.shape)
  567. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  568. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  569. if convert:
  570. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  571. else:
  572. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  573. return tensor.ndarray
  574. GGMLCompatibleTensor = UnquantizedTensor
  575. @dataclass
  576. class LazyTensor:
  577. _load: Callable[[], Tensor]
  578. shape: list[int]
  579. data_type: DataType
  580. description: str
  581. def load(self) -> Tensor:
  582. ret = self._load()
  583. # Should be okay if it maps to the same numpy type?
  584. assert ret.data_type == self.data_type or (self.data_type.dtype == ret.data_type.dtype), \
  585. (self.data_type, ret.data_type, self.description)
  586. return ret
  587. def astype(self, data_type: DataType) -> LazyTensor:
  588. self.validate_conversion_to(data_type)
  589. def load() -> Tensor:
  590. return self.load().astype(data_type)
  591. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  592. def validate_conversion_to(self, data_type: DataType) -> None:
  593. if data_type != self.data_type and data_type.name not in self.data_type.valid_conversions:
  594. raise ValueError(f'Cannot validate conversion from {self.data_type} to {data_type}.')
  595. LazyModel: TypeAlias = 'dict[str, LazyTensor]'
  596. @dataclass
  597. class ModelPlus:
  598. model: LazyModel
  599. paths: list[Path] # Where this was read from.
  600. format: Literal['ggml', 'torch', 'safetensors', 'none']
  601. vocab: BaseVocab | None # For GGML models (which have vocab built in), the vocab.
  602. def merge_sharded(models: list[LazyModel]) -> LazyModel:
  603. # Original LLaMA models have each file contain one part of each tensor.
  604. # Use a dict instead of a set to preserve order.
  605. names = {name: None for model in models for name in model}
  606. def convert(name: str) -> LazyTensor:
  607. lazy_tensors = [model[name] for model in models]
  608. if len(lazy_tensors) == 1:
  609. # only one file; don't go through this procedure since there might
  610. # be quantized tensors
  611. return lazy_tensors[0]
  612. if len(lazy_tensors[0].shape) == 1:
  613. # the tensor is just duplicated in every file
  614. return lazy_tensors[0]
  615. if name.startswith('tok_embeddings.') or \
  616. name.endswith('.attention.wo.weight') or \
  617. name.endswith('.feed_forward.w2.weight'):
  618. # split by columns
  619. axis = 1
  620. else:
  621. # split by rows
  622. axis = 0
  623. concatenated_shape = list(lazy_tensors[0].shape)
  624. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  625. def load() -> UnquantizedTensor:
  626. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  627. concatenated = np.concatenate(ndarrays, axis=axis)
  628. return UnquantizedTensor(concatenated)
  629. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  630. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  631. return {name: convert(name) for name in names}
  632. def merge_multifile_models(models_plus: list[ModelPlus]) -> ModelPlus:
  633. formats = set(mp.format for mp in models_plus)
  634. assert len(formats) == 1, "different formats?"
  635. format = formats.pop()
  636. paths = [path for mp in models_plus for path in mp.paths]
  637. # Use the first non-None vocab, if any.
  638. try:
  639. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  640. except StopIteration:
  641. vocab = None
  642. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  643. # Transformers models put different tensors in different files, but
  644. # don't split individual tensors between files.
  645. model: LazyModel = {}
  646. for mp in models_plus:
  647. model.update(mp.model)
  648. else:
  649. model = merge_sharded([mp.model for mp in models_plus])
  650. return ModelPlus(model, paths, format, vocab) # pytype: disable=wrong-arg-types
  651. def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
  652. def load() -> Tensor:
  653. return lazy_tensor.load().permute(n_head, n_head_kv)
  654. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  655. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int, n_head_kv: int) -> LazyTensor:
  656. def load() -> Tensor:
  657. return lazy_tensor.load().permute_part(n_part, n_head, n_head_kv)
  658. s = lazy_tensor.shape.copy()
  659. s[0] = s[0] // 3
  660. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  661. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  662. def load() -> Tensor:
  663. return lazy_tensor.load().part(n_part)
  664. s = lazy_tensor.shape.copy()
  665. s[0] = s[0] // 3
  666. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  667. def pack_experts_lazy(lazy_tensors: list[LazyTensor]) -> LazyTensor:
  668. def load() -> Tensor:
  669. tensors = [lazy_tensor.load() for lazy_tensor in lazy_tensors]
  670. return UnquantizedTensor(np.array([tensor.ndarray for tensor in tensors]))
  671. s = lazy_tensors[0].shape.copy()
  672. s.insert(0, len(lazy_tensors))
  673. return LazyTensor(load, s, lazy_tensors[0].data_type, 'pack_experts ' + ' | '.join(lt.description for lt in lazy_tensors))
  674. # Functionality that simulates `torch.load` but where individual tensors are
  675. # only loaded into memory on demand, not all at once.
  676. # PyTorch can't do this natively as of time of writing:
  677. # - https://github.com/pytorch/pytorch/issues/64327
  678. # This allows us to de-shard without multiplying RAM usage, and also
  679. # conveniently drops the PyTorch dependency (though we still need numpy).
  680. @dataclass
  681. class LazyStorageKind:
  682. data_type: DataType
  683. @dataclass
  684. class LazyStorage:
  685. load: Callable[[int, int], NDArray]
  686. kind: LazyStorageKind
  687. description: str
  688. class LazyUnpickler(pickle.Unpickler):
  689. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  690. super().__init__(fp)
  691. self.data_base_path = data_base_path
  692. self.zip_file = zip_file
  693. def persistent_load(self, pid: Any) -> Any:
  694. assert pid[0] == 'storage'
  695. assert isinstance(pid[1], LazyStorageKind)
  696. data_type = pid[1].data_type
  697. filename_stem = pid[2]
  698. filename = f'{self.data_base_path}/{filename_stem}'
  699. info = self.zip_file.getinfo(filename)
  700. def load(offset: int, elm_count: int) -> NDArray:
  701. dtype = data_type.dtype
  702. with self.zip_file.open(info) as fp:
  703. fp.seek(offset * dtype.itemsize)
  704. size = elm_count * dtype.itemsize
  705. data = fp.read(size)
  706. assert len(data) == size
  707. return np.frombuffer(data, dtype)
  708. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  709. return LazyStorage(load=load, kind=pid[1], description=description)
  710. @staticmethod
  711. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  712. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  713. assert isinstance(storage, LazyStorage)
  714. def load() -> UnquantizedTensor:
  715. elm_count = stride[0] * size[0]
  716. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  717. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  718. return LazyTensor(load, list(size), storage.kind.data_type, description)
  719. @staticmethod
  720. def rebuild_from_type_v2(func, new_type, args, state):
  721. return func(*args)
  722. CLASSES: dict[tuple[str, str], type[LazyTensor] | LazyStorageKind] = {
  723. # getattr used here as a workaround for mypy not being smart enough to determine
  724. # the staticmethods have a __func__ attribute.
  725. ('torch._tensor', '_rebuild_from_type_v2'): getattr(rebuild_from_type_v2, '__func__'),
  726. ('torch._utils', '_rebuild_tensor_v2'): getattr(lazy_rebuild_tensor_v2, '__func__'),
  727. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  728. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  729. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  730. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  731. ('torch', 'Tensor'): LazyTensor,
  732. }
  733. def find_class(self, module: str, name: str) -> Any:
  734. if not module.startswith('torch'):
  735. return super().find_class(module, name)
  736. return self.CLASSES[(module, name)]
  737. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  738. zf = zipfile.ZipFile(outer_fp)
  739. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  740. assert len(pickle_paths) == 1, pickle_paths
  741. pickle_fp = zf.open(pickle_paths[0], 'r')
  742. unpickler = LazyUnpickler(pickle_fp,
  743. data_base_path=pickle_paths[0][:-4],
  744. zip_file=zf)
  745. model = unpickler.load()
  746. if 'model' in model: model = model['model']
  747. as_dict = dict(model.items())
  748. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  749. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  750. header_size, = struct.unpack('<Q', fp.read(8))
  751. header: dict[str, dict[str, Any]] = json.loads(fp.read(header_size))
  752. # Use mmap for the actual data to avoid race conditions with the file offset.
  753. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  754. byte_buf = mapped[8 + header_size:]
  755. def convert(info: dict[str, Any]) -> LazyTensor:
  756. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  757. numpy_dtype = data_type.dtype
  758. shape: list[int] = info['shape']
  759. begin, end = info['data_offsets']
  760. assert 0 <= begin <= end <= len(byte_buf)
  761. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  762. buf = byte_buf[begin:end]
  763. def load() -> UnquantizedTensor:
  764. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  765. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  766. return LazyTensor(load, shape, data_type, description)
  767. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  768. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  769. def must_read(fp: IO[bytes], length: int) -> bytes:
  770. ret = fp.read(length)
  771. if len(ret) < length:
  772. raise EOFError("unexpectedly reached end of file")
  773. return ret
  774. @functools.lru_cache(maxsize=None)
  775. def lazy_load_file(path: Path) -> ModelPlus:
  776. fp = open(path, 'rb')
  777. first8 = fp.read(8)
  778. fp.seek(0)
  779. if first8[:2] == b'PK':
  780. # A zip file, i.e. PyTorch format
  781. return lazy_load_torch_file(fp, path)
  782. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  783. # Probably safetensors
  784. return lazy_load_safetensors_file(fp, path)
  785. else:
  786. raise ValueError(f"unknown format: {path}")
  787. In = TypeVar('In')
  788. Out = TypeVar('Out')
  789. def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False) -> Iterable[Out]:
  790. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  791. fast enough, this will stop calling `func` at some point rather than
  792. letting results pile up in memory. Specifically, there is a max of one
  793. output value buffered per thread.'''
  794. if concurrency < 2:
  795. yield from map(func, iterable)
  796. # Not reached.
  797. iterable = iter(iterable)
  798. executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor]
  799. if use_processpool_executor:
  800. executor_class = ProcessPoolExecutor
  801. else:
  802. executor_class = ThreadPoolExecutor
  803. with executor_class(max_workers=max_workers) as executor:
  804. futures: list[concurrent.futures.Future[Out]] = []
  805. done = False
  806. for _ in range(concurrency):
  807. try:
  808. futures.append(executor.submit(func, next(iterable)))
  809. except StopIteration:
  810. done = True
  811. break
  812. while futures:
  813. result = futures.pop(0).result()
  814. while not done and len(futures) < concurrency:
  815. try:
  816. futures.append(executor.submit(func, next(iterable)))
  817. except StopIteration:
  818. done = True
  819. break
  820. yield result
  821. def check_vocab_size(params: Params, vocab: BaseVocab, pad_vocab: bool = False) -> None:
  822. # Handle special case where the model's vocab size is not set
  823. if params.n_vocab == -1:
  824. raise ValueError(
  825. "The model's vocab size is set to -1 in params.json. Please update it manually."
  826. + (f" Maybe {vocab.vocab_size}?" if isinstance(vocab, Vocab) else ""),
  827. )
  828. if not isinstance(vocab, Vocab):
  829. return # model has no vocab
  830. # Check for a vocab size mismatch
  831. if params.n_vocab == vocab.vocab_size:
  832. logger.warning("Ignoring added_tokens.json since model matches vocab size without it.")
  833. return
  834. if pad_vocab and params.n_vocab > vocab.vocab_size:
  835. pad_count = params.n_vocab - vocab.vocab_size
  836. logger.debug(
  837. f"Padding vocab with {pad_count} token(s) - <dummy00001> through <dummy{pad_count:05}>"
  838. )
  839. for i in range(1, pad_count + 1):
  840. vocab.added_tokens_dict[f"<dummy{i:05}>"] = -1
  841. vocab.added_tokens_list.append(f"<dummy{i:05}>")
  842. vocab.vocab_size = params.n_vocab
  843. return
  844. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer} has {vocab.vocab_size})."
  845. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20:
  846. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  847. if vocab.vocab_size < params.n_vocab:
  848. msg += " Add the --pad-vocab option and try again."
  849. raise ValueError(msg)
  850. class OutputFile:
  851. def __init__(self, fname_out: Path, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE):
  852. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH], endianess=endianess)
  853. def add_meta_arch(self, params: Params) -> None:
  854. name = "LLaMA"
  855. # TODO: better logic to determine model name
  856. if params.n_ctx == 4096:
  857. name = "LLaMA v2"
  858. elif params.path_model is not None:
  859. name = str(params.path_model.parent).split('/')[-1]
  860. self.gguf.add_name (name)
  861. self.gguf.add_vocab_size (params.n_vocab)
  862. self.gguf.add_context_length (params.n_ctx)
  863. self.gguf.add_embedding_length (params.n_embd)
  864. self.gguf.add_block_count (params.n_layer)
  865. self.gguf.add_feed_forward_length (params.n_ff)
  866. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  867. self.gguf.add_head_count (params.n_head)
  868. self.gguf.add_head_count_kv (params.n_head_kv)
  869. if params.n_experts:
  870. self.gguf.add_expert_count(params.n_experts)
  871. if params.n_experts_used:
  872. self.gguf.add_expert_used_count(params.n_experts_used)
  873. if params.f_norm_eps:
  874. self.gguf.add_layer_norm_rms_eps(params.f_norm_eps)
  875. else:
  876. raise ValueError('f_norm_eps is None')
  877. if params.f_rope_freq_base is not None:
  878. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  879. if params.rope_scaling_type:
  880. assert params.f_rope_scale is not None
  881. self.gguf.add_rope_scaling_type(params.rope_scaling_type)
  882. self.gguf.add_rope_scaling_factor(params.f_rope_scale)
  883. if params.n_orig_ctx is not None:
  884. self.gguf.add_rope_scaling_orig_ctx_len(params.n_orig_ctx)
  885. if params.rope_finetuned is not None:
  886. self.gguf.add_rope_scaling_finetuned(params.rope_finetuned)
  887. if params.ftype is not None:
  888. self.gguf.add_file_type(params.ftype)
  889. def extract_vocabulary_from_model(self, vocab: Vocab) -> tuple[list[bytes], list[float], list[gguf.TokenType]]:
  890. tokens = []
  891. scores = []
  892. toktypes = []
  893. # NOTE: `all_tokens` returns the base vocabulary and added tokens
  894. for text, score, toktype in vocab.all_tokens():
  895. tokens.append(text)
  896. scores.append(score)
  897. toktypes.append(toktype)
  898. assert len(tokens) == vocab.vocab_size
  899. return tokens, scores, toktypes
  900. def add_meta_vocab(self, vocab: Vocab) -> None:
  901. # Ensure that tokenizer_model is added to the GGUF model
  902. self.gguf.add_tokenizer_model(vocab.tokenizer_model)
  903. # Extract model vocabulary for model conversion
  904. tokens, scores, toktypes = self.extract_vocabulary_from_model(vocab)
  905. # Add extracted token information for model conversion
  906. self.gguf.add_token_list(tokens)
  907. self.gguf.add_token_scores(scores)
  908. self.gguf.add_token_types(toktypes)
  909. def add_meta_special_vocab(self, svocab: gguf.SpecialVocab) -> None:
  910. svocab.add_to_gguf(self.gguf)
  911. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  912. n_elements = int(np.prod(tensor.shape))
  913. raw_dtype = getattr(tensor.data_type, 'ggml_type', None)
  914. data_type = getattr(tensor.data_type, 'quantized_type', None) or tensor.data_type.dtype
  915. data_nbytes = tensor.data_type.elements_to_bytes(n_elements)
  916. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes, raw_dtype=raw_dtype)
  917. def write_meta(self) -> None:
  918. self.gguf.write_header_to_file()
  919. self.gguf.write_kv_data_to_file()
  920. def write_tensor_info(self) -> None:
  921. self.gguf.write_ti_data_to_file()
  922. def write_tensor_data(self, ftype: GGMLFileType, model: LazyModel, concurrency: int) -> None:
  923. ndarrays_inner = bounded_parallel_map(OutputFile.do_item, model.items(), concurrency=concurrency)
  924. if ftype == GGMLFileType.MostlyQ8_0:
  925. ndarrays = bounded_parallel_map(
  926. OutputFile.maybe_do_quantize, ndarrays_inner, concurrency=concurrency, max_workers=concurrency,
  927. use_processpool_executor=True,
  928. )
  929. else:
  930. ndarrays = map(OutputFile.maybe_do_quantize, ndarrays_inner)
  931. start = time.time()
  932. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  933. elapsed = time.time() - start
  934. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  935. padi = len(str(len(model)))
  936. logger.info(
  937. f"[{i + 1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type.name:4} | T+{int(elapsed):4}"
  938. )
  939. self.gguf.write_tensor_data(ndarray)
  940. def close(self) -> None:
  941. self.gguf.close()
  942. @staticmethod
  943. def write_vocab_only(
  944. fname_out: Path, params: Params, vocab: Vocab, svocab: gguf.SpecialVocab,
  945. endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE, pad_vocab: bool = False,
  946. ) -> None:
  947. check_vocab_size(params, vocab, pad_vocab=pad_vocab)
  948. of = OutputFile(fname_out, endianess=endianess)
  949. # meta data
  950. of.add_meta_arch(params)
  951. of.add_meta_vocab(vocab)
  952. of.add_meta_special_vocab(svocab)
  953. of.write_meta()
  954. of.close()
  955. @staticmethod
  956. def do_item(item: tuple[str, LazyTensor]) -> tuple[DataType, NDArray]:
  957. name, lazy_tensor = item
  958. tensor = lazy_tensor.load().to_ggml()
  959. return (lazy_tensor.data_type, tensor.ndarray)
  960. @staticmethod
  961. def maybe_do_quantize(item: tuple[DataType, NDArray]) -> NDArray:
  962. dt, arr = item
  963. if not isinstance(dt, QuantizedDataType):
  964. return arr
  965. return dt.quantize(arr)
  966. @staticmethod
  967. def write_all(
  968. fname_out: Path, ftype: GGMLFileType, params: Params, model: LazyModel, vocab: BaseVocab, svocab: gguf.SpecialVocab,
  969. concurrency: int = DEFAULT_CONCURRENCY, endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE,
  970. pad_vocab: bool = False,
  971. ) -> None:
  972. check_vocab_size(params, vocab, pad_vocab=pad_vocab)
  973. of = OutputFile(fname_out, endianess=endianess)
  974. # meta data
  975. of.add_meta_arch(params)
  976. if isinstance(vocab, Vocab):
  977. of.add_meta_vocab(vocab)
  978. of.add_meta_special_vocab(svocab)
  979. else: # NoVocab
  980. of.gguf.add_tokenizer_model(vocab.tokenizer_model)
  981. # tensor info
  982. for name, lazy_tensor in model.items():
  983. of.add_tensor_info(name, lazy_tensor)
  984. of.write_meta()
  985. of.write_tensor_info()
  986. # tensor data
  987. of.write_tensor_data(ftype, model, concurrency)
  988. of.close()
  989. def pick_output_type(model: LazyModel, output_type_str: str | None) -> GGMLFileType:
  990. wq_type = model[gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0) + ".weight"].data_type
  991. if output_type_str == "f32" or (output_type_str is None and wq_type in (DT_F32, DT_BF16)):
  992. return GGMLFileType.AllF32
  993. if output_type_str == "f16" or (output_type_str is None and wq_type == DT_F16):
  994. return GGMLFileType.MostlyF16
  995. if output_type_str == "q8_0":
  996. return GGMLFileType.MostlyQ8_0
  997. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  998. raise ValueError(f"Unexpected combination of types: {name_to_type}")
  999. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  1000. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  1001. for (name, tensor) in model.items()}
  1002. def convert_model_names(model: LazyModel, params: Params, skip_unknown: bool) -> LazyModel:
  1003. tmap = gguf.TensorNameMap(ARCH, params.n_layer)
  1004. should_skip = set(gguf.MODEL_TENSOR_SKIP.get(ARCH, []))
  1005. tmp = model
  1006. # merge experts into one tensor
  1007. if params.n_experts and params.n_experts > 0:
  1008. for i_l in range(params.n_layer):
  1009. for w in range(1, 4):
  1010. experts = []
  1011. for e in range(params.n_experts):
  1012. if f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight" in model:
  1013. experts.append(model[f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight"])
  1014. del tmp[f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight"]
  1015. elif f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight" in model:
  1016. experts.append(model[f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight"])
  1017. del tmp[f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight"]
  1018. else:
  1019. raise ValueError(f"Expert tensor not found: layers.{i_l}.feed_forward.experts.{e}.w{w}.weight")
  1020. tmp[f"layers.{i_l}.feed_forward.experts.w{w}.weight"] = pack_experts_lazy(experts)
  1021. # HF models permut or pack some of the tensors, so we need to undo that
  1022. for i in itertools.count():
  1023. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  1024. logger.debug(f"Permuting layer {i}")
  1025. 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)
  1026. 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)
  1027. # tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  1028. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  1029. logger.debug(f"Unpacking and permuting layer {i}")
  1030. 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)
  1031. 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)
  1032. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  1033. del tmp[f"model.layers.{i}.self_attn.W_pack.weight"]
  1034. else:
  1035. break
  1036. out: LazyModel = {}
  1037. for name, lazy_tensor in model.items():
  1038. tensor_type, name_new = tmap.get_type_and_name(name, try_suffixes = (".weight", ".bias")) or (None, None)
  1039. if name_new is None:
  1040. if skip_unknown:
  1041. logger.warning(f"Unexpected tensor name: {name} - skipping")
  1042. continue
  1043. raise ValueError(f"Unexpected tensor name: {name}. Use --skip-unknown to ignore it (e.g. LLaVA)")
  1044. if tensor_type in should_skip:
  1045. logger.debug(f"skipping tensor {name_new}")
  1046. continue
  1047. logger.debug(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type.name:6s} | {lazy_tensor.shape}")
  1048. out[name_new] = lazy_tensor
  1049. return out
  1050. def nth_multifile_path(path: Path, n: int) -> Path | None:
  1051. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  1052. the nth path in the model.
  1053. '''
  1054. # Support the following patterns:
  1055. patterns = [
  1056. # - x.00.pth, x.01.pth, etc.
  1057. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  1058. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  1059. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  1060. # x.bin, x.bin.1, etc.
  1061. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  1062. ]
  1063. for regex, replacement in patterns:
  1064. if re.search(regex, path.name):
  1065. new_path = path.with_name(re.sub(regex, replacement, path.name))
  1066. if new_path.exists():
  1067. return new_path
  1068. return None
  1069. def find_multifile_paths(path: Path) -> list[Path]:
  1070. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  1071. the whole list of paths in the model.
  1072. '''
  1073. ret: list[Path] = []
  1074. for i in itertools.count():
  1075. nth_path = nth_multifile_path(path, i)
  1076. if nth_path is None:
  1077. break
  1078. ret.append(nth_path)
  1079. if not ret:
  1080. # No matches. This should only happen if the file was named, e.g.,
  1081. # foo.0, and there was no file named foo. Oh well, try to process it
  1082. # as a single file.
  1083. return [path]
  1084. return ret
  1085. def load_some_model(path: Path) -> ModelPlus:
  1086. '''Load a model of any supported format.'''
  1087. # Be extra-friendly and accept either a file or a directory:
  1088. if path.is_dir():
  1089. # Check if it's a set of safetensors files first
  1090. globs = ["model-00001-of-*.safetensors", "model.safetensors", "consolidated.safetensors"]
  1091. files = [file for glob in globs for file in path.glob(glob)]
  1092. if not files:
  1093. # Try the PyTorch patterns too, with lower priority
  1094. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  1095. files = [file for glob in globs for file in path.glob(glob)]
  1096. if not files:
  1097. raise FileNotFoundError(f"Can't find model in directory {path}")
  1098. if len(files) > 1:
  1099. raise ValueError(f"Found multiple models in {path}, not sure which to pick: {files}")
  1100. path = files[0]
  1101. paths = find_multifile_paths(path)
  1102. models_plus: list[ModelPlus] = []
  1103. for path in paths:
  1104. logger.info(f"Loading model file {path}")
  1105. models_plus.append(lazy_load_file(path))
  1106. model_plus = merge_multifile_models(models_plus)
  1107. return model_plus
  1108. class VocabFactory:
  1109. _VOCAB_CLASSES: list[type[Vocab]] = [SentencePieceVocab, BpeVocab, LlamaHfVocab]
  1110. def __init__(self, path: Path):
  1111. self.path = path
  1112. def _create_special_vocab(self, vocab: BaseVocab, model_parent_path: Path) -> gguf.SpecialVocab:
  1113. load_merges = vocab.name == "bpe"
  1114. n_vocab = vocab.vocab_size if isinstance(vocab, Vocab) else None
  1115. return gguf.SpecialVocab(
  1116. model_parent_path,
  1117. load_merges=load_merges,
  1118. special_token_types=None, # Predetermined or passed as a parameter
  1119. n_vocab=n_vocab,
  1120. )
  1121. def _create_vocab_by_path(self, vocab_types: list[str]) -> Vocab:
  1122. vocab_classes: dict[str, type[Vocab]] = {cls.name: cls for cls in self._VOCAB_CLASSES}
  1123. selected_vocabs: dict[str, type[Vocab]] = {}
  1124. for vtype in vocab_types:
  1125. try:
  1126. selected_vocabs[vtype] = vocab_classes[vtype]
  1127. except KeyError:
  1128. raise ValueError(f"Unsupported vocabulary type {vtype}") from None
  1129. for vtype, cls in selected_vocabs.items():
  1130. try:
  1131. vocab = cls(self.path)
  1132. break
  1133. except FileNotFoundError:
  1134. pass # ignore unavailable tokenizers
  1135. else:
  1136. raise FileNotFoundError(f"Could not find a tokenizer matching any of {vocab_types}")
  1137. logger.info(f"Loaded vocab file {vocab.fname_tokenizer!r}, type {vocab.name!r}")
  1138. return vocab
  1139. def load_vocab(self, vocab_types: list[str] | None, model_parent_path: Path) -> tuple[BaseVocab, gguf.SpecialVocab]:
  1140. vocab: BaseVocab
  1141. if vocab_types is None:
  1142. vocab = NoVocab()
  1143. else:
  1144. vocab = self._create_vocab_by_path(vocab_types)
  1145. # FIXME: Respect --vocab-dir?
  1146. special_vocab = self._create_special_vocab(
  1147. vocab,
  1148. model_parent_path,
  1149. )
  1150. return vocab, special_vocab
  1151. def default_outfile(model_paths: list[Path], file_type: GGMLFileType) -> Path:
  1152. namestr = {
  1153. GGMLFileType.AllF32: "f32",
  1154. GGMLFileType.MostlyF16: "f16",
  1155. GGMLFileType.MostlyQ8_0:"q8_0",
  1156. }[file_type]
  1157. ret = model_paths[0].parent / f"ggml-model-{namestr}.gguf"
  1158. if ret in model_paths:
  1159. logger.error(
  1160. f"Error: Default output path ({ret}) would overwrite the input. "
  1161. "Please explicitly specify a path using --outfile.")
  1162. sys.exit(1)
  1163. return ret
  1164. def do_dump_model(model_plus: ModelPlus) -> None:
  1165. print(f"model_plus.paths = {model_plus.paths!r}") # noqa: NP100
  1166. print(f"model_plus.format = {model_plus.format!r}") # noqa: NP100
  1167. print(f"model_plus.vocab = {model_plus.vocab!r}") # noqa: NP100
  1168. for name, lazy_tensor in model_plus.model.items():
  1169. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}") # noqa: NP100
  1170. def main(args_in: list[str] | None = None) -> None:
  1171. output_choices = ["f32", "f16"]
  1172. if np.uint32(1) == np.uint32(1).newbyteorder("<"):
  1173. # We currently only support Q8_0 output on little endian systems.
  1174. output_choices.append("q8_0")
  1175. parser = argparse.ArgumentParser(description="Convert a LLaMA model to a GGML compatible file")
  1176. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  1177. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  1178. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  1179. parser.add_argument("--no-vocab", action="store_true", help="store model without the vocab")
  1180. parser.add_argument("--outtype", choices=output_choices, help="output format - note: q8_0 may be very slow (default: f16 or f32 based on input)")
  1181. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  1182. parser.add_argument("--vocab-type", help="vocab types to try in order, choose from 'spm', 'bpe', 'hfft' (default: spm,hfft)", default="spm,hfft")
  1183. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  1184. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
  1185. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  1186. parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default=DEFAULT_CONCURRENCY)
  1187. parser.add_argument("--big-endian", action="store_true", help="model is executed on big endian machine")
  1188. parser.add_argument("--pad-vocab", action="store_true", help="add pad tokens when model vocab expects more than tokenizer metadata provides")
  1189. parser.add_argument("--skip-unknown", action="store_true", help="skip unknown tensor names instead of failing")
  1190. parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
  1191. args = parser.parse_args(args_in)
  1192. if args.verbose:
  1193. logging.basicConfig(level=logging.DEBUG)
  1194. elif args.dump_single or args.dump:
  1195. # Avoid printing anything besides the dump output
  1196. logging.basicConfig(level=logging.WARNING)
  1197. else:
  1198. logging.basicConfig(level=logging.INFO)
  1199. if args.no_vocab and args.vocab_only:
  1200. raise ValueError("--vocab-only does not make sense with --no-vocab")
  1201. if args.dump_single:
  1202. model_plus = lazy_load_file(args.model)
  1203. do_dump_model(model_plus)
  1204. return
  1205. if not args.vocab_only:
  1206. model_plus = load_some_model(args.model)
  1207. else:
  1208. model_plus = ModelPlus(model = {}, paths = [args.model / 'dummy'], format = 'none', vocab = None)
  1209. if args.dump:
  1210. do_dump_model(model_plus)
  1211. return
  1212. endianess = gguf.GGUFEndian.LITTLE
  1213. if args.big_endian:
  1214. endianess = gguf.GGUFEndian.BIG
  1215. params = None
  1216. if args.pad_vocab or not args.vocab_only:
  1217. params = Params.load(model_plus)
  1218. if params.n_ctx == -1:
  1219. if args.ctx is None:
  1220. msg = """\
  1221. The model doesn't have a context size, and you didn't specify one with --ctx
  1222. Please specify one with --ctx:
  1223. - LLaMA v1: --ctx 2048
  1224. - LLaMA v2: --ctx 4096"""
  1225. parser.error(textwrap.dedent(msg))
  1226. params.n_ctx = args.ctx
  1227. if args.outtype:
  1228. params.ftype = {
  1229. "f32": GGMLFileType.AllF32,
  1230. "f16": GGMLFileType.MostlyF16,
  1231. "q8_0": GGMLFileType.MostlyQ8_0,
  1232. }[args.outtype]
  1233. logger.info(f"params = {params}")
  1234. model_parent_path = model_plus.paths[0].parent
  1235. vocab_path = Path(args.vocab_dir or args.model or model_parent_path)
  1236. vocab_factory = VocabFactory(vocab_path)
  1237. vocab_types = None if args.no_vocab else args.vocab_type.split(",")
  1238. vocab, special_vocab = vocab_factory.load_vocab(vocab_types, model_parent_path)
  1239. if args.vocab_only:
  1240. assert isinstance(vocab, Vocab)
  1241. if not args.outfile:
  1242. raise ValueError("need --outfile if using --vocab-only")
  1243. outfile = args.outfile
  1244. if params is None:
  1245. params = Params(
  1246. n_vocab = vocab.vocab_size,
  1247. n_embd = 1,
  1248. n_layer = 1,
  1249. n_ctx = 1,
  1250. n_ff = 1,
  1251. n_head = 1,
  1252. n_head_kv = 1,
  1253. f_norm_eps = 1e-5,
  1254. )
  1255. OutputFile.write_vocab_only(outfile, params, vocab, special_vocab,
  1256. endianess=endianess, pad_vocab=args.pad_vocab)
  1257. logger.info(f"Wrote {outfile}")
  1258. return
  1259. if model_plus.vocab is not None and args.vocab_dir is None and not args.no_vocab:
  1260. vocab = model_plus.vocab
  1261. logger.info(f"Vocab info: {vocab}")
  1262. logger.info(f"Special vocab info: {special_vocab}")
  1263. model = model_plus.model
  1264. model = convert_model_names(model, params, args.skip_unknown)
  1265. ftype = pick_output_type(model, args.outtype)
  1266. model = convert_to_output_type(model, ftype)
  1267. outfile = args.outfile or default_outfile(model_plus.paths, ftype)
  1268. params.ftype = ftype
  1269. logger.info(f"Writing {outfile}, format {ftype}")
  1270. OutputFile.write_all(outfile, ftype, params, model, vocab, special_vocab,
  1271. concurrency=args.concurrency, endianess=endianess, pad_vocab=args.pad_vocab)
  1272. logger.info(f"Wrote {outfile}")
  1273. if __name__ == '__main__':
  1274. main()