convert.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. #!/usr/bin/env python
  2. import argparse
  3. import concurrent.futures
  4. import copy
  5. import enum
  6. import faulthandler
  7. import functools
  8. import io
  9. import itertools
  10. import json
  11. import math
  12. import mmap
  13. import pickle
  14. import re
  15. import signal
  16. import struct
  17. import sys
  18. import zipfile
  19. from abc import ABCMeta, abstractmethod
  20. from dataclasses import dataclass
  21. from pathlib import Path
  22. from typing import (IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List,
  23. Literal, Optional, Sequence, Tuple, TypeVar, Union)
  24. import numpy as np
  25. from sentencepiece import SentencePieceProcessor # type: ignore
  26. if TYPE_CHECKING:
  27. from typing_extensions import TypeAlias
  28. if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
  29. faulthandler.register(signal.SIGUSR1)
  30. NDArray: 'TypeAlias' = 'np.ndarray[Any, Any]'
  31. @dataclass(frozen=True)
  32. class UnquantizedDataType:
  33. name: str
  34. DT_F16 = UnquantizedDataType('F16')
  35. DT_F32 = UnquantizedDataType('F32')
  36. DT_I32 = UnquantizedDataType('I32')
  37. DT_BF16 = UnquantizedDataType('BF16')
  38. @dataclass(frozen=True)
  39. class QuantizedDataType:
  40. groupsize: int
  41. have_addends: bool
  42. have_g_idx: bool
  43. DT_Q4_0 = QuantizedDataType(groupsize=32, have_addends=False, have_g_idx=False)
  44. DT_Q4_1 = QuantizedDataType(groupsize=32, have_addends=True, have_g_idx=False)
  45. DataType = Union[UnquantizedDataType, QuantizedDataType]
  46. DATA_TYPE_TO_FTYPE: Dict[DataType, int] = {
  47. DT_F32: 0,
  48. DT_F16: 1,
  49. DT_Q4_0: 2,
  50. DT_Q4_1: 3,
  51. }
  52. FTYPE_TO_DATA_TYPE: Dict[int, DataType] = \
  53. {ftype: dtype for (dtype, ftype) in DATA_TYPE_TO_FTYPE.items()}
  54. DATA_TYPE_TO_NUMPY: Dict[DataType, 'np.dtype[Any]'] = {
  55. DT_BF16: np.dtype(np.uint16),
  56. DT_F16: np.dtype(np.float16),
  57. DT_F32: np.dtype(np.float32),
  58. DT_I32: np.dtype(np.int32),
  59. }
  60. NUMPY_TYPE_TO_DATA_TYPE: Dict['np.dtype[Any]', DataType] = \
  61. {dtype: data_type for (data_type, dtype) in DATA_TYPE_TO_NUMPY.items()}
  62. class GGMLFileType(enum.Enum):
  63. AllF32 = 0
  64. MostlyF16 = 1 # except 1d tensors
  65. MostlyQ4_0 = 2 # except 1d tensors
  66. MostlyQ4_1 = 3 # except 1d tensors
  67. PerLayerIsQ4_1 = 4 # but tok_embeddings.weight and output.weight are F16
  68. def type_for_tensor(self, name: str, tensor: 'LazyTensor') -> DataType:
  69. if len(tensor.shape) == 1:
  70. # 1D tensors are always F32.
  71. return DT_F32
  72. elif self == GGMLFileType.AllF32:
  73. return DT_F32
  74. elif self == GGMLFileType.MostlyF16:
  75. return DT_F16
  76. elif self == GGMLFileType.MostlyQ4_0:
  77. return DT_Q4_0
  78. elif self == GGMLFileType.MostlyQ4_1:
  79. return DT_Q4_1
  80. elif self == GGMLFileType.PerLayerIsQ4_1:
  81. if name in ('output.weight', 'tok_embeddings.weight'):
  82. return DT_F16
  83. else:
  84. return DT_Q4_1
  85. else:
  86. raise ValueError(self)
  87. def make_tensors_list() -> List[str]:
  88. ret = [
  89. 'tok_embeddings.weight',
  90. 'norm.weight',
  91. 'output.weight',
  92. ]
  93. for i in range(80): # maximum number of layer
  94. ret += [
  95. f'layers.{i}.attention.wq.weight',
  96. f'layers.{i}.attention.wk.weight',
  97. f'layers.{i}.attention.wv.weight',
  98. f'layers.{i}.attention.wo.weight',
  99. f'layers.{i}.attention_norm.weight',
  100. f'layers.{i}.feed_forward.w1.weight',
  101. f'layers.{i}.feed_forward.w2.weight',
  102. f'layers.{i}.feed_forward.w3.weight',
  103. f'layers.{i}.ffn_norm.weight',
  104. ]
  105. return ret
  106. TENSORS_LIST = make_tensors_list()
  107. TENSORS_SET = set(TENSORS_LIST)
  108. def find_n_mult(n_ff: int, n_embd: int) -> int:
  109. # hardcoded magic range
  110. for n_mult in range(256, 1, -1):
  111. calc_ff = (((8*n_embd) // 3 + n_mult - 1) // n_mult)*n_mult
  112. if calc_ff == n_ff:
  113. return n_mult
  114. raise Exception(f"failed to find n_mult for (n_ff={n_ff}, n_embd={n_embd}).")
  115. @dataclass
  116. class Params:
  117. n_vocab: int
  118. n_embd: int
  119. n_mult: int
  120. n_head: int
  121. n_layer: int
  122. @staticmethod
  123. def guessed(model: 'LazyModel') -> 'Params':
  124. # try transformer naming first
  125. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  126. # try transformer naming first
  127. if "model.layers.0.self_attn.q_proj.weight" in model:
  128. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  129. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  130. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  131. else:
  132. n_layer=next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  133. if n_layer < 1:
  134. raise Exception("failed to guess 'n_layer'. This model is unknown or unsupported.\n"
  135. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  136. n_head=n_embd // 128 # guessed
  137. return Params(
  138. n_vocab = n_vocab,
  139. n_embd = n_embd,
  140. n_mult = 256,
  141. n_head = n_head,
  142. n_layer = n_layer,
  143. )
  144. @staticmethod
  145. def loadHFTransformerJson(model: 'LazyModel', config_path: 'Path') -> 'Params':
  146. config = json.load(open(config_path))
  147. n_vocab = config["vocab_size"];
  148. n_embd = config["hidden_size"];
  149. n_head = config["num_attention_heads"];
  150. n_layer = config["num_hidden_layers"];
  151. n_ff = config["intermediate_size"];
  152. n_mult = find_n_mult(n_ff, n_embd);
  153. return Params(
  154. n_vocab = n_vocab,
  155. n_embd = n_embd,
  156. n_mult = n_mult,
  157. n_head = n_head,
  158. n_layer = n_layer,
  159. )
  160. # LLaMA v2 70B params.json
  161. # {"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
  162. @staticmethod
  163. def loadOriginalParamsJson(model: 'LazyModel', config_path: 'Path') -> 'Params':
  164. config = json.load(open(config_path))
  165. n_vocab = config["vocab_size"];
  166. n_embd = config["dim"];
  167. n_head = config["n_heads"];
  168. n_layer = config["n_layers"];
  169. n_mult = config["multiple_of"];
  170. if n_vocab == -1:
  171. n_vocab = model["tok_embeddings.weight"].shape[0]
  172. return Params(
  173. n_vocab = n_vocab,
  174. n_embd = n_embd,
  175. n_mult = n_mult,
  176. n_head = n_head,
  177. n_layer = n_layer,
  178. )
  179. @staticmethod
  180. def load(model_plus: 'ModelPlus') -> 'Params':
  181. hf_config_path = model_plus.paths[0].parent / "config.json"
  182. orig_config_path = model_plus.paths[0].parent / "params.json"
  183. if hf_config_path.exists():
  184. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  185. elif orig_config_path.exists():
  186. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  187. else:
  188. params = Params.guessed(model_plus.model)
  189. print(f'params: n_vocab:{params.n_vocab} n_embd:{params.n_embd} n_mult:{params.n_mult} n_head:{params.n_head} n_layer:{params.n_layer}')
  190. return params
  191. class SentencePieceVocab:
  192. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
  193. self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
  194. added_tokens: Dict[str, int]
  195. if fname_added_tokens is not None:
  196. added_tokens = json.load(open(fname_added_tokens))
  197. else:
  198. added_tokens = {}
  199. vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
  200. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  201. actual_ids = sorted(added_tokens.values())
  202. if expected_ids != actual_ids:
  203. raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
  204. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  205. self.added_tokens_list = [text for (text, idx) in items]
  206. self.vocab_size_base: int = vocab_size
  207. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  208. self.fname_tokenizer = fname_tokenizer
  209. self.fname_added_tokens = fname_added_tokens
  210. def sentencepiece_tokens(self) -> Iterable[Tuple[bytes, float]]:
  211. tokenizer = self.sentencepiece_tokenizer
  212. for i in range(tokenizer.vocab_size()):
  213. text: bytes
  214. if tokenizer.is_unknown(i):
  215. text = " \u2047 ".encode("utf-8")
  216. elif tokenizer.is_control(i):
  217. text = b""
  218. elif tokenizer.is_byte(i):
  219. piece = tokenizer.id_to_piece(i)
  220. if len(piece) != 6:
  221. raise Exception(f"Invalid token: {piece}")
  222. byte_value = int(piece[3:-1], 16)
  223. text = struct.pack("B", byte_value)
  224. else:
  225. text = tokenizer.id_to_piece(i).replace("\u2581", " ").encode("utf-8")
  226. score: float = tokenizer.get_score(i)
  227. yield text, score
  228. def added_tokens(self) -> Iterable[Tuple[bytes, float]]:
  229. for text in self.added_tokens_list:
  230. score = -1000.0
  231. yield text.encode("utf-8"), score
  232. def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
  233. yield from self.sentencepiece_tokens()
  234. yield from self.added_tokens()
  235. def __repr__(self) -> str:
  236. return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  237. class GGMLVocab:
  238. def __init__(self, tokens: List[Tuple[bytes, float]]):
  239. self.tokens = tokens
  240. self.vocab_size = len(tokens)
  241. def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
  242. return self.tokens
  243. def __repr__(self) -> str:
  244. return f"<GGMLVocab with {self.vocab_size} tokens>"
  245. Vocab = Union[SentencePieceVocab, GGMLVocab]
  246. def permute(weights: NDArray, n_head: int) -> NDArray:
  247. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  248. .swapaxes(1, 2)
  249. .reshape(weights.shape))
  250. def dequantize_q4(qvalues_pack32: NDArray, scales: NDArray, addends: Optional[NDArray], g_idx: Optional[NDArray]) -> NDArray:
  251. # First reinterpret each row from a list of int32s containing 8 values each
  252. # to a list of uint8s containing 2 values each.
  253. qvalues_pack8 = qvalues_pack32.view(np.uint8)
  254. # Then split out the two values per int8 (which requires an actual
  255. # conversion because numpy doesn't natively support int4s).
  256. qvalues = np.zeros([qvalues_pack8.shape[0], qvalues_pack8.shape[1] * 2], dtype=np.uint8)
  257. qvalues[:, 0::2] = qvalues_pack8 & 0xf
  258. qvalues[:, 1::2] = qvalues_pack8 >> 4
  259. assert addends is None or addends.shape == scales.shape
  260. assert qvalues.shape[0] == scales.shape[0]
  261. assert qvalues.shape[1] % scales.shape[1] == 0
  262. if g_idx is None:
  263. repeat_count = qvalues.shape[1] // scales.shape[1]
  264. scales = scales[:, :, np.newaxis]
  265. if addends is not None:
  266. addends = addends[:, :, np.newaxis]
  267. # Reshape so that the below computation broadcasts over scales and addends:
  268. qvalues.shape = (qvalues.shape[0], scales.shape[1], int(repeat_count))
  269. else:
  270. # In this case the scale and addend is selected for each column by g_idx:
  271. assert addends is not None
  272. scales = scales[:, g_idx]
  273. addends = addends[:, g_idx]
  274. if addends is None:
  275. # Q4_0
  276. qvalues = qvalues.view(np.int8)
  277. qvalues -= 8
  278. # And do the actual 'value = scale * qvalue + addend' computation.
  279. values = scales * qvalues
  280. if addends is not None:
  281. values += addends
  282. if g_idx is None:
  283. values.shape = (values.shape[0], values.shape[1] * values.shape[2])
  284. return values
  285. class Tensor(metaclass=ABCMeta):
  286. data_type: DataType
  287. @abstractmethod
  288. def astype(self, data_type: DataType) -> 'Tensor': ...
  289. @abstractmethod
  290. def permute(self, n_head: int) -> 'Tensor': ...
  291. @abstractmethod
  292. def permute_part(self, n_part: int, n_head: int) -> 'UnquantizedTensor': ...
  293. @abstractmethod
  294. def part(self, n_part: int) -> 'UnquantizedTensor': ...
  295. @abstractmethod
  296. def to_ggml(self) -> 'GGMLCompatibleTensor': ...
  297. def bf16_to_fp32(bf16_arr: np.ndarray) -> np.ndarray:
  298. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  299. fp32_arr = bf16_arr.astype(np.uint32) << 16
  300. return fp32_arr.view(np.float32)
  301. class UnquantizedTensor(Tensor):
  302. def __init__(self, ndarray: NDArray) -> None:
  303. assert isinstance(ndarray, np.ndarray)
  304. self.ndarray = ndarray
  305. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  306. def astype(self, data_type: DataType) -> Tensor:
  307. dtype = DATA_TYPE_TO_NUMPY[data_type]
  308. if self.data_type == DT_BF16:
  309. self.ndarray = bf16_to_fp32(self.ndarray)
  310. return UnquantizedTensor(self.ndarray.astype(dtype))
  311. def to_ggml(self) -> 'UnquantizedTensor':
  312. return self
  313. def permute_part(self, n_part: int, n_head: int) -> 'UnquantizedTensor':
  314. r = self.ndarray.shape[0] // 3
  315. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head))
  316. def part(self, n_part: int) -> 'UnquantizedTensor':
  317. r = self.ndarray.shape[0] // 3
  318. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  319. def permute(self, n_head: int) -> 'UnquantizedTensor':
  320. return UnquantizedTensor(permute(self.ndarray, n_head))
  321. def load_unquantized(lazy_tensor: 'LazyTensor', expected_dtype: Any = None, convert: bool = False) -> NDArray:
  322. tensor = lazy_tensor.load()
  323. assert isinstance(tensor, UnquantizedTensor)
  324. # double-check:
  325. actual_shape = list(tensor.ndarray.shape)
  326. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  327. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  328. if convert:
  329. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  330. else:
  331. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  332. return tensor.ndarray
  333. class GGMLQuantizedTensor(Tensor):
  334. data_type: QuantizedDataType
  335. def __init__(self, ndarray: NDArray, shape: List[int], data_type: DataType) -> None:
  336. rows, columns = shape
  337. assert data_type in (DT_Q4_1, DT_Q4_0) # for now
  338. assert isinstance(data_type, QuantizedDataType) # redundant, but mypy complains without this
  339. assert columns % data_type.groupsize == 0
  340. words_in_block = 6 if data_type == DT_Q4_1 else 5
  341. self.ndarray = ndarray.view(dtype=np.uint32).reshape((rows, columns // data_type.groupsize, words_in_block))
  342. self.shape = shape[:]
  343. self.data_type = data_type
  344. def astype(self, data_type: DataType) -> Tensor:
  345. if data_type == self.data_type:
  346. return self
  347. scales = self.ndarray[:, :, 0].view(np.float32)
  348. if self.data_type.have_addends:
  349. addends = self.ndarray[:, :, 1].view(np.float32)
  350. else:
  351. addends = None
  352. qweights = self.ndarray[:, :, -4:].reshape([self.shape[0], self.shape[1] // 8])
  353. dq = dequantize_q4(qweights, scales, addends, g_idx=None)
  354. return UnquantizedTensor(dq).astype(data_type)
  355. def to_ggml(self) -> 'GGMLQuantizedTensor':
  356. return self
  357. def permute(self, n_head: int) -> 'GGMLQuantizedTensor':
  358. return GGMLQuantizedTensor(permute(self.ndarray, n_head), self.shape, self.data_type)
  359. GGMLCompatibleTensor = Union[UnquantizedTensor, GGMLQuantizedTensor]
  360. class DeferredPermutedTensor(Tensor):
  361. def __init__(self, base: Tensor, n_head: int) -> None:
  362. self.base = base
  363. self.n_head = n_head
  364. self.data_type = self.base.data_type
  365. def astype(self, data_type: DataType) -> Tensor:
  366. return self.base.astype(data_type).permute(self.n_head)
  367. def to_ggml(self) -> GGMLCompatibleTensor:
  368. return self.base.to_ggml().permute(self.n_head)
  369. def permute(self, n_head: int) -> Tensor:
  370. raise Exception("shouldn't permute twice")
  371. class GPTQForLLaMaQuantizedTensor(Tensor):
  372. def __init__(self, model: 'LazyModel', namebase: str) -> None:
  373. qweight = load_unquantized(model[f"{namebase}.qweight"], np.int32)
  374. scales = load_unquantized(model[f"{namebase}.scales"], np.float32, convert=True)
  375. bias = model.get(f"{namebase}.bias")
  376. if bias is not None:
  377. # Q4_1 does not support bias; good thing the bias is always all zeros.
  378. assert not np.any(load_unquantized(bias))
  379. if f"{namebase}.zeros" in model:
  380. zeros = load_unquantized(model[f"{namebase}.zeros"], np.float32)
  381. else:
  382. qzeros = load_unquantized(model[f"{namebase}.qzeros"], np.int32)
  383. assert qzeros.dtype == np.int32
  384. zeros = dequantize_q4(qzeros, scales, scales, g_idx=None)
  385. assert zeros.dtype == np.float32
  386. assert zeros.shape == scales.shape
  387. # Output is transposed compared to the input, and addends have their sign flipped.
  388. # Scales and zeros similarly must be transposed but only for newer
  389. # versions of GPTQ-for-LLaMa; the older versions can be identified by
  390. # having shape (n_embd, 1).
  391. qweight = qweight.T
  392. if scales.shape[1] != 1:
  393. scales = scales.T
  394. zeros = zeros.T
  395. # Output also has signs flipped for the addends.
  396. self.qweight = qweight
  397. self.scales = scales
  398. self.addends = -zeros
  399. self.g_idx: Optional[NDArray]
  400. if f"{namebase}.g_idx" in model:
  401. self.g_idx = load_unquantized(model[f"{namebase}.g_idx"], np.int32)
  402. assert self.g_idx.shape == (qweight.shape[1] * 8,)
  403. else:
  404. self.g_idx = None
  405. self.shape = [self.qweight.shape[0], self.qweight.shape[1] * 8]
  406. self.data_type = QuantizedDataType(groupsize=self.groupsize(), have_addends=True,
  407. have_g_idx=(self.g_idx is not None))
  408. def inspect(self, row: int, col: int) -> None:
  409. '''For debugging.'''
  410. qweight = (self.qweight[row, col // 8] >> (4 * (col & 7))) & 0xf
  411. if self.g_idx is not None:
  412. group = self.g_idx[col]
  413. else:
  414. group = int(col // self.groupsize())
  415. scale = self.scales[row, group]
  416. addend = self.addends[row, group]
  417. with np.printoptions(precision=None, suppress=True):
  418. print(f'scale:{scale} addend:{addend} qweight:{qweight}')
  419. print('possible values:', np.arange(16) * scale + addend)
  420. print('actual value:', qweight * scale + addend)
  421. def astype(self, data_type: DataType) -> Tensor:
  422. if isinstance(data_type, QuantizedDataType):
  423. assert self.g_idx is None and data_type.have_addends is True and data_type.have_g_idx is False
  424. return self.regroup(data_type.groupsize)
  425. dequantized = dequantize_q4(np.ascontiguousarray(self.qweight), self.scales, self.addends, self.g_idx)
  426. return UnquantizedTensor(dequantized).astype(data_type)
  427. def groupsize(self) -> int:
  428. assert self.addends.shape == self.scales.shape
  429. assert self.shape[1] % self.scales.shape[1] == 0
  430. return self.shape[1] // self.scales.shape[1]
  431. def regroup(self, new_groupsize: int = 32) -> 'GPTQForLLaMaQuantizedTensor':
  432. # Old versions of GPTQ-for-LLaMa shared scales and addends between all the
  433. # columns in a row. Newer versions share them between every set of N
  434. # columns in a row, where N is the `groupsize` parameter, usually 128. The
  435. # output format shares them between every set of 32 columns. To handle
  436. # this, duplicate scales and addends for every smaller group.
  437. # (In the above, 'row' and 'column' are in the sense of the output.)
  438. assert self.g_idx is None
  439. old_groupsize = self.groupsize()
  440. assert old_groupsize >= new_groupsize and old_groupsize % new_groupsize == 0, old_groupsize
  441. ret = copy.copy(self)
  442. ret.addends = self.addends.repeat(old_groupsize // new_groupsize, axis=1)
  443. ret.scales = self.scales.repeat(old_groupsize // new_groupsize, axis=1)
  444. ret.data_type = QuantizedDataType(groupsize=new_groupsize, have_addends=True, have_g_idx=False)
  445. return ret
  446. def permute(self, n_head: int) -> Tensor:
  447. return DeferredPermutedTensor(self, n_head)
  448. def to_ggml(self) -> GGMLQuantizedTensor:
  449. # The output format looks like this:
  450. # For each row:
  451. # For each group of 32 columns:
  452. # - addend (float32, 4 bytes)
  453. # - scale (float32, 4 bytes)
  454. # - weights (int4 * 32, 16 bytes)
  455. if self.groupsize() != 32:
  456. raise Exception("should have been regrouped before converting to ggml")
  457. # Since the output format is mixed between integers and floats, we have
  458. # to hackily view the floats as int32s just so numpy will let us
  459. # concatenate them.
  460. addends_view = self.addends.view(dtype=np.int32)[:, :, np.newaxis]
  461. scales_view = self.scales.view(dtype=np.int32)[:, :, np.newaxis]
  462. # Split into groups of 4 columns (i.e. 32 columns of quantized data):
  463. grouped = self.qweight.reshape([self.qweight.shape[0], self.qweight.shape[1] // 4, 4])
  464. # And concatenate:
  465. grouped = np.concatenate([scales_view, addends_view, grouped], axis=2, casting='no')
  466. return GGMLQuantizedTensor(grouped, self.shape, DT_Q4_1)
  467. @dataclass
  468. class LazyTensor:
  469. _load: Callable[[], Tensor]
  470. shape: List[int]
  471. data_type: DataType
  472. description: str
  473. def load(self) -> Tensor:
  474. ret = self._load()
  475. assert ret.data_type == self.data_type, (self.data_type, ret.data_type, self.description)
  476. return ret
  477. def astype(self, data_type: DataType) -> 'LazyTensor':
  478. self.validate_conversion_to(data_type)
  479. def load() -> Tensor:
  480. return self.load().astype(data_type)
  481. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  482. def validate_conversion_to(self, data_type: DataType) -> None:
  483. if data_type == self.data_type:
  484. return
  485. if isinstance(data_type, QuantizedDataType):
  486. if not isinstance(self.data_type, QuantizedDataType):
  487. raise Exception(f"Can't turn an unquantized tensor into a quantized type ({data_type})")
  488. if self.data_type.have_g_idx:
  489. sys.stderr.write(
  490. "Error: Input uses the newer GPTQ-for-LLaMa format (using g_idx), "
  491. "which is not yet natively supported by GGML. "
  492. "For now you can still convert this model by passing `--outtype f16` to dequantize, "
  493. "but that will result in a much larger output file for no quality benefit.\n")
  494. sys.exit(1)
  495. assert not data_type.have_g_idx and self.data_type.have_addends and data_type.have_addends
  496. LazyModel = Dict[str, LazyTensor]
  497. @dataclass
  498. class ModelPlus:
  499. model: LazyModel
  500. paths: List[Path] # Where this was read from.
  501. format: Literal['ggml', 'torch', 'safetensors']
  502. vocab: Optional[Vocab] # For GGML models (which have vocab built in), the vocab.
  503. def merge_sharded(models: List[LazyModel]) -> LazyModel:
  504. # Original LLaMA models have each file contain one part of each tensor.
  505. # Use a dict instead of a set to preserve order.
  506. names = {name: None for model in models for name in model}
  507. def convert(name: str) -> LazyTensor:
  508. lazy_tensors: List[LazyTensor] = [model[name] for model in models]
  509. if len(lazy_tensors) == 1:
  510. # only one file; don't go through this procedure since there might
  511. # be quantized tensors
  512. return lazy_tensors[0]
  513. if len(lazy_tensors[0].shape) == 1:
  514. # the tensor is just duplicated in every file
  515. return lazy_tensors[0]
  516. if name.startswith('tok_embeddings.') or \
  517. name.endswith('.attention.wo.weight') or \
  518. name.endswith('.feed_forward.w2.weight'):
  519. # split by columns
  520. axis = 1
  521. else:
  522. # split by rows
  523. axis = 0
  524. concatenated_shape = list(lazy_tensors[0].shape)
  525. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  526. def load() -> UnquantizedTensor:
  527. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  528. concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
  529. return UnquantizedTensor(concatenated)
  530. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  531. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  532. return {name: convert(name) for name in names}
  533. def merge_multifile_models(models_plus: List[ModelPlus]) -> ModelPlus:
  534. formats = set(mp.format for mp in models_plus)
  535. assert len(formats) == 1, "different formats?"
  536. format = formats.pop()
  537. paths = [path for mp in models_plus for path in mp.paths]
  538. # Use the first non-None vocab, if any.
  539. try:
  540. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  541. except StopIteration:
  542. vocab = None
  543. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  544. # Transformers models put different tensors in different files, but
  545. # don't split indivdual tensors between files.
  546. model: LazyModel = {}
  547. for mp in models_plus:
  548. model.update(mp.model)
  549. else:
  550. model = merge_sharded([mp.model for mp in models_plus])
  551. return ModelPlus(model, paths, format, vocab)
  552. def permute_lazy(lazy_tensor: LazyTensor, n_head: int) -> LazyTensor:
  553. def load() -> Tensor:
  554. return lazy_tensor.load().permute(n_head)
  555. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}) ' + lazy_tensor.description)
  556. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int) -> LazyTensor:
  557. def load() -> Tensor:
  558. return lazy_tensor.load().permute_part(n_part, n_head)
  559. s = lazy_tensor.shape.copy()
  560. s[0] = s[0] // 3
  561. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}) ' + lazy_tensor.description)
  562. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  563. def load() -> Tensor:
  564. return lazy_tensor.load().part(n_part)
  565. s = lazy_tensor.shape.copy()
  566. s[0] = s[0] // 3
  567. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  568. def convert_transformers_to_orig(model: LazyModel, params: Params) -> LazyModel:
  569. out: LazyModel = {}
  570. out["tok_embeddings.weight"] = model["model.embed_tokens.weight"]
  571. out["norm.weight"] = model["model.norm.weight"]
  572. out["output.weight"] = model["lm_head.weight"]
  573. for i in itertools.count():
  574. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  575. out[f"layers.{i}.attention.wq.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.q_proj.weight"], params.n_head)
  576. out[f"layers.{i}.attention.wk.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.k_proj.weight"], params.n_head)
  577. out[f"layers.{i}.attention.wv.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  578. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  579. out[f"layers.{i}.attention.wq.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 0, params.n_head)
  580. out[f"layers.{i}.attention.wk.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 1, params.n_head)
  581. out[f"layers.{i}.attention.wv.weight"] = part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  582. else:
  583. break
  584. out[f"layers.{i}.attention.wo.weight"] = model[f"model.layers.{i}.self_attn.o_proj.weight"]
  585. out[f"layers.{i}.feed_forward.w1.weight"] = model[f"model.layers.{i}.mlp.gate_proj.weight"]
  586. out[f"layers.{i}.feed_forward.w2.weight"] = model[f"model.layers.{i}.mlp.down_proj.weight"]
  587. out[f"layers.{i}.feed_forward.w3.weight"] = model[f"model.layers.{i}.mlp.up_proj.weight"]
  588. out[f"layers.{i}.attention_norm.weight"] = model[f"model.layers.{i}.input_layernorm.weight"]
  589. out[f"layers.{i}.ffn_norm.weight"] = model[f"model.layers.{i}.post_attention_layernorm.weight"]
  590. return out
  591. def handle_quantization(model: LazyModel) -> LazyModel:
  592. '''Convert a model with entries for 'foo.qweight', 'foo.scales', etc.
  593. (which resolve to UnquantizedTensors with the raw data) to one with entries
  594. for 'foo.weight' (which resolve to QuantizedTensors).
  595. '''
  596. def convert(name: str) -> Tuple[str, LazyTensor]:
  597. if name.endswith(".qweight"):
  598. namebase = name.rsplit('.', 1)[0]
  599. orig_name = namebase + ".weight"
  600. lazy_tensor = model[name]
  601. assert len(lazy_tensor.shape) == 2
  602. real_shape = [lazy_tensor.shape[1], lazy_tensor.shape[0] * 8]
  603. # Calculate type. This replicates the logic in
  604. # GPTQForLLaMaQuantizedTensor (which is executed when the modelis
  605. # actually loaded).
  606. lazy_scales = model[f"{namebase}.scales"]
  607. scales_width = 1 if lazy_scales.shape[1] == 1 else lazy_scales.shape[0]
  608. assert real_shape[1] % scales_width == 0
  609. groupsize = real_shape[1] // scales_width
  610. have_g_idx = f"{namebase}.g_idx" in model
  611. data_type = QuantizedDataType(groupsize=groupsize, have_addends=True, have_g_idx=have_g_idx)
  612. def load() -> Tensor:
  613. return GPTQForLLaMaQuantizedTensor(model, namebase)
  614. return (orig_name, LazyTensor(load, real_shape, data_type, '[quantized]'))
  615. else:
  616. return (name, model[name])
  617. return dict(convert(name) for name in model)
  618. # Functionality that simulates `torch.load` but where individual tensors are
  619. # only loaded into memory on demand, not all at once.
  620. # PyTorch can't do this natively as of time of writing:
  621. # - https://github.com/pytorch/pytorch/issues/64327
  622. # This allows us to de-shard without multiplying RAM usage, and also
  623. # conveniently drops the PyTorch dependency (though we still need numpy).
  624. @dataclass
  625. class LazyStorageKind:
  626. data_type: DataType
  627. @dataclass
  628. class LazyStorage:
  629. load: Callable[[int, int], NDArray]
  630. kind: LazyStorageKind
  631. description: str
  632. class LazyUnpickler(pickle.Unpickler):
  633. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  634. super().__init__(fp)
  635. self.data_base_path = data_base_path
  636. self.zip_file = zip_file
  637. def persistent_load(self, pid: Any) -> Any:
  638. assert pid[0] == 'storage'
  639. assert isinstance(pid[1], LazyStorageKind)
  640. data_type = pid[1].data_type
  641. filename_stem = pid[2]
  642. filename = self.data_base_path + '/' + filename_stem
  643. info = self.zip_file.getinfo(filename)
  644. def load(offset: int, elm_count: int) -> NDArray:
  645. dtype = DATA_TYPE_TO_NUMPY.get(data_type)
  646. if dtype is None:
  647. raise Exception("tensor stored in unsupported format")
  648. fp = self.zip_file.open(info)
  649. fp.seek(offset * dtype.itemsize)
  650. size = elm_count * dtype.itemsize
  651. data = fp.read(size)
  652. assert len(data) == size
  653. return np.frombuffer(data, dtype)
  654. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  655. return LazyStorage(load=load, kind=pid[1], description=description)
  656. # @staticmethod
  657. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  658. # pyright: ignore[reportSelfClsParameterName]
  659. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  660. assert isinstance(storage, LazyStorage)
  661. def load() -> UnquantizedTensor:
  662. elm_count = stride[0] * size[0]
  663. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  664. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  665. return LazyTensor(load, list(size), storage.kind.data_type, description)
  666. # @staticmethod
  667. def rebuild_from_type_v2(func, new_type, args, state):
  668. return func(*args)
  669. CLASSES: Dict[Any, Any] = {
  670. ('torch._tensor', '_rebuild_from_type_v2'): rebuild_from_type_v2,
  671. ('torch._utils', '_rebuild_tensor_v2'): lazy_rebuild_tensor_v2,
  672. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  673. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  674. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  675. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  676. ('torch', 'Tensor'): LazyTensor,
  677. }
  678. def find_class(self, module: str, name: str) -> Any:
  679. if not module.startswith('torch'):
  680. return super().find_class(module, name)
  681. return self.CLASSES[(module, name)]
  682. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  683. zf = zipfile.ZipFile(outer_fp)
  684. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  685. assert len(pickle_paths) == 1, pickle_paths
  686. pickle_fp = zf.open(pickle_paths[0], 'r')
  687. unpickler = LazyUnpickler(pickle_fp,
  688. data_base_path=pickle_paths[0][:-4],
  689. zip_file=zf)
  690. model = unpickler.load()
  691. as_dict = dict(model.items())
  692. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  693. SAFETENSORS_DATA_TYPES: Dict[str, DataType] = {
  694. 'BF16': DT_BF16,
  695. 'F16': DT_F16,
  696. 'F32': DT_F32,
  697. 'I32': DT_I32,
  698. }
  699. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  700. header_size, = struct.unpack('<Q', fp.read(8))
  701. header: Dict[str, Dict[str, Any]] = json.loads(fp.read(header_size))
  702. # Use mmap for the actual data to avoid race conditions with the file offset.
  703. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  704. byte_buf = mapped[8 + header_size:]
  705. def convert(info: Dict[str, Any]) -> LazyTensor:
  706. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  707. numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
  708. shape: List[int] = info['shape']
  709. begin, end = info['data_offsets']
  710. assert 0 <= begin <= end <= len(byte_buf)
  711. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  712. buf = byte_buf[begin:end]
  713. def load() -> UnquantizedTensor:
  714. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  715. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  716. return LazyTensor(load, shape, data_type, description)
  717. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  718. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  719. def must_read(fp: IO[bytes], length: int) -> bytes:
  720. ret = fp.read(length)
  721. if len(ret) < length:
  722. raise Exception("unexpectedly reached end of file")
  723. return ret
  724. def lazy_load_ggml_file(fp: io.BufferedReader, path: Path) -> ModelPlus:
  725. magic = must_read(fp, 4)[::-1]
  726. if magic in (b'ggmf', b'ggjt'):
  727. version, = struct.unpack("i", must_read(fp, 4))
  728. assert version == 1
  729. else:
  730. assert magic == b'ggml'
  731. version = None
  732. n_vocab, n_embd, n_mult, n_head, n_layer, rot, file_type = struct.unpack('<7i', must_read(fp, 28))
  733. tokens: List[Tuple[bytes, float]] = []
  734. for i in range(n_vocab):
  735. if i == 32000:
  736. # HACK: GPT4All messed with the format without changing the magic
  737. # number. Specifically, they changed the vocab section to contain
  738. # `n_vocab - 1` tokens instead of `n_vocab` (i.e. omitting the
  739. # extra pad token). Try to detect if we're reading a file like
  740. # this.
  741. orig_pos = fp.tell()
  742. fp.seek(20, io.SEEK_CUR)
  743. is_gpt4all = fp.read(21) == b'tok_embeddings.weight'
  744. fp.seek(orig_pos)
  745. if is_gpt4all:
  746. break
  747. length, = struct.unpack("i", must_read(fp, 4))
  748. text = must_read(fp, length)
  749. if magic != b'ggml':
  750. score, = struct.unpack("f", must_read(fp, 4))
  751. tokens.append((text, score))
  752. vocab = GGMLVocab(tokens) if magic != b'ggml' else None
  753. model: LazyModel = {}
  754. # Use mmap for the actual data to avoid race conditions with the file offset.
  755. off = fp.raw.tell()
  756. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  757. fp.raw.seek(off) # needed on Windows
  758. def read_tensor() -> None: # this is a function so that variables captured in `load` don't change
  759. shape_len, name_len, ftype = struct.unpack("iii", must_read(fp, 12))
  760. assert 0 <= shape_len <= 3
  761. shape: List[int] = list(struct.unpack(f"{shape_len}i", must_read(fp, 4 * shape_len)))
  762. shape = shape[::-1]
  763. name = must_read(fp, name_len).decode('utf-8')
  764. data_type = FTYPE_TO_DATA_TYPE[ftype]
  765. if magic == b'ggjt':
  766. fp.seek((fp.tell() + 31) & -32)
  767. if data_type == DT_Q4_1:
  768. # See GPTQForLLaMaQuantizedTensor.ggml_ndarray()
  769. size = 24 * (shape[1] // 32) * shape[0]
  770. elif data_type == DT_Q4_0:
  771. size = 20 * (shape[1] // 32) * shape[0]
  772. else:
  773. numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
  774. elm_count = math.prod(shape)
  775. size = elm_count * numpy_dtype.itemsize
  776. offset = fp.tell()
  777. buf = mapped[offset:offset+size]
  778. fp.seek(size, io.SEEK_CUR)
  779. def load() -> Tensor:
  780. if isinstance(data_type, QuantizedDataType):
  781. ndarray = np.frombuffer(buf, dtype=np.uint32)
  782. return GGMLQuantizedTensor(ndarray, shape, data_type)
  783. else:
  784. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  785. description = f'ggml offset={offset} type={data_type} path={path}'
  786. model[name] = LazyTensor(load, shape, data_type, description)
  787. while fp.read(1) != b'':
  788. fp.seek(-1, io.SEEK_CUR)
  789. read_tensor()
  790. return ModelPlus(model=model, paths=[path], format='ggml', vocab=vocab)
  791. @functools.lru_cache(maxsize=None)
  792. def lazy_load_file(path: Path) -> ModelPlus:
  793. fp = open(path, 'rb')
  794. first8 = fp.read(8)
  795. fp.seek(0)
  796. if first8[:2] == b'PK':
  797. # A zip file, i.e. PyTorch format
  798. return lazy_load_torch_file(fp, path)
  799. elif first8[2:4] == b'gg':
  800. # GGML format
  801. return lazy_load_ggml_file(fp, path)
  802. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  803. # Probably safetensors
  804. return lazy_load_safetensors_file(fp, path)
  805. else:
  806. raise ValueError(f"unknown format: {path}")
  807. In = TypeVar('In')
  808. Out = TypeVar('Out')
  809. def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int) -> Iterable[Out]:
  810. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  811. fast enough, this will stop calling `func` at some point rather than
  812. letting results pile up in memory. Specifically, there is a max of one
  813. output value buffered per thread.'''
  814. with concurrent.futures.ThreadPoolExecutor() as executor:
  815. futures: List[concurrent.futures.Future[Out]] = []
  816. items_rev = list(iterable)[::-1]
  817. for i in range(min(concurrency, len(items_rev))):
  818. futures.append(executor.submit(func, items_rev.pop()))
  819. while futures:
  820. result = futures.pop(0).result()
  821. if items_rev:
  822. futures.append(executor.submit(func, items_rev.pop()))
  823. yield result
  824. def check_vocab_size(params: Params, vocab: Vocab) -> None:
  825. if params.n_vocab != vocab.vocab_size:
  826. # GGMLVocab comes from the same file as the model so shouldn't mismatch:
  827. assert isinstance(vocab, SentencePieceVocab)
  828. if params.n_vocab == vocab.vocab_size_base:
  829. print("Ignoring added_tokens.json since model matches vocab size without it.")
  830. vocab.added_tokens_list = []
  831. vocab.vocab_size = vocab.vocab_size_base
  832. return
  833. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
  834. if vocab.fname_added_tokens is not None:
  835. msg += f" combined with {vocab.fname_added_tokens}"
  836. msg += f" has {vocab.vocab_size})."
  837. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
  838. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  839. raise Exception(msg)
  840. class OutputFile:
  841. def __init__(self, fname_out: Path) -> None:
  842. self.fout = open(fname_out, "wb")
  843. def write_file_header(self, params: Params, file_type: GGMLFileType) -> None:
  844. self.fout.write(b"ggjt"[::-1]) # magic
  845. values = [
  846. 1, # file version
  847. params.n_vocab,
  848. params.n_embd,
  849. params.n_mult,
  850. params.n_head,
  851. params.n_layer,
  852. params.n_embd // params.n_head, # rot (obsolete)
  853. file_type.value,
  854. ]
  855. self.fout.write(struct.pack("i" * len(values), *values))
  856. def write_tensor_header(self, name: str, shape: Sequence[int], data_type: DataType) -> None:
  857. sname = name.encode('utf-8')
  858. self.fout.write(struct.pack("iii", len(shape), len(sname), DATA_TYPE_TO_FTYPE[data_type]))
  859. self.fout.write(struct.pack("i" * len(shape), *shape[::-1]))
  860. self.fout.write(sname)
  861. self.fout.seek((self.fout.tell() + 31) & -32)
  862. def write_vocab(self, vocab: Vocab) -> None:
  863. for text, score in vocab.all_tokens():
  864. self.fout.write(struct.pack("i", len(text)))
  865. self.fout.write(text)
  866. self.fout.write(struct.pack("f", score))
  867. @staticmethod
  868. def write_vocab_only(fname_out: Path, vocab: Vocab) -> None:
  869. of = OutputFile(fname_out)
  870. params = Params(n_vocab=vocab.vocab_size, n_embd=0, n_mult=0, n_head=1, n_layer=0)
  871. of = OutputFile(fname_out)
  872. of.write_file_header(params, file_type=GGMLFileType.AllF32)
  873. of.write_vocab(vocab)
  874. of.fout.close()
  875. @staticmethod
  876. def write_all(fname_out: Path, params: Params, file_type: GGMLFileType, model: LazyModel, vocab: Vocab) -> None:
  877. check_vocab_size(params, vocab)
  878. of = OutputFile(fname_out)
  879. of.write_file_header(params, file_type)
  880. print("Writing vocab...")
  881. of.write_vocab(vocab)
  882. def do_item(item: Tuple[str, LazyTensor]) -> NDArray:
  883. name, lazy_tensor = item
  884. return lazy_tensor.load().to_ggml().ndarray
  885. ndarrays = bounded_parallel_map(do_item, model.items(), concurrency=8)
  886. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  887. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  888. padi = len(str(len(model)))
  889. print(f"[{i+1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type}")
  890. of.write_tensor_header(name, lazy_tensor.shape, lazy_tensor.data_type)
  891. ndarray.tofile(of.fout)
  892. of.fout.close()
  893. def pick_output_type(model: LazyModel, output_type_str: Optional[str]) -> GGMLFileType:
  894. wq_type = model["layers.0.attention.wq.weight"].data_type
  895. if output_type_str == "f32" or (output_type_str is None and wq_type in (DT_F32, DT_BF16)):
  896. return GGMLFileType.AllF32
  897. if output_type_str == "f16" or (output_type_str is None and wq_type == DT_F16):
  898. return GGMLFileType.MostlyF16
  899. if output_type_str == "q4_1" or (output_type_str is None and isinstance(wq_type, QuantizedDataType) and
  900. wq_type.have_addends):
  901. if isinstance(model["output.weight"].data_type, QuantizedDataType):
  902. return GGMLFileType.MostlyQ4_1
  903. else:
  904. return GGMLFileType.PerLayerIsQ4_1
  905. if output_type_str == "q4_0" or (output_type_str is None and isinstance(wq_type, QuantizedDataType)):
  906. return GGMLFileType.MostlyQ4_0
  907. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  908. raise Exception(f"Unexpected combination of types: {name_to_type}")
  909. def do_necessary_conversions(model: LazyModel, params: Params) -> LazyModel:
  910. model = handle_quantization(model)
  911. if "lm_head.weight" in model:
  912. model = convert_transformers_to_orig(model, params)
  913. model = filter_and_sort_tensors(model)
  914. return model
  915. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  916. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  917. for (name, tensor) in model.items()}
  918. def nth_multifile_path(path: Path, n: int) -> Optional[Path]:
  919. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  920. the nth path in the model.
  921. '''
  922. # Support the following patterns:
  923. patterns: List[Tuple[str, str]] = [
  924. # - x.00.pth, x.01.pth, etc.
  925. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  926. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  927. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  928. # x.bin, x.bin.1, etc.
  929. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  930. ]
  931. for regex, replacement in patterns:
  932. if re.search(regex, path.name):
  933. new_path = path.with_name(re.sub(regex, replacement, path.name))
  934. if new_path.exists():
  935. return new_path
  936. return None
  937. def find_multifile_paths(path: Path) -> List[Path]:
  938. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  939. the whole list of paths in the model.
  940. '''
  941. ret: List[Path] = []
  942. for i in itertools.count():
  943. nth_path = nth_multifile_path(path, i)
  944. if nth_path is None:
  945. break
  946. ret.append(nth_path)
  947. if not ret:
  948. # No matches. This should only happen if the file was named, e.g.,
  949. # foo.0, and there was no file named foo. Oh well, try to process it
  950. # as a single file.
  951. return [path]
  952. return ret
  953. def load_some_model(path: Path) -> ModelPlus:
  954. '''Load a model of any supported format.'''
  955. # Be extra-friendly and accept either a file or a directory:
  956. if path.is_dir():
  957. # Check if it's a set of safetensors files first
  958. files = list(path.glob("model-00001-of-*.safetensors"))
  959. if not files:
  960. # Try the PyTorch patterns too, with lower priority
  961. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  962. files = [file for glob in globs for file in path.glob(glob)]
  963. if not files:
  964. # Try GGML too, but with lower priority, since if both a non-GGML
  965. # model and a GGML model exist in the same directory, we assume the
  966. # latter was converted from the former.
  967. files = list(path.glob("ggml-model*.bin*"))
  968. if not files:
  969. raise Exception(f"Can't find model in directory {path}")
  970. if len(files) > 1:
  971. raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
  972. path = files[0]
  973. paths = find_multifile_paths(path)
  974. models_plus: List[ModelPlus] = []
  975. for path in paths:
  976. print(f"Loading model file {path}")
  977. models_plus.append(lazy_load_file(path))
  978. model_plus = merge_multifile_models(models_plus)
  979. return model_plus
  980. def filter_and_sort_tensors(model: LazyModel) -> LazyModel:
  981. return {name: model[name] for name in TENSORS_LIST if name in model}
  982. def load_vocab(path: Path) -> SentencePieceVocab:
  983. # Be extra-friendly and accept either a file or a directory. Also, if it's
  984. # a directory, it might be the model directory, and tokenizer.model might
  985. # be in the parent of that.
  986. if path.is_dir():
  987. path2 = path / "tokenizer.model"
  988. # Use `.parent` instead of /.. to handle the symlink case better.
  989. path3 = path.parent / "tokenizer.model"
  990. if path2.exists():
  991. path = path2
  992. elif path3.exists():
  993. path = path3
  994. else:
  995. raise FileNotFoundError(
  996. f"Could not find tokenizer.model in {path} or its parent; "
  997. "if it's in another directory, pass the directory as --vocab-dir")
  998. added_tokens_path = path.parent / "added_tokens.json"
  999. print(f"Loading vocab file {path}")
  1000. return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  1001. def default_outfile(model_paths: List[Path], file_type: GGMLFileType) -> Path:
  1002. namestr = {
  1003. GGMLFileType.AllF32: "f32",
  1004. GGMLFileType.MostlyF16: "f16",
  1005. GGMLFileType.MostlyQ4_0: "q4_0",
  1006. GGMLFileType.MostlyQ4_1: "q4_1",
  1007. GGMLFileType.PerLayerIsQ4_1: "q4_1",
  1008. }[file_type]
  1009. ret = model_paths[0].parent / f"ggml-model-{namestr}.bin"
  1010. if ret in model_paths:
  1011. sys.stderr.write(
  1012. f"Error: Default output path ({ret}) would overwrite the input. "
  1013. "Please explicitly specify a path using --outfile.\n")
  1014. sys.exit(1)
  1015. return ret
  1016. def do_dump_model(model_plus: ModelPlus) -> None:
  1017. print(f"model_plus.paths = {model_plus.paths!r}")
  1018. print(f"model_plus.format = {model_plus.format!r}")
  1019. print(f"model_plus.vocab = {model_plus.vocab!r}")
  1020. for name, lazy_tensor in model_plus.model.items():
  1021. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
  1022. def main(args_in: Optional[List[str]] = None) -> None:
  1023. parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
  1024. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  1025. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  1026. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  1027. parser.add_argument("--outtype", choices=["f32", "f16", "q4_1", "q4_0"], help="output format (default: based on input)")
  1028. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  1029. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  1030. parser.add_argument("model", type=Path,
  1031. help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
  1032. args = parser.parse_args(args_in)
  1033. vocab: Vocab
  1034. if args.dump_single:
  1035. model_plus = lazy_load_file(args.model)
  1036. do_dump_model(model_plus)
  1037. elif args.vocab_only:
  1038. vocab = load_vocab(args.vocab_dir or args.model)
  1039. assert args.outfile, "need --outfile if using --vocab-only"
  1040. outfile = args.outfile
  1041. OutputFile.write_vocab_only(outfile, vocab)
  1042. print(f"Wrote {outfile}")
  1043. else:
  1044. model_plus = load_some_model(args.model)
  1045. if args.dump:
  1046. do_dump_model(model_plus)
  1047. return
  1048. if model_plus.vocab is not None and args.vocab_dir is None:
  1049. vocab = model_plus.vocab
  1050. else:
  1051. vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
  1052. vocab = load_vocab(vocab_dir)
  1053. params = Params.load(model_plus)
  1054. model = model_plus.model
  1055. model = do_necessary_conversions(model, params)
  1056. output_type = pick_output_type(model, args.outtype)
  1057. model = convert_to_output_type(model, output_type)
  1058. outfile = args.outfile or default_outfile(model_plus.paths, output_type)
  1059. OutputFile.write_all(outfile, params, output_type, model, vocab)
  1060. print(f"Wrote {outfile}")
  1061. if __name__ == '__main__':
  1062. main()