convert.py 47 KB

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