1
0

convert.py 49 KB

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