convert.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import argparse
  4. import concurrent.futures
  5. import copy
  6. import enum
  7. import faulthandler
  8. import functools
  9. import io
  10. import itertools
  11. import json
  12. import math
  13. import mmap
  14. import pickle
  15. import re
  16. import signal
  17. import struct
  18. import sys
  19. import time
  20. import zipfile
  21. from abc import ABCMeta, abstractmethod
  22. from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
  23. from dataclasses import dataclass
  24. from pathlib import Path
  25. from typing import IO, TYPE_CHECKING, Any, Callable, Generator, Iterable, Literal, Sequence, TypeVar
  26. import numpy as np
  27. from sentencepiece import SentencePieceProcessor # type: ignore[import]
  28. import os
  29. if 'NO_LOCAL_GGUF' not in os.environ:
  30. sys.path.insert(1, str(Path(__file__).parent / 'gguf-py' / 'gguf'))
  31. import gguf
  32. if TYPE_CHECKING:
  33. from typing import TypeAlias
  34. if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
  35. faulthandler.register(signal.SIGUSR1)
  36. NDArray: TypeAlias = 'np.ndarray[Any, Any]'
  37. ARCH=gguf.MODEL_ARCH.LLAMA
  38. NAMES=gguf.MODEL_TENSOR_NAMES[ARCH]
  39. DEFAULT_CONCURRENCY = 8
  40. #
  41. # data types
  42. #
  43. @dataclass(frozen=True)
  44. class DataType:
  45. name: str
  46. dtype: np.dtype[Any]
  47. valid_conversions: list[str]
  48. def elements_to_bytes(self, n_elements: int) -> int:
  49. return n_elements * self.dtype.itemsize
  50. @dataclass(frozen=True)
  51. class UnquantizedDataType(DataType):
  52. pass
  53. DT_F16 = UnquantizedDataType('F16', dtype = np.dtype(np.float16), valid_conversions = ['F32', 'Q8_0'])
  54. DT_F32 = UnquantizedDataType('F32', dtype = np.dtype(np.float32), valid_conversions = ['F16', 'Q8_0'])
  55. DT_I32 = UnquantizedDataType('I32', dtype = np.dtype(np.int16), valid_conversions = [])
  56. DT_BF16 = UnquantizedDataType('BF16', dtype = np.dtype(np.uint16), valid_conversions = ['F32', 'F16', 'Q8_0'])
  57. @dataclass(frozen=True)
  58. class QuantizedDataType(DataType):
  59. block_size: int
  60. quantized_dtype: np.dtype[Any]
  61. ggml_type: gguf.GGMLQuantizationType
  62. def quantize(self, arr: NDArray) -> NDArray:
  63. raise NotImplementedError(f'Quantization for {self.name} not implemented')
  64. def elements_to_bytes(self, n_elements: int) -> int:
  65. assert n_elements % self.block_size == 0, f'Invalid number of elements {n_elements} for {self.name} with block size {self.block_size}'
  66. return self.quantized_dtype.itemsize * (n_elements // self.block_size)
  67. @dataclass(frozen=True)
  68. class Q8_0QuantizedDataType(QuantizedDataType):
  69. # Mini Q8_0 quantization in Python!
  70. def quantize(self, arr: NDArray) -> NDArray:
  71. assert arr.size % self.block_size == 0 and arr.size != 0, f'Bad array size {arr.size}'
  72. assert arr.dtype == np.float32, f'Bad array type {arr.dtype}'
  73. n_blocks = arr.size // self.block_size
  74. blocks = arr.reshape((n_blocks, self.block_size))
  75. # Much faster implementation of block quantization contributed by @Cebtenzzre
  76. def quantize_blocks_q8_0(blocks: NDArray) -> Iterable[tuple[Any, Any]]:
  77. d = abs(blocks).max(axis = 1) / np.float32(127)
  78. with np.errstate(divide = 'ignore'):
  79. qs = (blocks / d[:, None]).round()
  80. qs[d == 0] = 0
  81. yield from zip(d, qs)
  82. return np.fromiter(quantize_blocks_q8_0(blocks), count = n_blocks, dtype = self.quantized_dtype)
  83. DT_Q8_0 = Q8_0QuantizedDataType('Q8_0',
  84. dtype = np.dtype(np.float32), valid_conversions = [],
  85. ggml_type = gguf.GGMLQuantizationType.Q8_0, block_size = 32,
  86. quantized_dtype = np.dtype([('d', '<f2'), ('qs', 'i1', (32,))]))
  87. # Quantized types skipped here because they may also map to np.float32
  88. NUMPY_TYPE_TO_DATA_TYPE: dict[np.dtype[Any], DataType] = {}
  89. for dt in (DT_BF16, DT_F16, DT_F32, DT_I32):
  90. if dt.dtype in NUMPY_TYPE_TO_DATA_TYPE:
  91. raise ValueError(f'Invalid duplicate data type {dt}')
  92. NUMPY_TYPE_TO_DATA_TYPE[dt.dtype] = dt
  93. SAFETENSORS_DATA_TYPES: dict[str, DataType] = {
  94. 'BF16': DT_BF16,
  95. 'F16': DT_F16,
  96. 'F32': DT_F32,
  97. 'I32': DT_I32,
  98. }
  99. # TODO: match this with `llama_ftype`
  100. # TODO: rename to LLAMAFileType
  101. # TODO: move to `gguf.py`
  102. class GGMLFileType(enum.IntEnum):
  103. AllF32 = 0
  104. MostlyF16 = 1 # except 1d tensors
  105. MostlyQ8_0 = 7 # except 1d tensors
  106. def type_for_tensor(self, name: str, tensor: LazyTensor) -> DataType:
  107. dt = GGML_FILE_TYPE_TO_DATA_TYPE.get(self)
  108. if dt is None:
  109. raise ValueError(self)
  110. # 1D tensors are always F32.
  111. return dt if len(tensor.shape) > 1 else DT_F32
  112. GGML_FILE_TYPE_TO_DATA_TYPE: dict[GGMLFileType, DataType] = {
  113. GGMLFileType.AllF32 : DT_F32,
  114. GGMLFileType.MostlyF16 : DT_F16,
  115. GGMLFileType.MostlyQ8_0: DT_Q8_0,
  116. }
  117. #
  118. # hparams loading
  119. #
  120. @dataclass
  121. class Params:
  122. n_vocab: int
  123. n_embd: int
  124. n_layer: int
  125. n_ctx: int
  126. n_ff: int
  127. n_head: int
  128. n_head_kv: int
  129. f_norm_eps: float
  130. f_rope_freq_base: float | None = None
  131. f_rope_scale: float | None = None
  132. ftype: GGMLFileType | None = None
  133. # path to the directory containing the model files
  134. path_model: Path | None = None
  135. @staticmethod
  136. def guessed(model: LazyModel) -> Params:
  137. # try transformer naming first
  138. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  139. # try transformer naming first
  140. if "model.layers.0.self_attn.q_proj.weight" in model:
  141. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  142. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  143. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  144. else:
  145. n_layer=next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  146. if n_layer < 1:
  147. raise Exception("failed to guess 'n_layer'. This model is unknown or unsupported.\n"
  148. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  149. n_head = n_embd // 128 # guessed
  150. n_mult = 256 # guessed
  151. # TODO: verify this
  152. n_ff = int(2 * (4 * n_embd) / 3)
  153. n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
  154. return Params(
  155. n_vocab = n_vocab,
  156. n_embd = n_embd,
  157. n_layer = n_layer,
  158. n_ctx = -1,
  159. n_ff = n_ff,
  160. n_head = n_head,
  161. n_head_kv = n_head,
  162. f_norm_eps = 1e-5,
  163. )
  164. @staticmethod
  165. def loadHFTransformerJson(model: LazyModel, config_path: Path) -> Params:
  166. config = json.load(open(config_path))
  167. n_vocab = config["vocab_size"]
  168. n_embd = config["hidden_size"]
  169. n_layer = config["num_hidden_layers"]
  170. n_ff = config["intermediate_size"]
  171. n_head = config["num_attention_heads"]
  172. n_head_kv = config["num_key_value_heads"] if "num_key_value_heads" in config else n_head
  173. f_norm_eps = config["rms_norm_eps"]
  174. f_rope_freq_base = config["rope_theta"] if "rope_theta" in config else None
  175. rope_scaling = config.get("rope_scaling")
  176. if isinstance(rope_scaling, dict) and rope_scaling.get("type") == "linear":
  177. f_rope_scale = config["rope_scaling"].get("factor")
  178. else:
  179. f_rope_scale = None
  180. if "max_sequence_length" in config:
  181. n_ctx = config["max_sequence_length"]
  182. elif "max_position_embeddings" in config:
  183. n_ctx = config["max_position_embeddings"]
  184. else:
  185. raise Exception("failed to guess 'n_ctx'. This model is unknown or unsupported.\n"
  186. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  187. return Params(
  188. n_vocab = n_vocab,
  189. n_embd = n_embd,
  190. n_layer = n_layer,
  191. n_ctx = n_ctx,
  192. n_ff = n_ff,
  193. n_head = n_head,
  194. n_head_kv = n_head_kv,
  195. f_norm_eps = f_norm_eps,
  196. f_rope_freq_base = f_rope_freq_base,
  197. f_rope_scale = f_rope_scale,
  198. )
  199. # LLaMA v2 70B params.json
  200. # {"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}
  201. @staticmethod
  202. def loadOriginalParamsJson(model: LazyModel, config_path: Path) -> Params:
  203. config = json.load(open(config_path))
  204. n_vocab = config["vocab_size"] if "vocab_size" in config else -1
  205. n_embd = config["dim"]
  206. n_layer = config["n_layers"]
  207. n_ff = -1
  208. n_head = config["n_heads"]
  209. n_head_kv = config["n_kv_heads"] if "n_kv_heads" in config else n_head
  210. f_norm_eps = config["norm_eps"]
  211. f_rope_freq_base = config["rope_theta"] if "rope_theta" in config else None
  212. # hack to determine LLaMA v1 vs v2 vs CodeLlama
  213. if f_rope_freq_base == 1000000:
  214. # CodeLlama
  215. n_ctx = 16384
  216. elif config["norm_eps"] == 1e-05:
  217. # LLaMA v2
  218. n_ctx = 4096
  219. else:
  220. # LLaMA v1
  221. n_ctx = 2048
  222. if n_vocab == -1:
  223. n_vocab = model["tok_embeddings.weight"].shape[0]
  224. if n_ff == -1:
  225. n_ff = model["layers.0.feed_forward.w1.weight"].shape[0]
  226. return Params(
  227. n_vocab = n_vocab,
  228. n_embd = n_embd,
  229. n_layer = n_layer,
  230. n_ctx = n_ctx,
  231. n_ff = n_ff,
  232. n_head = n_head,
  233. n_head_kv = n_head_kv,
  234. f_norm_eps = f_norm_eps,
  235. f_rope_freq_base = f_rope_freq_base,
  236. )
  237. @staticmethod
  238. def load(model_plus: ModelPlus) -> Params:
  239. hf_config_path = model_plus.paths[0].parent / "config.json"
  240. orig_config_path = model_plus.paths[0].parent / "params.json"
  241. if hf_config_path.exists():
  242. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  243. elif orig_config_path.exists():
  244. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  245. elif model_plus.format != 'none':
  246. params = Params.guessed(model_plus.model)
  247. else:
  248. raise ValueError('Cannot guess params when model format is none')
  249. params.path_model = model_plus.paths[0].parent
  250. return params
  251. #
  252. # vocab
  253. #
  254. class BpeVocab:
  255. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
  256. self.bpe_tokenizer = json.loads(open(str(fname_tokenizer), encoding="utf-8").read())
  257. added_tokens: dict[str, int]
  258. if fname_added_tokens is not None:
  259. # FIXME: Verify that added tokens here _cannot_ overlap with the main vocab.
  260. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  261. else:
  262. # Fall back to trying to find the added tokens in tokenizer.json
  263. tokenizer_json_file = fname_tokenizer.parent / 'tokenizer.json'
  264. if not tokenizer_json_file.is_file():
  265. added_tokens = {}
  266. else:
  267. tokenizer_json = json.load(open(tokenizer_json_file, encoding="utf-8"))
  268. added_tokens = dict(
  269. (item['content'], item['id'])
  270. for item in tokenizer_json.get('added_tokens', [])
  271. # Added tokens here can be duplicates of the main vocabulary.
  272. if item['content'] not in self.bpe_tokenizer )
  273. vocab_size: int = len(self.bpe_tokenizer)
  274. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  275. actual_ids = sorted(added_tokens.values())
  276. if expected_ids != actual_ids:
  277. expected_end_id = vocab_size + len(actual_ids) - 1
  278. 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}")
  279. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  280. self.added_tokens_list = [text for (text, idx) in items]
  281. self.vocab_size_base: int = vocab_size
  282. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  283. self.fname_tokenizer = fname_tokenizer
  284. self.fname_added_tokens = fname_added_tokens
  285. def bpe_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  286. tokenizer = self.bpe_tokenizer
  287. from transformers.models.gpt2 import tokenization_gpt2 # type: ignore[import]
  288. byte_encoder = tokenization_gpt2.bytes_to_unicode()
  289. byte_decoder = {v: k for k, v in byte_encoder.items()}
  290. score = 0.0
  291. for i, item in enumerate(tokenizer):
  292. text: bytes = item.encode("utf-8")
  293. # FIXME: These shouldn't be hardcoded, but it's probably better than the current behavior?
  294. if i <= 258 and text.startswith(b'<') and text.endswith(b'>'):
  295. if i == 0 and text == b'<unk>':
  296. toktype = gguf.TokenType.UNKNOWN
  297. elif i == 1 or i == 2:
  298. toktype = gguf.TokenType.CONTROL
  299. elif i >= 3 and text.startswith(b'<0x'):
  300. toktype = gguf.TokenType.BYTE
  301. else:
  302. toktype = gguf.TokenType.NORMAL
  303. else:
  304. toktype = gguf.TokenType.NORMAL
  305. yield text, score, toktype
  306. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  307. for text in self.added_tokens_list:
  308. score = -1000.0
  309. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  310. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  311. yield from self.bpe_tokens()
  312. yield from self.added_tokens()
  313. def __repr__(self) -> str:
  314. return f"<BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  315. class SentencePieceVocab:
  316. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None:
  317. self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
  318. added_tokens: dict[str, int]
  319. if fname_added_tokens is not None:
  320. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  321. else:
  322. added_tokens = {}
  323. vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
  324. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  325. actual_ids = sorted(added_tokens.values())
  326. if expected_ids != actual_ids:
  327. raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
  328. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  329. self.added_tokens_list = [text for (text, idx) in items]
  330. self.vocab_size_base: int = vocab_size
  331. self.vocab_size: int = 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 indivdual 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 detrmine
  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. as_dict = dict(model.items())
  588. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  589. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  590. header_size, = struct.unpack('<Q', fp.read(8))
  591. header: dict[str, dict[str, Any]] = json.loads(fp.read(header_size))
  592. # Use mmap for the actual data to avoid race conditions with the file offset.
  593. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  594. byte_buf = mapped[8 + header_size:]
  595. def convert(info: dict[str, Any]) -> LazyTensor:
  596. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  597. numpy_dtype = data_type.dtype
  598. shape: list[int] = info['shape']
  599. begin, end = info['data_offsets']
  600. assert 0 <= begin <= end <= len(byte_buf)
  601. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  602. buf = byte_buf[begin:end]
  603. def load() -> UnquantizedTensor:
  604. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  605. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  606. return LazyTensor(load, shape, data_type, description)
  607. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  608. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  609. def must_read(fp: IO[bytes], length: int) -> bytes:
  610. ret = fp.read(length)
  611. if len(ret) < length:
  612. raise Exception("unexpectedly reached end of file")
  613. return ret
  614. @functools.lru_cache(maxsize=None)
  615. def lazy_load_file(path: Path) -> ModelPlus:
  616. fp = open(path, 'rb')
  617. first8 = fp.read(8)
  618. fp.seek(0)
  619. if first8[:2] == b'PK':
  620. # A zip file, i.e. PyTorch format
  621. return lazy_load_torch_file(fp, path)
  622. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  623. # Probably safetensors
  624. return lazy_load_safetensors_file(fp, path)
  625. else:
  626. raise ValueError(f"unknown format: {path}")
  627. In = TypeVar('In')
  628. Out = TypeVar('Out')
  629. 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]:
  630. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  631. fast enough, this will stop calling `func` at some point rather than
  632. letting results pile up in memory. Specifically, there is a max of one
  633. output value buffered per thread.'''
  634. if concurrency < 2:
  635. yield from map(func, iterable)
  636. # Not reached.
  637. iterable = iter(iterable)
  638. executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor]
  639. if use_processpool_executor:
  640. executor_class = ProcessPoolExecutor
  641. else:
  642. executor_class = ThreadPoolExecutor
  643. with executor_class(max_workers = max_workers) as executor:
  644. futures: list[concurrent.futures.Future[Out]] = []
  645. done = False
  646. for _ in range(concurrency):
  647. try:
  648. futures.append(executor.submit(func, next(iterable)))
  649. except StopIteration:
  650. done = True
  651. break
  652. while futures:
  653. result = futures.pop(0).result()
  654. while not done and len(futures) < concurrency:
  655. try:
  656. futures.append(executor.submit(func, next(iterable)))
  657. except StopIteration:
  658. done = True
  659. break
  660. yield result
  661. def check_vocab_size(params: Params, vocab: Vocab) -> None:
  662. if params.n_vocab != vocab.vocab_size:
  663. assert isinstance(vocab, BpeVocab) or isinstance(vocab, SentencePieceVocab)
  664. if params.n_vocab == vocab.vocab_size_base:
  665. print("Ignoring added_tokens.json since model matches vocab size without it.")
  666. vocab.added_tokens_list = []
  667. vocab.vocab_size = vocab.vocab_size_base
  668. return
  669. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
  670. if vocab.fname_added_tokens is not None:
  671. msg += f" combined with {vocab.fname_added_tokens}"
  672. msg += f" has {vocab.vocab_size})."
  673. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
  674. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  675. raise Exception(msg)
  676. class OutputFile:
  677. def __init__(self, fname_out: Path) -> None:
  678. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
  679. def add_meta_arch(self, params: Params) -> None:
  680. name = "LLaMA"
  681. # TODO: better logic to determine model name
  682. if params.n_ctx == 4096:
  683. name = "LLaMA v2"
  684. elif params.path_model is not None:
  685. name = str(params.path_model.parent).split('/')[-1]
  686. self.gguf.add_name (name)
  687. self.gguf.add_context_length (params.n_ctx)
  688. self.gguf.add_embedding_length (params.n_embd)
  689. self.gguf.add_block_count (params.n_layer)
  690. self.gguf.add_feed_forward_length (params.n_ff)
  691. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  692. self.gguf.add_head_count (params.n_head)
  693. self.gguf.add_head_count_kv (params.n_head_kv)
  694. self.gguf.add_layer_norm_rms_eps (params.f_norm_eps)
  695. if params.f_rope_freq_base is not None:
  696. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  697. if params.f_rope_scale is not None:
  698. self.gguf.add_rope_scale_linear(params.f_rope_scale)
  699. if params.ftype is not None:
  700. self.gguf.add_file_type(params.ftype)
  701. def add_meta_vocab(self, vocab: Vocab) -> None:
  702. tokens = []
  703. scores = []
  704. toktypes = []
  705. # NOTE: `all_tokens` returns the base vocabulary and added tokens
  706. for text, score, toktype in vocab.all_tokens():
  707. tokens.append(text)
  708. scores.append(score)
  709. toktypes.append(toktype)
  710. if isinstance(vocab, SentencePieceVocab):
  711. self.gguf.add_tokenizer_model("llama")
  712. elif isinstance(vocab, BpeVocab):
  713. self.gguf.add_tokenizer_model("gpt2")
  714. else:
  715. raise ValueError(f'Unknown vocab type: Not BpeVocab or SentencePieceVocab')
  716. self.gguf.add_token_list(tokens)
  717. self.gguf.add_token_scores(scores)
  718. self.gguf.add_token_types(toktypes)
  719. def add_meta_special_vocab(self, svocab: gguf.SpecialVocab) -> None:
  720. svocab.add_to_gguf(self.gguf)
  721. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  722. n_elements = int(np.prod(tensor.shape))
  723. raw_dtype = getattr(tensor.data_type, 'ggml_type', None)
  724. data_type = getattr(tensor.data_type, 'quantized_type', None) or tensor.data_type.dtype
  725. data_nbytes = tensor.data_type.elements_to_bytes(n_elements)
  726. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes, raw_dtype = raw_dtype)
  727. def write_meta(self) -> None:
  728. self.gguf.write_header_to_file()
  729. self.gguf.write_kv_data_to_file()
  730. def write_tensor_info(self) -> None:
  731. self.gguf.write_ti_data_to_file()
  732. def close(self) -> None:
  733. self.gguf.close()
  734. @staticmethod
  735. def write_vocab_only(fname_out: Path, params: Params, vocab: Vocab, svocab: gguf.SpecialVocab) -> None:
  736. check_vocab_size(params, vocab)
  737. of = OutputFile(fname_out)
  738. # meta data
  739. of.add_meta_arch(params)
  740. of.add_meta_vocab(vocab)
  741. of.add_meta_special_vocab(svocab)
  742. of.write_meta()
  743. of.close()
  744. @staticmethod
  745. def do_item(item: tuple[str, LazyTensor]) -> tuple[DataType, NDArray]:
  746. name, lazy_tensor = item
  747. tensor = lazy_tensor.load().to_ggml()
  748. return (lazy_tensor.data_type, tensor.ndarray)
  749. @staticmethod
  750. def maybe_do_quantize(item: tuple[DataType, NDArray]) -> NDArray:
  751. dt, arr = item
  752. if not isinstance(dt, QuantizedDataType):
  753. return arr
  754. return dt.quantize(arr)
  755. @staticmethod
  756. def write_all(fname_out: Path, ftype: GGMLFileType, params: Params, model: LazyModel, vocab: Vocab, svocab: gguf.SpecialVocab, concurrency: int = DEFAULT_CONCURRENCY) -> None:
  757. check_vocab_size(params, vocab)
  758. of = OutputFile(fname_out)
  759. # meta data
  760. of.add_meta_arch(params)
  761. of.add_meta_vocab(vocab)
  762. of.add_meta_special_vocab(svocab)
  763. # tensor info
  764. for name, lazy_tensor in model.items():
  765. of.add_tensor_info(name, lazy_tensor)
  766. of.write_meta()
  767. of.write_tensor_info()
  768. # tensor data
  769. ndarrays_inner = bounded_parallel_map(OutputFile.do_item, model.items(), concurrency = concurrency)
  770. if ftype == GGMLFileType.MostlyQ8_0:
  771. ndarrays = bounded_parallel_map(OutputFile.maybe_do_quantize, ndarrays_inner, concurrency = concurrency, max_workers = concurrency, use_processpool_executor = True)
  772. else:
  773. ndarrays = map(OutputFile.maybe_do_quantize, ndarrays_inner)
  774. start = time.time()
  775. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  776. elapsed = time.time() - start
  777. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  778. padi = len(str(len(model)))
  779. 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}")
  780. of.gguf.write_tensor_data(ndarray)
  781. of.close()
  782. def pick_output_type(model: LazyModel, output_type_str: str | None) -> GGMLFileType:
  783. wq_type = model[NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0)+".weight"].data_type
  784. if output_type_str == "f32" or (output_type_str is None and wq_type == DT_F32):
  785. return GGMLFileType.AllF32
  786. if output_type_str == "f16" or (output_type_str is None and wq_type in (DT_F16, DT_BF16)):
  787. return GGMLFileType.MostlyF16
  788. if output_type_str == "q8_0":
  789. return GGMLFileType.MostlyQ8_0
  790. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  791. raise Exception(f"Unexpected combination of types: {name_to_type}")
  792. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  793. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  794. for (name, tensor) in model.items()}
  795. def convert_model_names(model: LazyModel, params: Params) -> LazyModel:
  796. tmap = gguf.TensorNameMap(ARCH, params.n_layer)
  797. should_skip: set[gguf.MODEL_TENSOR] = set(gguf.MODEL_TENSOR_SKIP.get(ARCH, []))
  798. tmp = model
  799. # HF models permut or pack some of the tensors, so we need to undo that
  800. for i in itertools.count():
  801. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  802. print(f"Permuting layer {i}")
  803. 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)
  804. 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)
  805. #tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  806. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  807. print(f"Unpacking and permuting layer {i}")
  808. 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)
  809. 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)
  810. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  811. del tmp[f"model.layers.{i}.self_attn.W_pack.weight"]
  812. else:
  813. break
  814. out: LazyModel = {}
  815. for name, lazy_tensor in model.items():
  816. tensor_type, name_new = tmap.get_type_and_name(name, try_suffixes = (".weight", ".bias")) or (None, None)
  817. if name_new is None:
  818. raise Exception(f"Unexpected tensor name: {name}")
  819. if tensor_type in should_skip:
  820. print(f"skipping tensor {name_new}")
  821. continue
  822. print(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type.name:6s} | {lazy_tensor.shape}")
  823. out[name_new] = lazy_tensor
  824. return out
  825. def nth_multifile_path(path: Path, n: int) -> Path | None:
  826. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  827. the nth path in the model.
  828. '''
  829. # Support the following patterns:
  830. patterns: list[tuple[str, str]] = [
  831. # - x.00.pth, x.01.pth, etc.
  832. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  833. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  834. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  835. # x.bin, x.bin.1, etc.
  836. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  837. ]
  838. for regex, replacement in patterns:
  839. if re.search(regex, path.name):
  840. new_path = path.with_name(re.sub(regex, replacement, path.name))
  841. if new_path.exists():
  842. return new_path
  843. return None
  844. def find_multifile_paths(path: Path) -> list[Path]:
  845. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  846. the whole list of paths in the model.
  847. '''
  848. ret: list[Path] = []
  849. for i in itertools.count():
  850. nth_path = nth_multifile_path(path, i)
  851. if nth_path is None:
  852. break
  853. ret.append(nth_path)
  854. if not ret:
  855. # No matches. This should only happen if the file was named, e.g.,
  856. # foo.0, and there was no file named foo. Oh well, try to process it
  857. # as a single file.
  858. return [path]
  859. return ret
  860. def load_some_model(path: Path) -> ModelPlus:
  861. '''Load a model of any supported format.'''
  862. # Be extra-friendly and accept either a file or a directory:
  863. if path.is_dir():
  864. # Check if it's a set of safetensors files first
  865. files = list(path.glob("model-00001-of-*.safetensors"))
  866. if not files:
  867. # Try the PyTorch patterns too, with lower priority
  868. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  869. files = [file for glob in globs for file in path.glob(glob)]
  870. if not files:
  871. raise Exception(f"Can't find model in directory {path}")
  872. if len(files) > 1:
  873. raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
  874. path = files[0]
  875. paths = find_multifile_paths(path)
  876. models_plus: list[ModelPlus] = []
  877. for path in paths:
  878. print(f"Loading model file {path}")
  879. models_plus.append(lazy_load_file(path))
  880. model_plus = merge_multifile_models(models_plus)
  881. return model_plus
  882. def load_vocab(path: Path, vocabtype: str | None) -> Vocab:
  883. # Be extra-friendly and accept either a file or a directory. Also, if it's
  884. # a directory, it might be the model directory, and tokenizer.model might
  885. # be in the parent of that.
  886. if path.is_dir():
  887. vocab_file = "tokenizer.model"
  888. if vocabtype == 'bpe':
  889. vocab_file = "vocab.json"
  890. path2 = path / vocab_file
  891. # Use `.parent` instead of /.. to handle the symlink case better.
  892. path3 = path.parent / vocab_file
  893. if path2.exists():
  894. path = path2
  895. elif path3.exists():
  896. path = path3
  897. else:
  898. raise FileNotFoundError(
  899. f"Could not find {vocab_file} in {path} or its parent; "
  900. "if it's in another directory, pass the directory as --vocab-dir")
  901. print(f"Loading vocab file '{path}', type '{vocabtype}'")
  902. added_tokens_path = path.parent / "added_tokens.json"
  903. if vocabtype == "bpe":
  904. return BpeVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  905. elif vocabtype == "spm":
  906. return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  907. else:
  908. raise ValueError(f"Unsupported vocabulary type {vocabtype}")
  909. def default_outfile(model_paths: list[Path], file_type: GGMLFileType) -> Path:
  910. namestr = {
  911. GGMLFileType.AllF32: "f32",
  912. GGMLFileType.MostlyF16: "f16",
  913. GGMLFileType.MostlyQ8_0:"q8_0",
  914. }[file_type]
  915. ret = model_paths[0].parent / f"ggml-model-{namestr}.gguf"
  916. if ret in model_paths:
  917. sys.stderr.write(
  918. f"Error: Default output path ({ret}) would overwrite the input. "
  919. "Please explicitly specify a path using --outfile.\n")
  920. sys.exit(1)
  921. return ret
  922. def do_dump_model(model_plus: ModelPlus) -> None:
  923. print(f"model_plus.paths = {model_plus.paths!r}")
  924. print(f"model_plus.format = {model_plus.format!r}")
  925. print(f"model_plus.vocab = {model_plus.vocab!r}")
  926. for name, lazy_tensor in model_plus.model.items():
  927. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
  928. def main(args_in: list[str] | None = None) -> None:
  929. parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
  930. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  931. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  932. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  933. parser.add_argument("--outtype", choices=["f32", "f16", "q8_0"], help="output format - note: q8_0 may be very slow (default: f16 or f32 based on input)")
  934. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  935. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  936. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
  937. parser.add_argument("--vocabtype", choices=["spm", "bpe"], help="vocab format (default: spm)", default="spm")
  938. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  939. parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default = DEFAULT_CONCURRENCY)
  940. args = parser.parse_args(args_in)
  941. if args.dump_single:
  942. model_plus = lazy_load_file(args.model)
  943. do_dump_model(model_plus)
  944. return
  945. if not args.vocab_only:
  946. model_plus = load_some_model(args.model)
  947. else:
  948. model_plus = ModelPlus(model = {}, paths = [args.model / 'dummy'], format = 'none', vocab = None)
  949. if args.dump:
  950. do_dump_model(model_plus)
  951. return
  952. params = Params.load(model_plus)
  953. if params.n_ctx == -1:
  954. if args.ctx is None:
  955. raise Exception("The model doesn't have a context size, and you didn't specify one with --ctx\n"
  956. "Please specify one with --ctx:\n"
  957. " - LLaMA v1: --ctx 2048\n"
  958. " - LLaMA v2: --ctx 4096\n")
  959. params.n_ctx = args.ctx
  960. if args.outtype:
  961. params.ftype = {
  962. "f32": GGMLFileType.AllF32,
  963. "f16": GGMLFileType.MostlyF16,
  964. "q8_0": GGMLFileType.MostlyQ8_0,
  965. }[args.outtype]
  966. print(f"params = {params}")
  967. vocab: Vocab
  968. if args.vocab_only:
  969. assert args.outfile, "need --outfile if using --vocab-only"
  970. # FIXME: Try to respect vocab_dir somehow?
  971. vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype)
  972. special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype == 'bpe')
  973. outfile = args.outfile
  974. OutputFile.write_vocab_only(outfile, params, vocab, special_vocab)
  975. print(f"Wrote {outfile}")
  976. return
  977. if model_plus.vocab is not None and args.vocab_dir is None:
  978. vocab = model_plus.vocab
  979. else:
  980. vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
  981. vocab = load_vocab(vocab_dir, args.vocabtype)
  982. # FIXME: Try to respect vocab_dir somehow?
  983. special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype == 'bpe')
  984. model = model_plus.model
  985. model = convert_model_names(model, params)
  986. ftype = pick_output_type(model, args.outtype)
  987. model = convert_to_output_type(model, ftype)
  988. outfile = args.outfile or default_outfile(model_plus.paths, ftype)
  989. params.ftype = ftype
  990. print(f"Writing {outfile}, format {ftype}")
  991. OutputFile.write_all(outfile, ftype, params, model, vocab, special_vocab, concurrency = args.concurrency)
  992. print(f"Wrote {outfile}")
  993. if __name__ == '__main__':
  994. main()