1
0

convert.py 49 KB

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