convert.py 49 KB

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