convert.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import argparse
  4. import concurrent.futures
  5. import enum
  6. import faulthandler
  7. import functools
  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 time
  18. import zipfile
  19. from abc import ABCMeta, abstractmethod
  20. from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
  21. from dataclasses import dataclass
  22. from pathlib import Path
  23. from typing import IO, TYPE_CHECKING, Any, Callable, Iterable, Literal, TypeVar
  24. import numpy as np
  25. from sentencepiece import SentencePieceProcessor
  26. import os
  27. if 'NO_LOCAL_GGUF' not in os.environ:
  28. sys.path.insert(1, str(Path(__file__).parent / 'gguf-py'))
  29. import gguf
  30. if TYPE_CHECKING:
  31. from typing import TypeAlias
  32. if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
  33. faulthandler.register(signal.SIGUSR1)
  34. NDArray: TypeAlias = 'np.ndarray[Any, Any]'
  35. ARCH = gguf.MODEL_ARCH.LLAMA
  36. DEFAULT_CONCURRENCY = 8
  37. #
  38. # data types
  39. #
  40. @dataclass(frozen=True)
  41. class DataType:
  42. name: str
  43. dtype: np.dtype[Any]
  44. valid_conversions: list[str]
  45. def elements_to_bytes(self, n_elements: int) -> int:
  46. return n_elements * self.dtype.itemsize
  47. @dataclass(frozen=True)
  48. class UnquantizedDataType(DataType):
  49. pass
  50. DT_F16 = UnquantizedDataType('F16', dtype = np.dtype(np.float16), valid_conversions = ['F32', 'Q8_0'])
  51. DT_F32 = UnquantizedDataType('F32', dtype = np.dtype(np.float32), valid_conversions = ['F16', 'Q8_0'])
  52. DT_I32 = UnquantizedDataType('I32', dtype = np.dtype(np.int16), valid_conversions = [])
  53. DT_BF16 = UnquantizedDataType('BF16', dtype = np.dtype(np.uint16), valid_conversions = ['F32', 'F16', 'Q8_0'])
  54. @dataclass(frozen=True)
  55. class QuantizedDataType(DataType):
  56. block_size: int
  57. quantized_dtype: np.dtype[Any]
  58. ggml_type: gguf.GGMLQuantizationType
  59. def quantize(self, arr: NDArray) -> NDArray:
  60. raise NotImplementedError(f'Quantization for {self.name} not implemented')
  61. def elements_to_bytes(self, n_elements: int) -> int:
  62. assert n_elements % self.block_size == 0, f'Invalid number of elements {n_elements} for {self.name} with block size {self.block_size}'
  63. return self.quantized_dtype.itemsize * (n_elements // self.block_size)
  64. @dataclass(frozen=True)
  65. class Q8_0QuantizedDataType(QuantizedDataType):
  66. # Mini Q8_0 quantization in Python!
  67. def quantize(self, arr: NDArray) -> NDArray:
  68. assert arr.size % self.block_size == 0 and arr.size != 0, f'Bad array size {arr.size}'
  69. assert arr.dtype == np.float32, f'Bad array type {arr.dtype}'
  70. n_blocks = arr.size // self.block_size
  71. blocks = arr.reshape((n_blocks, self.block_size))
  72. # Much faster implementation of block quantization contributed by @Cebtenzzre
  73. def quantize_blocks_q8_0(blocks: NDArray) -> Iterable[tuple[Any, Any]]:
  74. d = abs(blocks).max(axis = 1) / np.float32(127)
  75. with np.errstate(divide = 'ignore'):
  76. qs = (blocks / d[:, None]).round()
  77. qs[d == 0] = 0
  78. yield from zip(d, qs)
  79. return np.fromiter(quantize_blocks_q8_0(blocks), count = n_blocks, dtype = self.quantized_dtype)
  80. DT_Q8_0 = Q8_0QuantizedDataType('Q8_0',
  81. dtype = np.dtype(np.float32), valid_conversions = [],
  82. ggml_type = gguf.GGMLQuantizationType.Q8_0, block_size = 32,
  83. quantized_dtype = np.dtype([('d', '<f2'), ('qs', 'i1', (32,))]))
  84. # Quantized types skipped here because they may also map to np.float32
  85. NUMPY_TYPE_TO_DATA_TYPE: dict[np.dtype[Any], DataType] = {}
  86. for dt in (DT_BF16, DT_F16, DT_F32, DT_I32):
  87. if dt.dtype in NUMPY_TYPE_TO_DATA_TYPE:
  88. raise ValueError(f'Invalid duplicate data type {dt}')
  89. NUMPY_TYPE_TO_DATA_TYPE[dt.dtype] = dt
  90. SAFETENSORS_DATA_TYPES: dict[str, DataType] = {
  91. 'BF16': DT_BF16,
  92. 'F16': DT_F16,
  93. 'F32': DT_F32,
  94. 'I32': DT_I32,
  95. }
  96. # TODO: match this with `llama_ftype`
  97. # TODO: rename to LLAMAFileType
  98. # TODO: move to `gguf.py`
  99. class GGMLFileType(enum.IntEnum):
  100. AllF32 = 0
  101. MostlyF16 = 1 # except 1d tensors
  102. MostlyQ8_0 = 7 # except 1d tensors
  103. def type_for_tensor(self, name: str, tensor: LazyTensor) -> DataType:
  104. dt = GGML_FILE_TYPE_TO_DATA_TYPE.get(self)
  105. if dt is None:
  106. raise ValueError(self)
  107. # 1D tensors are always F32.
  108. return dt if len(tensor.shape) > 1 else DT_F32
  109. GGML_FILE_TYPE_TO_DATA_TYPE: dict[GGMLFileType, DataType] = {
  110. GGMLFileType.AllF32 : DT_F32,
  111. GGMLFileType.MostlyF16 : DT_F16,
  112. GGMLFileType.MostlyQ8_0: DT_Q8_0,
  113. }
  114. #
  115. # hparams loading
  116. #
  117. @dataclass
  118. class Params:
  119. n_vocab: int
  120. n_embd: int
  121. n_layer: int
  122. n_ctx: int
  123. n_ff: int
  124. n_head: int
  125. n_head_kv: int
  126. n_experts: int | None = None
  127. n_experts_used: int | None = None
  128. f_norm_eps: float | None = None
  129. rope_scaling_type: gguf.RopeScalingType | None = None
  130. f_rope_freq_base: float | None = None
  131. f_rope_scale: float | None = None
  132. n_orig_ctx: int | None = None
  133. rope_finetuned: bool | None = None
  134. ftype: GGMLFileType | None = None
  135. # path to the directory containing the model files
  136. path_model: Path | None = None
  137. @staticmethod
  138. def guessed(model: LazyModel) -> Params:
  139. # try transformer naming first
  140. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  141. # try transformer naming first
  142. if "model.layers.0.self_attn.q_proj.weight" in model:
  143. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  144. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  145. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  146. else:
  147. n_layer = next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  148. if n_layer < 1:
  149. raise Exception("failed to guess 'n_layer'. This model is unknown or unsupported.\n"
  150. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  151. n_head = n_embd // 128 # guessed
  152. n_mult = 256 # guessed
  153. # TODO: verify this
  154. n_ff = int(2 * (4 * n_embd) / 3)
  155. n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
  156. return Params(
  157. n_vocab = n_vocab,
  158. n_embd = n_embd,
  159. n_layer = n_layer,
  160. n_ctx = -1,
  161. n_ff = n_ff,
  162. n_head = n_head,
  163. n_head_kv = n_head,
  164. f_norm_eps = 1e-5,
  165. )
  166. @staticmethod
  167. def loadHFTransformerJson(model: LazyModel, config_path: Path) -> Params:
  168. config = json.load(open(config_path))
  169. rope_scaling_type = f_rope_scale = n_orig_ctx = rope_finetuned = None
  170. rope_scaling = config.get("rope_scaling")
  171. if rope_scaling is not None and (typ := rope_scaling.get("type")):
  172. rope_factor = rope_scaling.get("factor")
  173. f_rope_scale = rope_factor
  174. if typ == "linear":
  175. rope_scaling_type = gguf.RopeScalingType.LINEAR
  176. elif typ == "yarn":
  177. rope_scaling_type = gguf.RopeScalingType.YARN
  178. n_orig_ctx = rope_scaling['original_max_position_embeddings']
  179. rope_finetuned = rope_scaling['finetuned']
  180. else:
  181. raise NotImplementedError(f'Unknown rope scaling type: {typ}')
  182. if "max_sequence_length" in config:
  183. n_ctx = config["max_sequence_length"]
  184. elif "max_position_embeddings" in config:
  185. n_ctx = config["max_position_embeddings"]
  186. else:
  187. raise Exception("failed to guess 'n_ctx'. This model is unknown or unsupported.\n"
  188. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  189. n_experts = None
  190. n_experts_used = None
  191. if "num_local_experts" in config:
  192. n_experts = config["num_local_experts"]
  193. n_experts_used = config["num_experts_per_tok"]
  194. return Params(
  195. n_vocab = config["vocab_size"],
  196. n_embd = config["hidden_size"],
  197. n_layer = config["num_hidden_layers"],
  198. n_ctx = n_ctx,
  199. n_ff = config["intermediate_size"],
  200. n_head = (n_head := config["num_attention_heads"]),
  201. n_head_kv = config.get("num_key_value_heads", n_head),
  202. n_experts = n_experts,
  203. n_experts_used = n_experts_used,
  204. f_norm_eps = config["rms_norm_eps"],
  205. f_rope_freq_base = config.get("rope_theta"),
  206. rope_scaling_type = rope_scaling_type,
  207. f_rope_scale = f_rope_scale,
  208. n_orig_ctx = n_orig_ctx,
  209. rope_finetuned = rope_finetuned,
  210. )
  211. # LLaMA v2 70B params.json
  212. # {"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}
  213. @staticmethod
  214. def loadOriginalParamsJson(model: LazyModel, config_path: Path) -> Params:
  215. config = json.load(open(config_path))
  216. n_experts = None
  217. n_experts_used = None
  218. f_rope_freq_base = None
  219. # hack to determine LLaMA v1 vs v2 vs CodeLlama
  220. if config.get("moe"):
  221. # Mixtral
  222. n_ctx = 32768
  223. elif config.get("rope_theta") == 1000000:
  224. # CodeLlama
  225. n_ctx = 16384
  226. elif config["norm_eps"] == 1e-05:
  227. # LLaMA v2
  228. n_ctx = 4096
  229. else:
  230. # LLaMA v1
  231. n_ctx = 2048
  232. if "layers.0.feed_forward.w1.weight" in model:
  233. n_ff = model["layers.0.feed_forward.w1.weight"].shape[0]
  234. if config.get("moe"):
  235. n_ff = model["layers.0.feed_forward.experts.0.w1.weight"].shape[0]
  236. n_experts = config["moe"]["num_experts"]
  237. n_experts_used = config["moe"]["num_experts_per_tok"]
  238. f_rope_freq_base = 1e6
  239. return Params(
  240. n_vocab = model["tok_embeddings.weight"].shape[0],
  241. n_embd = config["dim"],
  242. n_layer = config["n_layers"],
  243. n_ctx = n_ctx,
  244. n_ff = n_ff,
  245. n_head = (n_head := config["n_heads"]),
  246. n_head_kv = config.get("n_kv_heads", n_head),
  247. n_experts = n_experts,
  248. n_experts_used = n_experts_used,
  249. f_norm_eps = config["norm_eps"],
  250. f_rope_freq_base = config.get("rope_theta", f_rope_freq_base),
  251. )
  252. @staticmethod
  253. def load(model_plus: ModelPlus) -> Params:
  254. hf_config_path = model_plus.paths[0].parent / "config.json"
  255. orig_config_path = model_plus.paths[0].parent / "params.json"
  256. if hf_config_path.exists():
  257. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  258. elif orig_config_path.exists():
  259. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  260. elif model_plus.format != 'none':
  261. params = Params.guessed(model_plus.model)
  262. else:
  263. raise ValueError('Cannot guess params when model format is none')
  264. params.path_model = model_plus.paths[0].parent
  265. return params
  266. #
  267. # vocab
  268. #
  269. class BpeVocab:
  270. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
  271. self.bpe_tokenizer = json.loads(open(str(fname_tokenizer), encoding="utf-8").read())
  272. added_tokens: dict[str, int]
  273. if fname_added_tokens is not None:
  274. # FIXME: Verify that added tokens here _cannot_ overlap with the main vocab.
  275. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  276. else:
  277. # Fall back to trying to find the added tokens in tokenizer.json
  278. tokenizer_json_file = fname_tokenizer.parent / 'tokenizer.json'
  279. if not tokenizer_json_file.is_file():
  280. added_tokens = {}
  281. else:
  282. tokenizer_json = json.load(open(tokenizer_json_file, encoding="utf-8"))
  283. added_tokens = dict(
  284. (item['content'], item['id'])
  285. for item in tokenizer_json.get('added_tokens', [])
  286. # Added tokens here can be duplicates of the main vocabulary.
  287. if item['content'] not in self.bpe_tokenizer)
  288. vocab_size: int = len(self.bpe_tokenizer)
  289. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  290. actual_ids = sorted(added_tokens.values())
  291. if expected_ids != actual_ids:
  292. expected_end_id = vocab_size + len(actual_ids) - 1
  293. raise Exception(f"Expected the {len(actual_ids)} added token ID(s) to be sequential in the range {vocab_size} - {expected_end_id}; got {actual_ids}")
  294. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  295. self.added_tokens_list = [text for (text, idx) in items]
  296. self.vocab_size_base: int = vocab_size
  297. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  298. self.fname_tokenizer = fname_tokenizer
  299. self.fname_added_tokens = fname_added_tokens
  300. def bpe_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  301. tokenizer = self.bpe_tokenizer
  302. reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.items()}
  303. for i, _ in enumerate(tokenizer):
  304. yield reverse_vocab[i], 0.0, gguf.TokenType.NORMAL
  305. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  306. for text in self.added_tokens_list:
  307. score = -1000.0
  308. yield text.encode("utf-8"), score, gguf.TokenType.CONTROL
  309. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  310. yield from self.bpe_tokens()
  311. yield from self.added_tokens()
  312. def __repr__(self) -> str:
  313. return f"<BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  314. class SentencePieceVocab:
  315. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
  316. self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
  317. added_tokens: dict[str, int]
  318. if fname_added_tokens is not None:
  319. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  320. else:
  321. added_tokens = {}
  322. vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
  323. new_tokens = {id: piece for piece, id in added_tokens.items() if id >= vocab_size}
  324. expected_new_ids = list(range(vocab_size, vocab_size + len(new_tokens)))
  325. actual_new_ids = sorted(new_tokens.keys())
  326. if expected_new_ids != actual_new_ids:
  327. raise ValueError(f"Expected new token IDs {expected_new_ids} to be sequential; got {actual_new_ids}")
  328. # Token pieces that were added to the base vocabulary.
  329. self.added_tokens_list = [new_tokens[id] for id in actual_new_ids]
  330. self.vocab_size_base = vocab_size
  331. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  332. self.fname_tokenizer = fname_tokenizer
  333. self.fname_added_tokens = fname_added_tokens
  334. def sentencepiece_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  335. tokenizer = self.sentencepiece_tokenizer
  336. for i in range(tokenizer.vocab_size()):
  337. piece = tokenizer.id_to_piece(i)
  338. text: bytes = piece.encode("utf-8")
  339. score: float = tokenizer.get_score(i)
  340. toktype = gguf.TokenType.NORMAL
  341. if tokenizer.is_unknown(i):
  342. toktype = gguf.TokenType.UNKNOWN
  343. if tokenizer.is_control(i):
  344. toktype = gguf.TokenType.CONTROL
  345. # NOTE: I think added_tokens are user defined.
  346. # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
  347. # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
  348. if tokenizer.is_unused(i):
  349. toktype = gguf.TokenType.UNUSED
  350. if tokenizer.is_byte(i):
  351. toktype = gguf.TokenType.BYTE
  352. yield text, score, toktype
  353. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  354. for text in self.added_tokens_list:
  355. score = -1000.0
  356. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  357. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  358. yield from self.sentencepiece_tokens()
  359. yield from self.added_tokens()
  360. def __repr__(self) -> str:
  361. return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  362. Vocab: TypeAlias = 'BpeVocab | SentencePieceVocab'
  363. #
  364. # data loading
  365. # TODO: reuse (probably move to gguf.py?)
  366. #
  367. def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
  368. # print( "permute debug " + str(weights.shape[0]) + " x " + str(weights.shape[1]) + " nhead " + str(n_head) + " nheadkv " + str(n_kv_head) )
  369. if n_head_kv is not None and n_head != n_head_kv:
  370. n_head = n_head_kv
  371. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  372. .swapaxes(1, 2)
  373. .reshape(weights.shape))
  374. class Tensor(metaclass=ABCMeta):
  375. data_type: DataType
  376. @abstractmethod
  377. def astype(self, data_type: DataType) -> Tensor: ...
  378. @abstractmethod
  379. def permute(self, n_head: int, n_head_kv: int) -> Tensor: ...
  380. @abstractmethod
  381. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor: ...
  382. @abstractmethod
  383. def part(self, n_part: int) -> UnquantizedTensor: ...
  384. @abstractmethod
  385. def to_ggml(self) -> GGMLCompatibleTensor: ...
  386. def bf16_to_fp32(bf16_arr: np.ndarray[Any, np.dtype[np.uint16]]) -> NDArray:
  387. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  388. fp32_arr = bf16_arr.astype(np.uint32) << 16
  389. return fp32_arr.view(np.float32)
  390. class UnquantizedTensor(Tensor):
  391. def __init__(self, ndarray: NDArray) -> None:
  392. assert isinstance(ndarray, np.ndarray)
  393. self.ndarray = ndarray
  394. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  395. def astype(self, data_type: DataType) -> Tensor:
  396. dtype = data_type.dtype
  397. if self.data_type == DT_BF16:
  398. self.ndarray = bf16_to_fp32(self.ndarray)
  399. return UnquantizedTensor(self.ndarray.astype(dtype))
  400. def to_ggml(self) -> UnquantizedTensor:
  401. return self
  402. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  403. r = self.ndarray.shape[0] // 3
  404. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head, n_head_kv))
  405. def part(self, n_part: int) -> UnquantizedTensor:
  406. r = self.ndarray.shape[0] // 3
  407. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  408. def permute(self, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  409. return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
  410. def load_unquantized(lazy_tensor: LazyTensor, expected_dtype: Any = None, convert: bool = False) -> NDArray:
  411. tensor = lazy_tensor.load()
  412. assert isinstance(tensor, UnquantizedTensor)
  413. # double-check:
  414. actual_shape = list(tensor.ndarray.shape)
  415. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  416. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  417. if convert:
  418. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  419. else:
  420. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  421. return tensor.ndarray
  422. GGMLCompatibleTensor = UnquantizedTensor
  423. @dataclass
  424. class LazyTensor:
  425. _load: Callable[[], Tensor]
  426. shape: list[int]
  427. data_type: DataType
  428. description: str
  429. def load(self) -> Tensor:
  430. ret = self._load()
  431. # Should be okay if it maps to the same numpy type?
  432. assert ret.data_type == self.data_type or (self.data_type.dtype == ret.data_type.dtype), \
  433. (self.data_type, ret.data_type, self.description)
  434. return ret
  435. def astype(self, data_type: DataType) -> LazyTensor:
  436. self.validate_conversion_to(data_type)
  437. def load() -> Tensor:
  438. return self.load().astype(data_type)
  439. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  440. def validate_conversion_to(self, data_type: DataType) -> None:
  441. if data_type != self.data_type and data_type.name not in self.data_type.valid_conversions:
  442. raise ValueError(f'Cannot validate conversion from {self.data_type} to {data_type}.')
  443. LazyModel: TypeAlias = 'dict[str, LazyTensor]'
  444. @dataclass
  445. class ModelPlus:
  446. model: LazyModel
  447. paths: list[Path] # Where this was read from.
  448. format: Literal['ggml', 'torch', 'safetensors', 'none']
  449. vocab: Vocab | None # For GGML models (which have vocab built in), the vocab.
  450. def merge_sharded(models: list[LazyModel]) -> LazyModel:
  451. # Original LLaMA models have each file contain one part of each tensor.
  452. # Use a dict instead of a set to preserve order.
  453. names = {name: None for model in models for name in model}
  454. def convert(name: str) -> LazyTensor:
  455. lazy_tensors: list[LazyTensor] = [model[name] for model in models]
  456. if len(lazy_tensors) == 1:
  457. # only one file; don't go through this procedure since there might
  458. # be quantized tensors
  459. return lazy_tensors[0]
  460. if len(lazy_tensors[0].shape) == 1:
  461. # the tensor is just duplicated in every file
  462. return lazy_tensors[0]
  463. if name.startswith('tok_embeddings.') or \
  464. name.endswith('.attention.wo.weight') or \
  465. name.endswith('.feed_forward.w2.weight'):
  466. # split by columns
  467. axis = 1
  468. else:
  469. # split by rows
  470. axis = 0
  471. concatenated_shape = list(lazy_tensors[0].shape)
  472. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  473. def load() -> UnquantizedTensor:
  474. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  475. concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
  476. return UnquantizedTensor(concatenated)
  477. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  478. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  479. return {name: convert(name) for name in names}
  480. def merge_multifile_models(models_plus: list[ModelPlus]) -> ModelPlus:
  481. formats = set(mp.format for mp in models_plus)
  482. assert len(formats) == 1, "different formats?"
  483. format = formats.pop()
  484. paths = [path for mp in models_plus for path in mp.paths]
  485. # Use the first non-None vocab, if any.
  486. try:
  487. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  488. except StopIteration:
  489. vocab = None
  490. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  491. # Transformers models put different tensors in different files, but
  492. # don't split individual tensors between files.
  493. model: LazyModel = {}
  494. for mp in models_plus:
  495. model.update(mp.model)
  496. else:
  497. model = merge_sharded([mp.model for mp in models_plus])
  498. return ModelPlus(model, paths, format, vocab)
  499. def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
  500. def load() -> Tensor:
  501. return lazy_tensor.load().permute(n_head, n_head_kv)
  502. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  503. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int, n_head_kv: int) -> LazyTensor:
  504. def load() -> Tensor:
  505. return lazy_tensor.load().permute_part(n_part, n_head, n_head_kv)
  506. s = lazy_tensor.shape.copy()
  507. s[0] = s[0] // 3
  508. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  509. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  510. def load() -> Tensor:
  511. return lazy_tensor.load().part(n_part)
  512. s = lazy_tensor.shape.copy()
  513. s[0] = s[0] // 3
  514. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  515. # Functionality that simulates `torch.load` but where individual tensors are
  516. # only loaded into memory on demand, not all at once.
  517. # PyTorch can't do this natively as of time of writing:
  518. # - https://github.com/pytorch/pytorch/issues/64327
  519. # This allows us to de-shard without multiplying RAM usage, and also
  520. # conveniently drops the PyTorch dependency (though we still need numpy).
  521. @dataclass
  522. class LazyStorageKind:
  523. data_type: DataType
  524. @dataclass
  525. class LazyStorage:
  526. load: Callable[[int, int], NDArray]
  527. kind: LazyStorageKind
  528. description: str
  529. class LazyUnpickler(pickle.Unpickler):
  530. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  531. super().__init__(fp)
  532. self.data_base_path = data_base_path
  533. self.zip_file = zip_file
  534. def persistent_load(self, pid: Any) -> Any:
  535. assert pid[0] == 'storage'
  536. assert isinstance(pid[1], LazyStorageKind)
  537. data_type = pid[1].data_type
  538. filename_stem = pid[2]
  539. filename = f'{self.data_base_path}/{filename_stem}'
  540. info = self.zip_file.getinfo(filename)
  541. def load(offset: int, elm_count: int) -> NDArray:
  542. dtype = data_type.dtype
  543. fp = self.zip_file.open(info)
  544. fp.seek(offset * dtype.itemsize)
  545. size = elm_count * dtype.itemsize
  546. data = fp.read(size)
  547. assert len(data) == size
  548. return np.frombuffer(data, dtype)
  549. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  550. return LazyStorage(load=load, kind=pid[1], description=description)
  551. @staticmethod
  552. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  553. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  554. assert isinstance(storage, LazyStorage)
  555. def load() -> UnquantizedTensor:
  556. elm_count = stride[0] * size[0]
  557. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  558. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  559. return LazyTensor(load, list(size), storage.kind.data_type, description)
  560. @staticmethod
  561. def rebuild_from_type_v2(func, new_type, args, state):
  562. return func(*args)
  563. CLASSES: dict[tuple[str, str], Any] = {
  564. # getattr used here as a workaround for mypy not being smart enough to determine
  565. # the staticmethods have a __func__ attribute.
  566. ('torch._tensor', '_rebuild_from_type_v2'): getattr(rebuild_from_type_v2, '__func__'),
  567. ('torch._utils', '_rebuild_tensor_v2'): getattr(lazy_rebuild_tensor_v2, '__func__'),
  568. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  569. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  570. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  571. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  572. ('torch', 'Tensor'): LazyTensor,
  573. }
  574. def find_class(self, module: str, name: str) -> Any:
  575. if not module.startswith('torch'):
  576. return super().find_class(module, name)
  577. return self.CLASSES[(module, name)]
  578. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  579. zf = zipfile.ZipFile(outer_fp)
  580. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  581. assert len(pickle_paths) == 1, pickle_paths
  582. pickle_fp = zf.open(pickle_paths[0], 'r')
  583. unpickler = LazyUnpickler(pickle_fp,
  584. data_base_path=pickle_paths[0][:-4],
  585. zip_file=zf)
  586. model = unpickler.load()
  587. if 'model' in model: model = model['model']
  588. as_dict = dict(model.items())
  589. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  590. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  591. header_size, = struct.unpack('<Q', fp.read(8))
  592. header: dict[str, dict[str, Any]] = json.loads(fp.read(header_size))
  593. # Use mmap for the actual data to avoid race conditions with the file offset.
  594. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  595. byte_buf = mapped[8 + header_size:]
  596. def convert(info: dict[str, Any]) -> LazyTensor:
  597. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  598. numpy_dtype = data_type.dtype
  599. shape: list[int] = info['shape']
  600. begin, end = info['data_offsets']
  601. assert 0 <= begin <= end <= len(byte_buf)
  602. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  603. buf = byte_buf[begin:end]
  604. def load() -> UnquantizedTensor:
  605. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  606. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  607. return LazyTensor(load, shape, data_type, description)
  608. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  609. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  610. def must_read(fp: IO[bytes], length: int) -> bytes:
  611. ret = fp.read(length)
  612. if len(ret) < length:
  613. raise Exception("unexpectedly reached end of file")
  614. return ret
  615. @functools.lru_cache(maxsize=None)
  616. def lazy_load_file(path: Path) -> ModelPlus:
  617. fp = open(path, 'rb')
  618. first8 = fp.read(8)
  619. fp.seek(0)
  620. if first8[:2] == b'PK':
  621. # A zip file, i.e. PyTorch format
  622. return lazy_load_torch_file(fp, path)
  623. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  624. # Probably safetensors
  625. return lazy_load_safetensors_file(fp, path)
  626. else:
  627. raise ValueError(f"unknown format: {path}")
  628. In = TypeVar('In')
  629. Out = TypeVar('Out')
  630. def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False) -> Iterable[Out]:
  631. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  632. fast enough, this will stop calling `func` at some point rather than
  633. letting results pile up in memory. Specifically, there is a max of one
  634. output value buffered per thread.'''
  635. if concurrency < 2:
  636. yield from map(func, iterable)
  637. # Not reached.
  638. iterable = iter(iterable)
  639. executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor]
  640. if use_processpool_executor:
  641. executor_class = ProcessPoolExecutor
  642. else:
  643. executor_class = ThreadPoolExecutor
  644. with executor_class(max_workers = max_workers) as executor:
  645. futures: list[concurrent.futures.Future[Out]] = []
  646. done = False
  647. for _ in range(concurrency):
  648. try:
  649. futures.append(executor.submit(func, next(iterable)))
  650. except StopIteration:
  651. done = True
  652. break
  653. while futures:
  654. result = futures.pop(0).result()
  655. while not done and len(futures) < concurrency:
  656. try:
  657. futures.append(executor.submit(func, next(iterable)))
  658. except StopIteration:
  659. done = True
  660. break
  661. yield result
  662. def check_vocab_size(params: Params, vocab: Vocab) -> None:
  663. if params.n_vocab != vocab.vocab_size:
  664. assert isinstance(vocab, BpeVocab) or isinstance(vocab, SentencePieceVocab)
  665. if params.n_vocab == vocab.vocab_size_base:
  666. print("Ignoring added_tokens.json since model matches vocab size without it.")
  667. vocab.added_tokens_list = []
  668. vocab.vocab_size = vocab.vocab_size_base
  669. return
  670. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
  671. if vocab.fname_added_tokens is not None:
  672. msg += f" combined with {vocab.fname_added_tokens}"
  673. msg += f" has {vocab.vocab_size})."
  674. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
  675. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  676. raise Exception(msg)
  677. class OutputFile:
  678. def __init__(self, fname_out: Path, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE) -> None:
  679. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH], endianess=endianess)
  680. def add_meta_arch(self, params: Params) -> None:
  681. name = "LLaMA"
  682. # TODO: better logic to determine model name
  683. if params.n_ctx == 4096:
  684. name = "LLaMA v2"
  685. elif params.path_model is not None:
  686. name = str(params.path_model.parent).split('/')[-1]
  687. self.gguf.add_name (name)
  688. self.gguf.add_context_length (params.n_ctx)
  689. self.gguf.add_embedding_length (params.n_embd)
  690. self.gguf.add_block_count (params.n_layer)
  691. self.gguf.add_feed_forward_length (params.n_ff)
  692. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  693. self.gguf.add_head_count (params.n_head)
  694. self.gguf.add_head_count_kv (params.n_head_kv)
  695. if params.n_experts:
  696. self.gguf.add_expert_count(params.n_experts)
  697. if params.n_experts_used:
  698. self.gguf.add_expert_used_count(params.n_experts_used)
  699. if params.f_norm_eps:
  700. self.gguf.add_layer_norm_rms_eps(params.f_norm_eps)
  701. else:
  702. raise ValueError('f_norm_eps is None')
  703. if params.f_rope_freq_base is not None:
  704. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  705. if params.rope_scaling_type:
  706. assert params.f_rope_scale is not None
  707. self.gguf.add_rope_scaling_type(params.rope_scaling_type)
  708. self.gguf.add_rope_scaling_factor(params.f_rope_scale)
  709. if params.n_orig_ctx is not None:
  710. self.gguf.add_rope_scaling_orig_ctx_len(params.n_orig_ctx)
  711. if params.rope_finetuned is not None:
  712. self.gguf.add_rope_scaling_finetuned(params.rope_finetuned)
  713. if params.ftype is not None:
  714. self.gguf.add_file_type(params.ftype)
  715. def add_meta_vocab(self, vocab: Vocab) -> None:
  716. tokens = []
  717. scores = []
  718. toktypes = []
  719. # NOTE: `all_tokens` returns the base vocabulary and added tokens
  720. for text, score, toktype in vocab.all_tokens():
  721. tokens.append(text)
  722. scores.append(score)
  723. toktypes.append(toktype)
  724. if isinstance(vocab, SentencePieceVocab):
  725. self.gguf.add_tokenizer_model("llama")
  726. elif isinstance(vocab, BpeVocab):
  727. self.gguf.add_tokenizer_model("gpt2")
  728. else:
  729. raise ValueError('Unknown vocab type: Not BpeVocab or SentencePieceVocab')
  730. self.gguf.add_token_list(tokens)
  731. self.gguf.add_token_scores(scores)
  732. self.gguf.add_token_types(toktypes)
  733. def add_meta_special_vocab(self, svocab: gguf.SpecialVocab) -> None:
  734. svocab.add_to_gguf(self.gguf)
  735. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  736. n_elements = int(np.prod(tensor.shape))
  737. raw_dtype = getattr(tensor.data_type, 'ggml_type', None)
  738. data_type = getattr(tensor.data_type, 'quantized_type', None) or tensor.data_type.dtype
  739. data_nbytes = tensor.data_type.elements_to_bytes(n_elements)
  740. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes, raw_dtype = raw_dtype)
  741. def write_meta(self) -> None:
  742. self.gguf.write_header_to_file()
  743. self.gguf.write_kv_data_to_file()
  744. def write_tensor_info(self) -> None:
  745. self.gguf.write_ti_data_to_file()
  746. def close(self) -> None:
  747. self.gguf.close()
  748. @staticmethod
  749. def write_vocab_only(fname_out: Path, params: Params, vocab: Vocab, svocab: gguf.SpecialVocab, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE) -> None:
  750. check_vocab_size(params, vocab)
  751. of = OutputFile(fname_out, endianess=endianess)
  752. # meta data
  753. of.add_meta_arch(params)
  754. of.add_meta_vocab(vocab)
  755. of.add_meta_special_vocab(svocab)
  756. of.write_meta()
  757. of.close()
  758. @staticmethod
  759. def do_item(item: tuple[str, LazyTensor]) -> tuple[DataType, NDArray]:
  760. name, lazy_tensor = item
  761. tensor = lazy_tensor.load().to_ggml()
  762. return (lazy_tensor.data_type, tensor.ndarray)
  763. @staticmethod
  764. def maybe_do_quantize(item: tuple[DataType, NDArray]) -> NDArray:
  765. dt, arr = item
  766. if not isinstance(dt, QuantizedDataType):
  767. return arr
  768. return dt.quantize(arr)
  769. @staticmethod
  770. def write_all(fname_out: Path, ftype: GGMLFileType, params: Params, model: LazyModel, vocab: Vocab, svocab: gguf.SpecialVocab, concurrency: int = DEFAULT_CONCURRENCY, endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE) -> None:
  771. check_vocab_size(params, vocab)
  772. of = OutputFile(fname_out, endianess=endianess)
  773. # meta data
  774. of.add_meta_arch(params)
  775. of.add_meta_vocab(vocab)
  776. of.add_meta_special_vocab(svocab)
  777. # tensor info
  778. for name, lazy_tensor in model.items():
  779. of.add_tensor_info(name, lazy_tensor)
  780. of.write_meta()
  781. of.write_tensor_info()
  782. # tensor data
  783. ndarrays_inner = bounded_parallel_map(OutputFile.do_item, model.items(), concurrency = concurrency)
  784. if ftype == GGMLFileType.MostlyQ8_0:
  785. ndarrays = bounded_parallel_map(OutputFile.maybe_do_quantize, ndarrays_inner, concurrency = concurrency, max_workers = concurrency, use_processpool_executor = True)
  786. else:
  787. ndarrays = map(OutputFile.maybe_do_quantize, ndarrays_inner)
  788. start = time.time()
  789. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  790. elapsed = time.time() - start
  791. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  792. padi = len(str(len(model)))
  793. print(f"[{i+1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type.name:4} | T+{int(elapsed):4}")
  794. of.gguf.write_tensor_data(ndarray)
  795. of.close()
  796. def pick_output_type(model: LazyModel, output_type_str: str | None) -> GGMLFileType:
  797. wq_type = model[gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0) + ".weight"].data_type
  798. if output_type_str == "f32" or (output_type_str is None and wq_type == DT_F32):
  799. return GGMLFileType.AllF32
  800. if output_type_str == "f16" or (output_type_str is None and wq_type in (DT_F16, DT_BF16)):
  801. return GGMLFileType.MostlyF16
  802. if output_type_str == "q8_0":
  803. return GGMLFileType.MostlyQ8_0
  804. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  805. raise Exception(f"Unexpected combination of types: {name_to_type}")
  806. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  807. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  808. for (name, tensor) in model.items()}
  809. def convert_model_names(model: LazyModel, params: Params) -> LazyModel:
  810. tmap = gguf.TensorNameMap(ARCH, params.n_layer)
  811. should_skip: set[gguf.MODEL_TENSOR] = set(gguf.MODEL_TENSOR_SKIP.get(ARCH, []))
  812. tmp = model
  813. # HF models permut or pack some of the tensors, so we need to undo that
  814. for i in itertools.count():
  815. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  816. print(f"Permuting layer {i}")
  817. tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.q_proj.weight"], params.n_head, params.n_head)
  818. tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.k_proj.weight"], params.n_head, params.n_head_kv)
  819. # tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  820. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  821. print(f"Unpacking and permuting layer {i}")
  822. tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 0, params.n_head, params.n_head)
  823. tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 1, params.n_head, params.n_head_kv)
  824. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  825. del tmp[f"model.layers.{i}.self_attn.W_pack.weight"]
  826. else:
  827. break
  828. out: LazyModel = {}
  829. for name, lazy_tensor in model.items():
  830. tensor_type, name_new = tmap.get_type_and_name(name, try_suffixes = (".weight", ".bias")) or (None, None)
  831. if name_new is None:
  832. raise Exception(f"Unexpected tensor name: {name}")
  833. if tensor_type in should_skip:
  834. print(f"skipping tensor {name_new}")
  835. continue
  836. print(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type.name:6s} | {lazy_tensor.shape}")
  837. out[name_new] = lazy_tensor
  838. return out
  839. def nth_multifile_path(path: Path, n: int) -> Path | None:
  840. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  841. the nth path in the model.
  842. '''
  843. # Support the following patterns:
  844. patterns: list[tuple[str, str]] = [
  845. # - x.00.pth, x.01.pth, etc.
  846. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  847. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  848. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  849. # x.bin, x.bin.1, etc.
  850. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  851. ]
  852. for regex, replacement in patterns:
  853. if re.search(regex, path.name):
  854. new_path = path.with_name(re.sub(regex, replacement, path.name))
  855. if new_path.exists():
  856. return new_path
  857. return None
  858. def find_multifile_paths(path: Path) -> list[Path]:
  859. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  860. the whole list of paths in the model.
  861. '''
  862. ret: list[Path] = []
  863. for i in itertools.count():
  864. nth_path = nth_multifile_path(path, i)
  865. if nth_path is None:
  866. break
  867. ret.append(nth_path)
  868. if not ret:
  869. # No matches. This should only happen if the file was named, e.g.,
  870. # foo.0, and there was no file named foo. Oh well, try to process it
  871. # as a single file.
  872. return [path]
  873. return ret
  874. def load_some_model(path: Path) -> ModelPlus:
  875. '''Load a model of any supported format.'''
  876. # Be extra-friendly and accept either a file or a directory:
  877. if path.is_dir():
  878. # Check if it's a set of safetensors files first
  879. globs = ["model-00001-of-*.safetensors", "model.safetensors"]
  880. files = [file for glob in globs for file in path.glob(glob)]
  881. if not files:
  882. # Try the PyTorch patterns too, with lower priority
  883. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  884. files = [file for glob in globs for file in path.glob(glob)]
  885. if not files:
  886. raise Exception(f"Can't find model in directory {path}")
  887. if len(files) > 1:
  888. raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
  889. path = files[0]
  890. paths = find_multifile_paths(path)
  891. models_plus: list[ModelPlus] = []
  892. for path in paths:
  893. print(f"Loading model file {path}")
  894. models_plus.append(lazy_load_file(path))
  895. model_plus = merge_multifile_models(models_plus)
  896. return model_plus
  897. def load_vocab(path: Path, vocabtype: str | None) -> Vocab:
  898. # Be extra-friendly and accept either a file or a directory. Also, if it's
  899. # a directory, it might be the model directory, and tokenizer.model might
  900. # be in the parent of that.
  901. if path.is_dir():
  902. vocab_file = "tokenizer.model"
  903. if vocabtype == 'bpe':
  904. vocab_file = "vocab.json"
  905. path2 = path / vocab_file
  906. # Use `.parent` instead of /.. to handle the symlink case better.
  907. path3 = path.parent / vocab_file
  908. if path2.exists():
  909. path = path2
  910. elif path3.exists():
  911. path = path3
  912. else:
  913. raise FileNotFoundError(
  914. f"Could not find {vocab_file} in {path} or its parent; "
  915. "if it's in another directory, pass the directory as --vocab-dir")
  916. print(f"Loading vocab file '{path}', type '{vocabtype}'")
  917. added_tokens_path = path.parent / "added_tokens.json"
  918. if vocabtype == "bpe":
  919. return BpeVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  920. elif vocabtype == "spm":
  921. return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  922. else:
  923. raise ValueError(f"Unsupported vocabulary type {vocabtype}")
  924. def default_outfile(model_paths: list[Path], file_type: GGMLFileType) -> Path:
  925. namestr = {
  926. GGMLFileType.AllF32: "f32",
  927. GGMLFileType.MostlyF16: "f16",
  928. GGMLFileType.MostlyQ8_0:"q8_0",
  929. }[file_type]
  930. ret = model_paths[0].parent / f"ggml-model-{namestr}.gguf"
  931. if ret in model_paths:
  932. sys.stderr.write(
  933. f"Error: Default output path ({ret}) would overwrite the input. "
  934. "Please explicitly specify a path using --outfile.\n")
  935. sys.exit(1)
  936. return ret
  937. def do_dump_model(model_plus: ModelPlus) -> None:
  938. print(f"model_plus.paths = {model_plus.paths!r}")
  939. print(f"model_plus.format = {model_plus.format!r}")
  940. print(f"model_plus.vocab = {model_plus.vocab!r}")
  941. for name, lazy_tensor in model_plus.model.items():
  942. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
  943. def main(args_in: list[str] | None = None) -> None:
  944. output_choices = ["f32", "f16"]
  945. if np.uint32(1) == np.uint32(1).newbyteorder("<"):
  946. # We currently only support Q8_0 output on little endian systems.
  947. output_choices.append("q8_0")
  948. parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
  949. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  950. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  951. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  952. parser.add_argument("--outtype", choices=output_choices, help="output format - note: q8_0 may be very slow (default: f16 or f32 based on input)")
  953. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  954. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  955. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin, *.safetensors)")
  956. parser.add_argument("--vocabtype", choices=["spm", "bpe"], help="vocab format (default: spm)", default="spm")
  957. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  958. parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default = DEFAULT_CONCURRENCY)
  959. parser.add_argument("--bigendian", action="store_true", help="model is executed on big endian machine")
  960. args = parser.parse_args(args_in)
  961. if args.dump_single:
  962. model_plus = lazy_load_file(args.model)
  963. do_dump_model(model_plus)
  964. return
  965. if not args.vocab_only:
  966. model_plus = load_some_model(args.model)
  967. else:
  968. model_plus = ModelPlus(model = {}, paths = [args.model / 'dummy'], format = 'none', vocab = None)
  969. if args.dump:
  970. do_dump_model(model_plus)
  971. return
  972. endianess = gguf.GGUFEndian.LITTLE
  973. if args.bigendian:
  974. endianess = gguf.GGUFEndian.BIG
  975. params = Params.load(model_plus)
  976. if params.n_ctx == -1:
  977. if args.ctx is None:
  978. raise Exception("The model doesn't have a context size, and you didn't specify one with --ctx\n"
  979. "Please specify one with --ctx:\n"
  980. " - LLaMA v1: --ctx 2048\n"
  981. " - LLaMA v2: --ctx 4096\n")
  982. params.n_ctx = args.ctx
  983. if args.outtype:
  984. params.ftype = {
  985. "f32": GGMLFileType.AllF32,
  986. "f16": GGMLFileType.MostlyF16,
  987. "q8_0": GGMLFileType.MostlyQ8_0,
  988. }[args.outtype]
  989. print(f"params = {params}")
  990. vocab: Vocab
  991. if args.vocab_only:
  992. if not args.outfile:
  993. raise ValueError("need --outfile if using --vocab-only")
  994. # FIXME: Try to respect vocab_dir somehow?
  995. vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype)
  996. special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent,
  997. load_merges = args.vocabtype == 'bpe',
  998. n_vocab = vocab.vocab_size)
  999. outfile = args.outfile
  1000. OutputFile.write_vocab_only(outfile, params, vocab, special_vocab)
  1001. print(f"Wrote {outfile}")
  1002. return
  1003. if model_plus.vocab is not None and args.vocab_dir is None:
  1004. vocab = model_plus.vocab
  1005. else:
  1006. vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
  1007. vocab = load_vocab(vocab_dir, args.vocabtype)
  1008. # FIXME: Try to respect vocab_dir somehow?
  1009. special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent,
  1010. load_merges = args.vocabtype == 'bpe',
  1011. n_vocab = vocab.vocab_size)
  1012. model = model_plus.model
  1013. model = convert_model_names(model, params)
  1014. ftype = pick_output_type(model, args.outtype)
  1015. model = convert_to_output_type(model, ftype)
  1016. outfile = args.outfile or default_outfile(model_plus.paths, ftype)
  1017. params.ftype = ftype
  1018. print(f"Writing {outfile}, format {ftype}")
  1019. OutputFile.write_all(outfile, ftype, params, model, vocab, special_vocab, concurrency = args.concurrency, endianess=endianess)
  1020. print(f"Wrote {outfile}")
  1021. if __name__ == '__main__':
  1022. main()