convert.py 48 KB

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