convert.py 46 KB

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