convert.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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 pickle
  13. import re
  14. import signal
  15. import struct
  16. import sys
  17. import time
  18. import zipfile
  19. from abc import ABCMeta, abstractmethod
  20. from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
  21. from dataclasses import dataclass
  22. from pathlib import Path
  23. from typing import IO, TYPE_CHECKING, Any, Callable, Iterable, Literal, TypeVar
  24. import numpy as np
  25. from sentencepiece import SentencePieceProcessor
  26. import os
  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. f_norm_eps: float
  127. rope_scaling_type: gguf.RopeScalingType | None = None
  128. f_rope_freq_base: float | None = None
  129. f_rope_scale: float | None = None
  130. n_orig_ctx: int | None = None
  131. rope_finetuned: bool | None = None
  132. ftype: GGMLFileType | None = None
  133. # path to the directory containing the model files
  134. path_model: Path | None = None
  135. @staticmethod
  136. def guessed(model: LazyModel) -> Params:
  137. # try transformer naming first
  138. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  139. # try transformer naming first
  140. if "model.layers.0.self_attn.q_proj.weight" in model:
  141. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  142. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  143. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  144. else:
  145. n_layer = next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  146. if n_layer < 1:
  147. raise Exception("failed to guess 'n_layer'. This model is unknown or unsupported.\n"
  148. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  149. n_head = n_embd // 128 # guessed
  150. n_mult = 256 # guessed
  151. # TODO: verify this
  152. n_ff = int(2 * (4 * n_embd) / 3)
  153. n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
  154. return Params(
  155. n_vocab = n_vocab,
  156. n_embd = n_embd,
  157. n_layer = n_layer,
  158. n_ctx = -1,
  159. n_ff = n_ff,
  160. n_head = n_head,
  161. n_head_kv = n_head,
  162. f_norm_eps = 1e-5,
  163. )
  164. @staticmethod
  165. def loadHFTransformerJson(model: LazyModel, config_path: Path) -> Params:
  166. config = json.load(open(config_path))
  167. rope_scaling_type = f_rope_scale = n_orig_ctx = rope_finetuned = None
  168. rope_scaling = config.get("rope_scaling")
  169. if rope_scaling is not None and (typ := rope_scaling.get("type")):
  170. rope_factor = rope_scaling.get("factor")
  171. f_rope_scale = rope_factor
  172. if typ == "linear":
  173. rope_scaling_type = gguf.RopeScalingType.LINEAR
  174. elif typ == "yarn":
  175. rope_scaling_type = gguf.RopeScalingType.YARN
  176. n_orig_ctx = rope_scaling['original_max_position_embeddings']
  177. rope_finetuned = rope_scaling['finetuned']
  178. else:
  179. raise NotImplementedError(f'Unknown rope scaling type: {typ}')
  180. if "max_sequence_length" in config:
  181. n_ctx = config["max_sequence_length"]
  182. elif "max_position_embeddings" in config:
  183. n_ctx = config["max_position_embeddings"]
  184. else:
  185. raise Exception("failed to guess 'n_ctx'. This model is unknown or unsupported.\n"
  186. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  187. return Params(
  188. n_vocab = config["vocab_size"],
  189. n_embd = config["hidden_size"],
  190. n_layer = config["num_hidden_layers"],
  191. n_ctx = n_ctx,
  192. n_ff = config["intermediate_size"],
  193. n_head = (n_head := config["num_attention_heads"]),
  194. n_head_kv = config.get("num_key_value_heads", n_head),
  195. f_norm_eps = config["rms_norm_eps"],
  196. f_rope_freq_base = config.get("rope_theta"),
  197. rope_scaling_type = rope_scaling_type,
  198. f_rope_scale = f_rope_scale,
  199. n_orig_ctx = n_orig_ctx,
  200. rope_finetuned = rope_finetuned,
  201. )
  202. # LLaMA v2 70B params.json
  203. # {"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}
  204. @staticmethod
  205. def loadOriginalParamsJson(model: LazyModel, config_path: Path) -> Params:
  206. config = json.load(open(config_path))
  207. # hack to determine LLaMA v1 vs v2 vs CodeLlama
  208. if config.get("rope_theta") == 1000000:
  209. # CodeLlama
  210. n_ctx = 16384
  211. elif config["norm_eps"] == 1e-05:
  212. # LLaMA v2
  213. n_ctx = 4096
  214. else:
  215. # LLaMA v1
  216. n_ctx = 2048
  217. return Params(
  218. n_vocab = model["tok_embeddings.weight"].shape[0],
  219. n_embd = config["dim"],
  220. n_layer = config["n_layers"],
  221. n_ctx = n_ctx,
  222. n_ff = model["layers.0.feed_forward.w1.weight"].shape[0],
  223. n_head = (n_head := config["n_heads"]),
  224. n_head_kv = config.get("n_kv_heads", n_head),
  225. f_norm_eps = config["norm_eps"],
  226. f_rope_freq_base = config.get("rope_theta"),
  227. )
  228. @staticmethod
  229. def load(model_plus: ModelPlus) -> Params:
  230. hf_config_path = model_plus.paths[0].parent / "config.json"
  231. orig_config_path = model_plus.paths[0].parent / "params.json"
  232. if hf_config_path.exists():
  233. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  234. elif orig_config_path.exists():
  235. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  236. elif model_plus.format != 'none':
  237. params = Params.guessed(model_plus.model)
  238. else:
  239. raise ValueError('Cannot guess params when model format is none')
  240. params.path_model = model_plus.paths[0].parent
  241. return params
  242. #
  243. # vocab
  244. #
  245. class BpeVocab:
  246. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
  247. self.bpe_tokenizer = json.loads(open(str(fname_tokenizer), encoding="utf-8").read())
  248. added_tokens: dict[str, int]
  249. if fname_added_tokens is not None:
  250. # FIXME: Verify that added tokens here _cannot_ overlap with the main vocab.
  251. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  252. else:
  253. # Fall back to trying to find the added tokens in tokenizer.json
  254. tokenizer_json_file = fname_tokenizer.parent / 'tokenizer.json'
  255. if not tokenizer_json_file.is_file():
  256. added_tokens = {}
  257. else:
  258. tokenizer_json = json.load(open(tokenizer_json_file, encoding="utf-8"))
  259. added_tokens = dict(
  260. (item['content'], item['id'])
  261. for item in tokenizer_json.get('added_tokens', [])
  262. # Added tokens here can be duplicates of the main vocabulary.
  263. if item['content'] not in self.bpe_tokenizer)
  264. vocab_size: int = len(self.bpe_tokenizer)
  265. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  266. actual_ids = sorted(added_tokens.values())
  267. if expected_ids != actual_ids:
  268. expected_end_id = vocab_size + len(actual_ids) - 1
  269. 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}")
  270. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  271. self.added_tokens_list = [text for (text, idx) in items]
  272. self.vocab_size_base: int = vocab_size
  273. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  274. self.fname_tokenizer = fname_tokenizer
  275. self.fname_added_tokens = fname_added_tokens
  276. def bpe_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  277. tokenizer = self.bpe_tokenizer
  278. reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.items()}
  279. for i, _ in enumerate(tokenizer):
  280. yield reverse_vocab[i], 0.0, gguf.TokenType.NORMAL
  281. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  282. for text in self.added_tokens_list:
  283. score = -1000.0
  284. yield text.encode("utf-8"), score, gguf.TokenType.CONTROL
  285. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  286. yield from self.bpe_tokens()
  287. yield from self.added_tokens()
  288. def __repr__(self) -> str:
  289. return f"<BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  290. class SentencePieceVocab:
  291. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
  292. self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
  293. added_tokens: dict[str, int]
  294. if fname_added_tokens is not None:
  295. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  296. else:
  297. added_tokens = {}
  298. vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
  299. new_tokens = {id: piece for piece, id in added_tokens.items() if id >= vocab_size}
  300. expected_new_ids = list(range(vocab_size, vocab_size + len(new_tokens)))
  301. actual_new_ids = sorted(new_tokens.keys())
  302. if expected_new_ids != actual_new_ids:
  303. raise ValueError(f"Expected new token IDs {expected_new_ids} to be sequential; got {actual_new_ids}")
  304. # Token pieces that were added to the base vocabulary.
  305. self.added_tokens_list = [new_tokens[id] for id in actual_new_ids]
  306. self.vocab_size_base = vocab_size
  307. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  308. self.fname_tokenizer = fname_tokenizer
  309. self.fname_added_tokens = fname_added_tokens
  310. def sentencepiece_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  311. tokenizer = self.sentencepiece_tokenizer
  312. for i in range(tokenizer.vocab_size()):
  313. piece = tokenizer.id_to_piece(i)
  314. text: bytes = piece.encode("utf-8")
  315. score: float = tokenizer.get_score(i)
  316. toktype = gguf.TokenType.NORMAL
  317. if tokenizer.is_unknown(i):
  318. toktype = gguf.TokenType.UNKNOWN
  319. if tokenizer.is_control(i):
  320. toktype = gguf.TokenType.CONTROL
  321. # NOTE: I think added_tokens are user defined.
  322. # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
  323. # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
  324. if tokenizer.is_unused(i):
  325. toktype = gguf.TokenType.UNUSED
  326. if tokenizer.is_byte(i):
  327. toktype = gguf.TokenType.BYTE
  328. yield text, score, toktype
  329. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  330. for text in self.added_tokens_list:
  331. score = -1000.0
  332. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  333. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  334. yield from self.sentencepiece_tokens()
  335. yield from self.added_tokens()
  336. def __repr__(self) -> str:
  337. return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  338. Vocab: TypeAlias = 'BpeVocab | SentencePieceVocab'
  339. #
  340. # data loading
  341. # TODO: reuse (probably move to gguf.py?)
  342. #
  343. def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
  344. # print( "permute debug " + str(weights.shape[0]) + " x " + str(weights.shape[1]) + " nhead " + str(n_head) + " nheadkv " + str(n_kv_head) )
  345. if n_head_kv is not None and n_head != n_head_kv:
  346. n_head = n_head_kv
  347. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  348. .swapaxes(1, 2)
  349. .reshape(weights.shape))
  350. class Tensor(metaclass=ABCMeta):
  351. data_type: DataType
  352. @abstractmethod
  353. def astype(self, data_type: DataType) -> Tensor: ...
  354. @abstractmethod
  355. def permute(self, n_head: int, n_head_kv: int) -> Tensor: ...
  356. @abstractmethod
  357. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor: ...
  358. @abstractmethod
  359. def part(self, n_part: int) -> UnquantizedTensor: ...
  360. @abstractmethod
  361. def to_ggml(self) -> GGMLCompatibleTensor: ...
  362. def bf16_to_fp32(bf16_arr: np.ndarray[Any, np.dtype[np.uint16]]) -> NDArray:
  363. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  364. fp32_arr = bf16_arr.astype(np.uint32) << 16
  365. return fp32_arr.view(np.float32)
  366. class UnquantizedTensor(Tensor):
  367. def __init__(self, ndarray: NDArray) -> None:
  368. assert isinstance(ndarray, np.ndarray)
  369. self.ndarray = ndarray
  370. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  371. def astype(self, data_type: DataType) -> Tensor:
  372. dtype = data_type.dtype
  373. if self.data_type == DT_BF16:
  374. self.ndarray = bf16_to_fp32(self.ndarray)
  375. return UnquantizedTensor(self.ndarray.astype(dtype))
  376. def to_ggml(self) -> UnquantizedTensor:
  377. return self
  378. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  379. r = self.ndarray.shape[0] // 3
  380. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head, n_head_kv))
  381. def part(self, n_part: int) -> UnquantizedTensor:
  382. r = self.ndarray.shape[0] // 3
  383. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  384. def permute(self, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  385. return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
  386. def load_unquantized(lazy_tensor: LazyTensor, expected_dtype: Any = None, convert: bool = False) -> NDArray:
  387. tensor = lazy_tensor.load()
  388. assert isinstance(tensor, UnquantizedTensor)
  389. # double-check:
  390. actual_shape = list(tensor.ndarray.shape)
  391. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  392. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  393. if convert:
  394. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  395. else:
  396. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  397. return tensor.ndarray
  398. GGMLCompatibleTensor = UnquantizedTensor
  399. @dataclass
  400. class LazyTensor:
  401. _load: Callable[[], Tensor]
  402. shape: list[int]
  403. data_type: DataType
  404. description: str
  405. def load(self) -> Tensor:
  406. ret = self._load()
  407. # Should be okay if it maps to the same numpy type?
  408. assert ret.data_type == self.data_type or (self.data_type.dtype == ret.data_type.dtype), \
  409. (self.data_type, ret.data_type, self.description)
  410. return ret
  411. def astype(self, data_type: DataType) -> LazyTensor:
  412. self.validate_conversion_to(data_type)
  413. def load() -> Tensor:
  414. return self.load().astype(data_type)
  415. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  416. def validate_conversion_to(self, data_type: DataType) -> None:
  417. if data_type != self.data_type and data_type.name not in self.data_type.valid_conversions:
  418. raise ValueError(f'Cannot validate conversion from {self.data_type} to {data_type}.')
  419. LazyModel: TypeAlias = 'dict[str, LazyTensor]'
  420. @dataclass
  421. class ModelPlus:
  422. model: LazyModel
  423. paths: list[Path] # Where this was read from.
  424. format: Literal['ggml', 'torch', 'safetensors', 'none']
  425. vocab: Vocab | None # For GGML models (which have vocab built in), the vocab.
  426. def merge_sharded(models: list[LazyModel]) -> LazyModel:
  427. # Original LLaMA models have each file contain one part of each tensor.
  428. # Use a dict instead of a set to preserve order.
  429. names = {name: None for model in models for name in model}
  430. def convert(name: str) -> LazyTensor:
  431. lazy_tensors: list[LazyTensor] = [model[name] for model in models]
  432. if len(lazy_tensors) == 1:
  433. # only one file; don't go through this procedure since there might
  434. # be quantized tensors
  435. return lazy_tensors[0]
  436. if len(lazy_tensors[0].shape) == 1:
  437. # the tensor is just duplicated in every file
  438. return lazy_tensors[0]
  439. if name.startswith('tok_embeddings.') or \
  440. name.endswith('.attention.wo.weight') or \
  441. name.endswith('.feed_forward.w2.weight'):
  442. # split by columns
  443. axis = 1
  444. else:
  445. # split by rows
  446. axis = 0
  447. concatenated_shape = list(lazy_tensors[0].shape)
  448. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  449. def load() -> UnquantizedTensor:
  450. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  451. concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
  452. return UnquantizedTensor(concatenated)
  453. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  454. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  455. return {name: convert(name) for name in names}
  456. def merge_multifile_models(models_plus: list[ModelPlus]) -> ModelPlus:
  457. formats = set(mp.format for mp in models_plus)
  458. assert len(formats) == 1, "different formats?"
  459. format = formats.pop()
  460. paths = [path for mp in models_plus for path in mp.paths]
  461. # Use the first non-None vocab, if any.
  462. try:
  463. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  464. except StopIteration:
  465. vocab = None
  466. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  467. # Transformers models put different tensors in different files, but
  468. # don't split indivdual tensors between files.
  469. model: LazyModel = {}
  470. for mp in models_plus:
  471. model.update(mp.model)
  472. else:
  473. model = merge_sharded([mp.model for mp in models_plus])
  474. return ModelPlus(model, paths, format, vocab)
  475. def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
  476. def load() -> Tensor:
  477. return lazy_tensor.load().permute(n_head, n_head_kv)
  478. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  479. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int, n_head_kv: int) -> LazyTensor:
  480. def load() -> Tensor:
  481. return lazy_tensor.load().permute_part(n_part, n_head, n_head_kv)
  482. s = lazy_tensor.shape.copy()
  483. s[0] = s[0] // 3
  484. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  485. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  486. def load() -> Tensor:
  487. return lazy_tensor.load().part(n_part)
  488. s = lazy_tensor.shape.copy()
  489. s[0] = s[0] // 3
  490. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  491. # Functionality that simulates `torch.load` but where individual tensors are
  492. # only loaded into memory on demand, not all at once.
  493. # PyTorch can't do this natively as of time of writing:
  494. # - https://github.com/pytorch/pytorch/issues/64327
  495. # This allows us to de-shard without multiplying RAM usage, and also
  496. # conveniently drops the PyTorch dependency (though we still need numpy).
  497. @dataclass
  498. class LazyStorageKind:
  499. data_type: DataType
  500. @dataclass
  501. class LazyStorage:
  502. load: Callable[[int, int], NDArray]
  503. kind: LazyStorageKind
  504. description: str
  505. class LazyUnpickler(pickle.Unpickler):
  506. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  507. super().__init__(fp)
  508. self.data_base_path = data_base_path
  509. self.zip_file = zip_file
  510. def persistent_load(self, pid: Any) -> Any:
  511. assert pid[0] == 'storage'
  512. assert isinstance(pid[1], LazyStorageKind)
  513. data_type = pid[1].data_type
  514. filename_stem = pid[2]
  515. filename = f'{self.data_base_path}/{filename_stem}'
  516. info = self.zip_file.getinfo(filename)
  517. def load(offset: int, elm_count: int) -> NDArray:
  518. dtype = data_type.dtype
  519. fp = self.zip_file.open(info)
  520. fp.seek(offset * dtype.itemsize)
  521. size = elm_count * dtype.itemsize
  522. data = fp.read(size)
  523. assert len(data) == size
  524. return np.frombuffer(data, dtype)
  525. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  526. return LazyStorage(load=load, kind=pid[1], description=description)
  527. @staticmethod
  528. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  529. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  530. assert isinstance(storage, LazyStorage)
  531. def load() -> UnquantizedTensor:
  532. elm_count = stride[0] * size[0]
  533. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  534. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  535. return LazyTensor(load, list(size), storage.kind.data_type, description)
  536. @staticmethod
  537. def rebuild_from_type_v2(func, new_type, args, state):
  538. return func(*args)
  539. CLASSES: dict[tuple[str, str], Any] = {
  540. # getattr used here as a workaround for mypy not being smart enough to detrmine
  541. # the staticmethods have a __func__ attribute.
  542. ('torch._tensor', '_rebuild_from_type_v2'): getattr(rebuild_from_type_v2, '__func__'),
  543. ('torch._utils', '_rebuild_tensor_v2'): getattr(lazy_rebuild_tensor_v2, '__func__'),
  544. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  545. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  546. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  547. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  548. ('torch', 'Tensor'): LazyTensor,
  549. }
  550. def find_class(self, module: str, name: str) -> Any:
  551. if not module.startswith('torch'):
  552. return super().find_class(module, name)
  553. return self.CLASSES[(module, name)]
  554. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  555. zf = zipfile.ZipFile(outer_fp)
  556. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  557. assert len(pickle_paths) == 1, pickle_paths
  558. pickle_fp = zf.open(pickle_paths[0], 'r')
  559. unpickler = LazyUnpickler(pickle_fp,
  560. data_base_path=pickle_paths[0][:-4],
  561. zip_file=zf)
  562. model = unpickler.load()
  563. if 'model' in model: model = model['model']
  564. as_dict = dict(model.items())
  565. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  566. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  567. header_size, = struct.unpack('<Q', fp.read(8))
  568. header: dict[str, dict[str, Any]] = json.loads(fp.read(header_size))
  569. # Use mmap for the actual data to avoid race conditions with the file offset.
  570. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  571. byte_buf = mapped[8 + header_size:]
  572. def convert(info: dict[str, Any]) -> LazyTensor:
  573. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  574. numpy_dtype = data_type.dtype
  575. shape: list[int] = info['shape']
  576. begin, end = info['data_offsets']
  577. assert 0 <= begin <= end <= len(byte_buf)
  578. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  579. buf = byte_buf[begin:end]
  580. def load() -> UnquantizedTensor:
  581. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  582. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  583. return LazyTensor(load, shape, data_type, description)
  584. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  585. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  586. def must_read(fp: IO[bytes], length: int) -> bytes:
  587. ret = fp.read(length)
  588. if len(ret) < length:
  589. raise Exception("unexpectedly reached end of file")
  590. return ret
  591. @functools.lru_cache(maxsize=None)
  592. def lazy_load_file(path: Path) -> ModelPlus:
  593. fp = open(path, 'rb')
  594. first8 = fp.read(8)
  595. fp.seek(0)
  596. if first8[:2] == b'PK':
  597. # A zip file, i.e. PyTorch format
  598. return lazy_load_torch_file(fp, path)
  599. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  600. # Probably safetensors
  601. return lazy_load_safetensors_file(fp, path)
  602. else:
  603. raise ValueError(f"unknown format: {path}")
  604. In = TypeVar('In')
  605. Out = TypeVar('Out')
  606. 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]:
  607. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  608. fast enough, this will stop calling `func` at some point rather than
  609. letting results pile up in memory. Specifically, there is a max of one
  610. output value buffered per thread.'''
  611. if concurrency < 2:
  612. yield from map(func, iterable)
  613. # Not reached.
  614. iterable = iter(iterable)
  615. executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor]
  616. if use_processpool_executor:
  617. executor_class = ProcessPoolExecutor
  618. else:
  619. executor_class = ThreadPoolExecutor
  620. with executor_class(max_workers = max_workers) as executor:
  621. futures: list[concurrent.futures.Future[Out]] = []
  622. done = False
  623. for _ in range(concurrency):
  624. try:
  625. futures.append(executor.submit(func, next(iterable)))
  626. except StopIteration:
  627. done = True
  628. break
  629. while futures:
  630. result = futures.pop(0).result()
  631. while not done and len(futures) < concurrency:
  632. try:
  633. futures.append(executor.submit(func, next(iterable)))
  634. except StopIteration:
  635. done = True
  636. break
  637. yield result
  638. def check_vocab_size(params: Params, vocab: Vocab) -> None:
  639. if params.n_vocab != vocab.vocab_size:
  640. assert isinstance(vocab, BpeVocab) or isinstance(vocab, SentencePieceVocab)
  641. if params.n_vocab == vocab.vocab_size_base:
  642. print("Ignoring added_tokens.json since model matches vocab size without it.")
  643. vocab.added_tokens_list = []
  644. vocab.vocab_size = vocab.vocab_size_base
  645. return
  646. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
  647. if vocab.fname_added_tokens is not None:
  648. msg += f" combined with {vocab.fname_added_tokens}"
  649. msg += f" has {vocab.vocab_size})."
  650. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
  651. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  652. raise Exception(msg)
  653. class OutputFile:
  654. def __init__(self, fname_out: Path, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE) -> None:
  655. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH], endianess=endianess)
  656. def add_meta_arch(self, params: Params) -> None:
  657. name = "LLaMA"
  658. # TODO: better logic to determine model name
  659. if params.n_ctx == 4096:
  660. name = "LLaMA v2"
  661. elif params.path_model is not None:
  662. name = str(params.path_model.parent).split('/')[-1]
  663. self.gguf.add_name (name)
  664. self.gguf.add_context_length (params.n_ctx)
  665. self.gguf.add_embedding_length (params.n_embd)
  666. self.gguf.add_block_count (params.n_layer)
  667. self.gguf.add_feed_forward_length (params.n_ff)
  668. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  669. self.gguf.add_head_count (params.n_head)
  670. self.gguf.add_head_count_kv (params.n_head_kv)
  671. self.gguf.add_layer_norm_rms_eps (params.f_norm_eps)
  672. if params.f_rope_freq_base is not None:
  673. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  674. if params.rope_scaling_type:
  675. assert params.f_rope_scale is not None
  676. self.gguf.add_rope_scaling_type(params.rope_scaling_type)
  677. self.gguf.add_rope_scaling_factor(params.f_rope_scale)
  678. if params.n_orig_ctx is not None:
  679. self.gguf.add_rope_scaling_orig_ctx_len(params.n_orig_ctx)
  680. if params.rope_finetuned is not None:
  681. self.gguf.add_rope_scaling_finetuned(params.rope_finetuned)
  682. if params.ftype is not None:
  683. self.gguf.add_file_type(params.ftype)
  684. def add_meta_vocab(self, vocab: Vocab) -> None:
  685. tokens = []
  686. scores = []
  687. toktypes = []
  688. # NOTE: `all_tokens` returns the base vocabulary and added tokens
  689. for text, score, toktype in vocab.all_tokens():
  690. tokens.append(text)
  691. scores.append(score)
  692. toktypes.append(toktype)
  693. if isinstance(vocab, SentencePieceVocab):
  694. self.gguf.add_tokenizer_model("llama")
  695. elif isinstance(vocab, BpeVocab):
  696. self.gguf.add_tokenizer_model("gpt2")
  697. else:
  698. raise ValueError('Unknown vocab type: Not BpeVocab or SentencePieceVocab')
  699. self.gguf.add_token_list(tokens)
  700. self.gguf.add_token_scores(scores)
  701. self.gguf.add_token_types(toktypes)
  702. def add_meta_special_vocab(self, svocab: gguf.SpecialVocab) -> None:
  703. svocab.add_to_gguf(self.gguf)
  704. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  705. n_elements = int(np.prod(tensor.shape))
  706. raw_dtype = getattr(tensor.data_type, 'ggml_type', None)
  707. data_type = getattr(tensor.data_type, 'quantized_type', None) or tensor.data_type.dtype
  708. data_nbytes = tensor.data_type.elements_to_bytes(n_elements)
  709. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes, raw_dtype = raw_dtype)
  710. def write_meta(self) -> None:
  711. self.gguf.write_header_to_file()
  712. self.gguf.write_kv_data_to_file()
  713. def write_tensor_info(self) -> None:
  714. self.gguf.write_ti_data_to_file()
  715. def close(self) -> None:
  716. self.gguf.close()
  717. @staticmethod
  718. def write_vocab_only(fname_out: Path, params: Params, vocab: Vocab, svocab: gguf.SpecialVocab, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE) -> None:
  719. check_vocab_size(params, vocab)
  720. of = OutputFile(fname_out, endianess=endianess)
  721. # meta data
  722. of.add_meta_arch(params)
  723. of.add_meta_vocab(vocab)
  724. of.add_meta_special_vocab(svocab)
  725. of.write_meta()
  726. of.close()
  727. @staticmethod
  728. def do_item(item: tuple[str, LazyTensor]) -> tuple[DataType, NDArray]:
  729. name, lazy_tensor = item
  730. tensor = lazy_tensor.load().to_ggml()
  731. return (lazy_tensor.data_type, tensor.ndarray)
  732. @staticmethod
  733. def maybe_do_quantize(item: tuple[DataType, NDArray]) -> NDArray:
  734. dt, arr = item
  735. if not isinstance(dt, QuantizedDataType):
  736. return arr
  737. return dt.quantize(arr)
  738. @staticmethod
  739. def write_all(fname_out: Path, ftype: GGMLFileType, params: Params, model: LazyModel, vocab: Vocab, svocab: gguf.SpecialVocab, concurrency: int = DEFAULT_CONCURRENCY, endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE) -> None:
  740. check_vocab_size(params, vocab)
  741. of = OutputFile(fname_out, endianess=endianess)
  742. # meta data
  743. of.add_meta_arch(params)
  744. of.add_meta_vocab(vocab)
  745. of.add_meta_special_vocab(svocab)
  746. # tensor info
  747. for name, lazy_tensor in model.items():
  748. of.add_tensor_info(name, lazy_tensor)
  749. of.write_meta()
  750. of.write_tensor_info()
  751. # tensor data
  752. ndarrays_inner = bounded_parallel_map(OutputFile.do_item, model.items(), concurrency = concurrency)
  753. if ftype == GGMLFileType.MostlyQ8_0:
  754. ndarrays = bounded_parallel_map(OutputFile.maybe_do_quantize, ndarrays_inner, concurrency = concurrency, max_workers = concurrency, use_processpool_executor = True)
  755. else:
  756. ndarrays = map(OutputFile.maybe_do_quantize, ndarrays_inner)
  757. start = time.time()
  758. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  759. elapsed = time.time() - start
  760. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  761. padi = len(str(len(model)))
  762. print(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}")
  763. of.gguf.write_tensor_data(ndarray)
  764. of.close()
  765. def pick_output_type(model: LazyModel, output_type_str: str | None) -> GGMLFileType:
  766. wq_type = model[gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0) +".weight"].data_type
  767. if output_type_str == "f32" or (output_type_str is None and wq_type == DT_F32):
  768. return GGMLFileType.AllF32
  769. if output_type_str == "f16" or (output_type_str is None and wq_type in (DT_F16, DT_BF16)):
  770. return GGMLFileType.MostlyF16
  771. if output_type_str == "q8_0":
  772. return GGMLFileType.MostlyQ8_0
  773. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  774. raise Exception(f"Unexpected combination of types: {name_to_type}")
  775. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  776. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  777. for (name, tensor) in model.items()}
  778. def convert_model_names(model: LazyModel, params: Params) -> LazyModel:
  779. tmap = gguf.TensorNameMap(ARCH, params.n_layer)
  780. should_skip: set[gguf.MODEL_TENSOR] = set(gguf.MODEL_TENSOR_SKIP.get(ARCH, []))
  781. tmp = model
  782. # HF models permut or pack some of the tensors, so we need to undo that
  783. for i in itertools.count():
  784. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  785. print(f"Permuting layer {i}")
  786. 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)
  787. 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)
  788. # tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  789. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  790. print(f"Unpacking and permuting layer {i}")
  791. 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)
  792. 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)
  793. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  794. del tmp[f"model.layers.{i}.self_attn.W_pack.weight"]
  795. else:
  796. break
  797. out: LazyModel = {}
  798. for name, lazy_tensor in model.items():
  799. tensor_type, name_new = tmap.get_type_and_name(name, try_suffixes = (".weight", ".bias")) or (None, None)
  800. if name_new is None:
  801. raise Exception(f"Unexpected tensor name: {name}")
  802. if tensor_type in should_skip:
  803. print(f"skipping tensor {name_new}")
  804. continue
  805. print(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type.name:6s} | {lazy_tensor.shape}")
  806. out[name_new] = lazy_tensor
  807. return out
  808. def nth_multifile_path(path: Path, n: int) -> Path | None:
  809. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  810. the nth path in the model.
  811. '''
  812. # Support the following patterns:
  813. patterns: list[tuple[str, str]] = [
  814. # - x.00.pth, x.01.pth, etc.
  815. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  816. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  817. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  818. # x.bin, x.bin.1, etc.
  819. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  820. ]
  821. for regex, replacement in patterns:
  822. if re.search(regex, path.name):
  823. new_path = path.with_name(re.sub(regex, replacement, path.name))
  824. if new_path.exists():
  825. return new_path
  826. return None
  827. def find_multifile_paths(path: Path) -> list[Path]:
  828. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  829. the whole list of paths in the model.
  830. '''
  831. ret: list[Path] = []
  832. for i in itertools.count():
  833. nth_path = nth_multifile_path(path, i)
  834. if nth_path is None:
  835. break
  836. ret.append(nth_path)
  837. if not ret:
  838. # No matches. This should only happen if the file was named, e.g.,
  839. # foo.0, and there was no file named foo. Oh well, try to process it
  840. # as a single file.
  841. return [path]
  842. return ret
  843. def load_some_model(path: Path) -> ModelPlus:
  844. '''Load a model of any supported format.'''
  845. # Be extra-friendly and accept either a file or a directory:
  846. if path.is_dir():
  847. # Check if it's a set of safetensors files first
  848. globs = ["model-00001-of-*.safetensors", "model.safetensors"]
  849. files = [file for glob in globs for file in path.glob(glob)]
  850. if not files:
  851. # Try the PyTorch patterns too, with lower priority
  852. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  853. files = [file for glob in globs for file in path.glob(glob)]
  854. if not files:
  855. raise Exception(f"Can't find model in directory {path}")
  856. if len(files) > 1:
  857. raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
  858. path = files[0]
  859. paths = find_multifile_paths(path)
  860. models_plus: list[ModelPlus] = []
  861. for path in paths:
  862. print(f"Loading model file {path}")
  863. models_plus.append(lazy_load_file(path))
  864. model_plus = merge_multifile_models(models_plus)
  865. return model_plus
  866. def load_vocab(path: Path, vocabtype: str | None) -> Vocab:
  867. # Be extra-friendly and accept either a file or a directory. Also, if it's
  868. # a directory, it might be the model directory, and tokenizer.model might
  869. # be in the parent of that.
  870. if path.is_dir():
  871. vocab_file = "tokenizer.model"
  872. if vocabtype == 'bpe':
  873. vocab_file = "vocab.json"
  874. path2 = path / vocab_file
  875. # Use `.parent` instead of /.. to handle the symlink case better.
  876. path3 = path.parent / vocab_file
  877. if path2.exists():
  878. path = path2
  879. elif path3.exists():
  880. path = path3
  881. else:
  882. raise FileNotFoundError(
  883. f"Could not find {vocab_file} in {path} or its parent; "
  884. "if it's in another directory, pass the directory as --vocab-dir")
  885. print(f"Loading vocab file '{path}', type '{vocabtype}'")
  886. added_tokens_path = path.parent / "added_tokens.json"
  887. if vocabtype == "bpe":
  888. return BpeVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  889. elif vocabtype == "spm":
  890. return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  891. else:
  892. raise ValueError(f"Unsupported vocabulary type {vocabtype}")
  893. def default_outfile(model_paths: list[Path], file_type: GGMLFileType) -> Path:
  894. namestr = {
  895. GGMLFileType.AllF32: "f32",
  896. GGMLFileType.MostlyF16: "f16",
  897. GGMLFileType.MostlyQ8_0:"q8_0",
  898. }[file_type]
  899. ret = model_paths[0].parent / f"ggml-model-{namestr}.gguf"
  900. if ret in model_paths:
  901. sys.stderr.write(
  902. f"Error: Default output path ({ret}) would overwrite the input. "
  903. "Please explicitly specify a path using --outfile.\n")
  904. sys.exit(1)
  905. return ret
  906. def do_dump_model(model_plus: ModelPlus) -> None:
  907. print(f"model_plus.paths = {model_plus.paths!r}")
  908. print(f"model_plus.format = {model_plus.format!r}")
  909. print(f"model_plus.vocab = {model_plus.vocab!r}")
  910. for name, lazy_tensor in model_plus.model.items():
  911. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
  912. def main(args_in: list[str] | None = None) -> None:
  913. output_choices = ["f32", "f16"]
  914. if np.uint32(1) == np.uint32(1).newbyteorder("<"):
  915. # We currently only support Q8_0 output on little endian systems.
  916. output_choices.append("q8_0")
  917. parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
  918. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  919. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  920. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  921. parser.add_argument("--outtype", choices=output_choices, help="output format - note: q8_0 may be very slow (default: f16 or f32 based on input)")
  922. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  923. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  924. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin, *.safetensors)")
  925. parser.add_argument("--vocabtype", choices=["spm", "bpe"], help="vocab format (default: spm)", default="spm")
  926. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  927. parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default = DEFAULT_CONCURRENCY)
  928. parser.add_argument("--bigendian", action="store_true", help="model is executed on big endian machine")
  929. args = parser.parse_args(args_in)
  930. if args.dump_single:
  931. model_plus = lazy_load_file(args.model)
  932. do_dump_model(model_plus)
  933. return
  934. if not args.vocab_only:
  935. model_plus = load_some_model(args.model)
  936. else:
  937. model_plus = ModelPlus(model = {}, paths = [args.model / 'dummy'], format = 'none', vocab = None)
  938. if args.dump:
  939. do_dump_model(model_plus)
  940. return
  941. endianess = gguf.GGUFEndian.LITTLE
  942. if args.bigendian:
  943. endianess = gguf.GGUFEndian.BIG
  944. params = Params.load(model_plus)
  945. if params.n_ctx == -1:
  946. if args.ctx is None:
  947. raise Exception("The model doesn't have a context size, and you didn't specify one with --ctx\n"
  948. "Please specify one with --ctx:\n"
  949. " - LLaMA v1: --ctx 2048\n"
  950. " - LLaMA v2: --ctx 4096\n")
  951. params.n_ctx = args.ctx
  952. if args.outtype:
  953. params.ftype = {
  954. "f32": GGMLFileType.AllF32,
  955. "f16": GGMLFileType.MostlyF16,
  956. "q8_0": GGMLFileType.MostlyQ8_0,
  957. }[args.outtype]
  958. print(f"params = {params}")
  959. vocab: Vocab
  960. if args.vocab_only:
  961. if not args.outfile:
  962. raise ValueError("need --outfile if using --vocab-only")
  963. # FIXME: Try to respect vocab_dir somehow?
  964. vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype)
  965. special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent,
  966. load_merges = args.vocabtype == 'bpe',
  967. n_vocab = vocab.vocab_size)
  968. outfile = args.outfile
  969. OutputFile.write_vocab_only(outfile, params, vocab, special_vocab)
  970. print(f"Wrote {outfile}")
  971. return
  972. if model_plus.vocab is not None and args.vocab_dir is None:
  973. vocab = model_plus.vocab
  974. else:
  975. vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
  976. vocab = load_vocab(vocab_dir, args.vocabtype)
  977. # FIXME: Try to respect vocab_dir somehow?
  978. special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent,
  979. load_merges = args.vocabtype == 'bpe',
  980. n_vocab = vocab.vocab_size)
  981. model = model_plus.model
  982. model = convert_model_names(model, params)
  983. ftype = pick_output_type(model, args.outtype)
  984. model = convert_to_output_type(model, ftype)
  985. outfile = args.outfile or default_outfile(model_plus.paths, ftype)
  986. params.ftype = ftype
  987. print(f"Writing {outfile}, format {ftype}")
  988. OutputFile.write_all(outfile, ftype, params, model, vocab, special_vocab, concurrency = args.concurrency, endianess=endianess)
  989. print(f"Wrote {outfile}")
  990. if __name__ == '__main__':
  991. main()