convert.py 48 KB

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