convert_legacy_llama.py 56 KB

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