convert.py 47 KB

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