convert.py 59 KB

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