convert.py 47 KB

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