1
0

convert.py 62 KB

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