convert.py 53 KB

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