convert.py 49 KB

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