convert.py 51 KB

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