1
0

convert_legacy_llama.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  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
  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. #
  282. # data loading
  283. # TODO: reuse (probably move to gguf.py?)
  284. #
  285. def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
  286. if n_head_kv is not None and n_head != n_head_kv:
  287. n_head = n_head_kv
  288. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  289. .swapaxes(1, 2)
  290. .reshape(weights.shape))
  291. class Tensor(ABC):
  292. ndarray: NDArray
  293. data_type: DataType
  294. @abstractmethod
  295. def astype(self, data_type: DataType) -> Self: ...
  296. @abstractmethod
  297. def permute(self, n_head: int, n_head_kv: int) -> Self: ...
  298. @abstractmethod
  299. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> Self: ...
  300. @abstractmethod
  301. def part(self, n_part: int) -> Self: ...
  302. @abstractmethod
  303. def to_ggml(self) -> GGMLCompatibleTensor: ...
  304. def bf16_to_fp32(bf16_arr: np.ndarray[Any, np.dtype[np.uint16]]) -> NDArray:
  305. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  306. fp32_arr = bf16_arr.astype(np.uint32) << 16
  307. return fp32_arr.view(np.float32)
  308. class UnquantizedTensor(Tensor):
  309. def __init__(self, ndarray: NDArray):
  310. assert isinstance(ndarray, np.ndarray)
  311. self.ndarray = ndarray
  312. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  313. def astype(self, data_type: DataType) -> UnquantizedTensor:
  314. dtype = data_type.dtype
  315. if self.data_type == DT_BF16:
  316. self.ndarray = bf16_to_fp32(self.ndarray)
  317. return UnquantizedTensor(self.ndarray.astype(dtype))
  318. def to_ggml(self) -> Self:
  319. return self
  320. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  321. r = self.ndarray.shape[0] // 3
  322. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head, n_head_kv))
  323. def part(self, n_part: int) -> UnquantizedTensor:
  324. r = self.ndarray.shape[0] // 3
  325. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  326. def permute(self, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  327. return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
  328. def load_unquantized(lazy_tensor: LazyTensor, expected_dtype: Any = None, convert: bool = False) -> NDArray:
  329. tensor = lazy_tensor.load()
  330. assert isinstance(tensor, UnquantizedTensor)
  331. # double-check:
  332. actual_shape = list(tensor.ndarray.shape)
  333. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  334. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  335. if convert:
  336. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  337. else:
  338. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  339. return tensor.ndarray
  340. GGMLCompatibleTensor = UnquantizedTensor
  341. @dataclass
  342. class LazyTensor:
  343. _load: Callable[[], Tensor]
  344. shape: list[int]
  345. data_type: DataType
  346. description: str
  347. def load(self) -> Tensor:
  348. ret = self._load()
  349. # Should be okay if it maps to the same numpy type?
  350. assert ret.data_type == self.data_type or (self.data_type.dtype == ret.data_type.dtype), \
  351. (self.data_type, ret.data_type, self.description)
  352. return ret
  353. def astype(self, data_type: DataType) -> LazyTensor:
  354. self.validate_conversion_to(data_type)
  355. def load() -> Tensor:
  356. return self.load().astype(data_type)
  357. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  358. def validate_conversion_to(self, data_type: DataType) -> None:
  359. if data_type != self.data_type and data_type.name not in self.data_type.valid_conversions:
  360. raise ValueError(f'Cannot validate conversion from {self.data_type} to {data_type}.')
  361. LazyModel: TypeAlias = 'dict[str, LazyTensor]'
  362. ModelFormat: TypeAlias = Literal['ggml', 'torch', 'safetensors', 'none']
  363. @dataclass
  364. class ModelPlus:
  365. model: LazyModel
  366. paths: list[Path] # Where this was read from.
  367. format: ModelFormat
  368. vocab: BaseVocab | None # For GGML models (which have vocab built in), the vocab.
  369. def merge_sharded(models: list[LazyModel]) -> LazyModel:
  370. # Original LLaMA models have each file contain one part of each tensor.
  371. # Use a dict instead of a set to preserve order.
  372. names = {name: None for model in models for name in model}
  373. def convert(name: str) -> LazyTensor:
  374. lazy_tensors = [model[name] for model in models]
  375. if len(lazy_tensors) == 1:
  376. # only one file; don't go through this procedure since there might
  377. # be quantized tensors
  378. return lazy_tensors[0]
  379. if len(lazy_tensors[0].shape) == 1:
  380. # the tensor is just duplicated in every file
  381. return lazy_tensors[0]
  382. if name.startswith('tok_embeddings.') or \
  383. name.endswith('.attention.wo.weight') or \
  384. name.endswith('.feed_forward.w2.weight'):
  385. # split by columns
  386. axis = 1
  387. else:
  388. # split by rows
  389. axis = 0
  390. concatenated_shape = list(lazy_tensors[0].shape)
  391. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  392. def load() -> UnquantizedTensor:
  393. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  394. concatenated = np.concatenate(ndarrays, axis=axis)
  395. return UnquantizedTensor(concatenated)
  396. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  397. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  398. return {name: convert(name) for name in names}
  399. def merge_multifile_models(models_plus: list[ModelPlus]) -> ModelPlus:
  400. formats: set[ModelFormat] = set(mp.format for mp in models_plus)
  401. assert len(formats) == 1, "different formats?"
  402. format = formats.pop()
  403. paths = [path for mp in models_plus for path in mp.paths]
  404. # Use the first non-None vocab, if any.
  405. try:
  406. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  407. except StopIteration:
  408. vocab = None
  409. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  410. # Transformers models put different tensors in different files, but
  411. # don't split individual tensors between files.
  412. model: LazyModel = {}
  413. for mp in models_plus:
  414. model.update(mp.model)
  415. else:
  416. model = merge_sharded([mp.model for mp in models_plus])
  417. return ModelPlus(model, paths, format, vocab)
  418. def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
  419. def load() -> Tensor:
  420. return lazy_tensor.load().permute(n_head, n_head_kv)
  421. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  422. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int, n_head_kv: int) -> LazyTensor:
  423. def load() -> Tensor:
  424. return lazy_tensor.load().permute_part(n_part, n_head, n_head_kv)
  425. s = lazy_tensor.shape.copy()
  426. s[0] = s[0] // 3
  427. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  428. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  429. def load() -> Tensor:
  430. return lazy_tensor.load().part(n_part)
  431. s = lazy_tensor.shape.copy()
  432. s[0] = s[0] // 3
  433. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  434. def pack_experts_lazy(lazy_tensors: list[LazyTensor]) -> LazyTensor:
  435. def load() -> Tensor:
  436. tensors = [lazy_tensor.load() for lazy_tensor in lazy_tensors]
  437. return UnquantizedTensor(np.array([tensor.ndarray for tensor in tensors]))
  438. s = lazy_tensors[0].shape.copy()
  439. s.insert(0, len(lazy_tensors))
  440. return LazyTensor(load, s, lazy_tensors[0].data_type, 'pack_experts ' + ' | '.join(lt.description for lt in lazy_tensors))
  441. # Functionality that simulates `torch.load` but where individual tensors are
  442. # only loaded into memory on demand, not all at once.
  443. # PyTorch can't do this natively as of time of writing:
  444. # - https://github.com/pytorch/pytorch/issues/64327
  445. # This allows us to de-shard without multiplying RAM usage, and also
  446. # conveniently drops the PyTorch dependency (though we still need numpy).
  447. @dataclass
  448. class LazyStorageKind:
  449. data_type: DataType
  450. @dataclass
  451. class LazyStorage:
  452. load: Callable[[int, int], NDArray]
  453. kind: LazyStorageKind
  454. description: str
  455. class LazyUnpickler(pickle.Unpickler):
  456. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  457. super().__init__(fp)
  458. self.data_base_path = data_base_path
  459. self.zip_file = zip_file
  460. def persistent_load(self, pid: Any) -> Any:
  461. assert pid[0] == 'storage'
  462. assert isinstance(pid[1], LazyStorageKind)
  463. data_type = pid[1].data_type
  464. filename_stem = pid[2]
  465. filename = f'{self.data_base_path}/{filename_stem}'
  466. info = self.zip_file.getinfo(filename)
  467. def load(offset: int, elm_count: int) -> NDArray:
  468. dtype = data_type.dtype
  469. with self.zip_file.open(info) as fp:
  470. fp.seek(offset * dtype.itemsize)
  471. size = elm_count * dtype.itemsize
  472. data = fp.read(size)
  473. assert len(data) == size
  474. return np.frombuffer(data, dtype)
  475. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  476. return LazyStorage(load=load, kind=pid[1], description=description)
  477. @staticmethod
  478. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  479. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  480. assert isinstance(storage, LazyStorage)
  481. def load() -> UnquantizedTensor:
  482. elm_count = stride[0] * size[0]
  483. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  484. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  485. return LazyTensor(load, list(size), storage.kind.data_type, description)
  486. @staticmethod
  487. def rebuild_from_type_v2(func, new_type, args, state):
  488. return func(*args)
  489. CLASSES: dict[tuple[str, str], type[LazyTensor] | LazyStorageKind] = {
  490. # getattr used here as a workaround for mypy not being smart enough to determine
  491. # the staticmethods have a __func__ attribute.
  492. ('torch._tensor', '_rebuild_from_type_v2'): getattr(rebuild_from_type_v2, '__func__'),
  493. ('torch._utils', '_rebuild_tensor_v2'): getattr(lazy_rebuild_tensor_v2, '__func__'),
  494. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  495. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  496. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  497. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  498. ('torch', 'Tensor'): LazyTensor,
  499. }
  500. def find_class(self, module: str, name: str) -> Any:
  501. if not module.startswith('torch'):
  502. return super().find_class(module, name)
  503. return self.CLASSES[(module, name)]
  504. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  505. zf = zipfile.ZipFile(outer_fp)
  506. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  507. assert len(pickle_paths) == 1, pickle_paths
  508. pickle_fp = zf.open(pickle_paths[0], 'r')
  509. unpickler = LazyUnpickler(pickle_fp,
  510. data_base_path=pickle_paths[0][:-4],
  511. zip_file=zf)
  512. model = unpickler.load()
  513. if 'model' in model: model = model['model']
  514. as_dict = dict(model.items())
  515. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  516. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  517. header_size, = struct.unpack('<Q', fp.read(8))
  518. header: dict[str, dict[str, Any]] = json.loads(fp.read(header_size))
  519. # Use mmap for the actual data to avoid race conditions with the file offset.
  520. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  521. byte_buf = mapped[8 + header_size:]
  522. def convert(info: dict[str, Any]) -> LazyTensor:
  523. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  524. numpy_dtype = data_type.dtype
  525. shape: list[int] = info['shape']
  526. begin, end = info['data_offsets']
  527. assert 0 <= begin <= end <= len(byte_buf)
  528. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  529. buf = byte_buf[begin:end]
  530. def load() -> UnquantizedTensor:
  531. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  532. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  533. return LazyTensor(load, shape, data_type, description)
  534. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  535. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  536. def must_read(fp: IO[bytes], length: int) -> bytes:
  537. ret = fp.read(length)
  538. if len(ret) < length:
  539. raise EOFError("unexpectedly reached end of file")
  540. return ret
  541. @functools.lru_cache(maxsize=None)
  542. def lazy_load_file(path: Path) -> ModelPlus:
  543. fp = open(path, 'rb')
  544. first8 = fp.read(8)
  545. fp.seek(0)
  546. if first8[:2] == b'PK':
  547. # A zip file, i.e. PyTorch format
  548. return lazy_load_torch_file(fp, path)
  549. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  550. # Probably safetensors
  551. return lazy_load_safetensors_file(fp, path)
  552. else:
  553. raise ValueError(f"unknown format: {path}")
  554. In = TypeVar('In')
  555. Out = TypeVar('Out')
  556. 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]:
  557. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  558. fast enough, this will stop calling `func` at some point rather than
  559. letting results pile up in memory. Specifically, there is a max of one
  560. output value buffered per thread.'''
  561. if concurrency < 2:
  562. yield from map(func, iterable)
  563. # Not reached.
  564. iterable = iter(iterable)
  565. executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor]
  566. if use_processpool_executor:
  567. executor_class = ProcessPoolExecutor
  568. else:
  569. executor_class = ThreadPoolExecutor
  570. with executor_class(max_workers=max_workers) as executor:
  571. futures: list[concurrent.futures.Future[Out]] = []
  572. done = False
  573. for _ in range(concurrency):
  574. try:
  575. futures.append(executor.submit(func, next(iterable)))
  576. except StopIteration:
  577. done = True
  578. break
  579. while futures:
  580. result = futures.pop(0).result()
  581. while not done and len(futures) < concurrency:
  582. try:
  583. futures.append(executor.submit(func, next(iterable)))
  584. except StopIteration:
  585. done = True
  586. break
  587. yield result
  588. def check_vocab_size(params: Params, vocab: BaseVocab, pad_vocab: bool = False) -> None:
  589. # Handle special case where the model's vocab size is not set
  590. if params.n_vocab == -1:
  591. raise ValueError(
  592. "The model's vocab size is set to -1 in params.json. Please update it manually."
  593. + (f" Maybe {vocab.vocab_size}?" if isinstance(vocab, Vocab) else ""),
  594. )
  595. if not isinstance(vocab, Vocab):
  596. return # model has no vocab
  597. # Check for a vocab size mismatch
  598. if params.n_vocab == vocab.vocab_size:
  599. logger.warning("Ignoring added_tokens.json since model matches vocab size without it.")
  600. return
  601. if pad_vocab and params.n_vocab > vocab.vocab_size:
  602. pad_count = params.n_vocab - vocab.vocab_size
  603. logger.debug(
  604. f"Padding vocab with {pad_count} token(s) - <dummy00001> through <dummy{pad_count:05}>"
  605. )
  606. for i in range(1, pad_count + 1):
  607. vocab.added_tokens_dict[f"<dummy{i:05}>"] = -1
  608. vocab.added_tokens_list.append(f"<dummy{i:05}>")
  609. vocab.vocab_size = params.n_vocab
  610. return
  611. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer} has {vocab.vocab_size})."
  612. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20:
  613. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  614. if vocab.vocab_size < params.n_vocab:
  615. msg += " Add the --pad-vocab option and try again."
  616. raise ValueError(msg)
  617. class OutputFile:
  618. def __init__(self, fname_out: Path, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE):
  619. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH], endianess=endianess)
  620. def add_meta_model(self, params: Params, metadata: gguf.Metadata | None) -> None:
  621. # Metadata About The Model And Its Provenence
  622. name = "LLaMA"
  623. if metadata is not None and metadata.name is not None:
  624. name = metadata.name
  625. elif params.path_model is not None:
  626. name = params.path_model.name
  627. elif params.n_ctx == 4096:
  628. # Heuristic detection of LLaMA v2 model
  629. name = "LLaMA v2"
  630. self.gguf.add_name(name)
  631. if metadata is not None:
  632. if metadata.author is not None:
  633. self.gguf.add_author(metadata.author)
  634. if metadata.version is not None:
  635. self.gguf.add_version(metadata.version)
  636. if metadata.organization is not None:
  637. self.gguf.add_organization(metadata.organization)
  638. if metadata.finetune is not None:
  639. self.gguf.add_finetune(metadata.finetune)
  640. if metadata.basename is not None:
  641. self.gguf.add_basename(metadata.basename)
  642. if metadata.description is not None:
  643. self.gguf.add_description(metadata.description)
  644. if metadata.quantized_by is not None:
  645. self.gguf.add_quantized_by(metadata.quantized_by)
  646. if metadata.size_label is not None:
  647. self.gguf.add_size_label(metadata.size_label)
  648. if metadata.license is not None:
  649. self.gguf.add_license(metadata.license)
  650. if metadata.license_name is not None:
  651. self.gguf.add_license_name(metadata.license_name)
  652. if metadata.license_link is not None:
  653. self.gguf.add_license_link(metadata.license_link)
  654. if metadata.url is not None:
  655. self.gguf.add_url(metadata.url)
  656. if metadata.doi is not None:
  657. self.gguf.add_doi(metadata.doi)
  658. if metadata.uuid is not None:
  659. self.gguf.add_uuid(metadata.uuid)
  660. if metadata.repo_url is not None:
  661. self.gguf.add_repo_url(metadata.repo_url)
  662. if metadata.source_url is not None:
  663. self.gguf.add_source_url(metadata.source_url)
  664. if metadata.source_doi is not None:
  665. self.gguf.add_source_doi(metadata.source_doi)
  666. if metadata.source_uuid is not None:
  667. self.gguf.add_source_uuid(metadata.source_uuid)
  668. if metadata.source_repo_url is not None:
  669. self.gguf.add_source_repo_url(metadata.source_repo_url)
  670. if metadata.base_models is not None:
  671. self.gguf.add_base_model_count(len(metadata.base_models))
  672. for key, base_model_entry in enumerate(metadata.base_models):
  673. if "name" in base_model_entry:
  674. self.gguf.add_base_model_name(key, base_model_entry["name"])
  675. if "author" in base_model_entry:
  676. self.gguf.add_base_model_author(key, base_model_entry["author"])
  677. if "version" in base_model_entry:
  678. self.gguf.add_base_model_version(key, base_model_entry["version"])
  679. if "organization" in base_model_entry:
  680. self.gguf.add_base_model_organization(key, base_model_entry["organization"])
  681. if "description" in base_model_entry:
  682. self.gguf.add_base_model_description(key, base_model_entry["description"])
  683. if "url" in base_model_entry:
  684. self.gguf.add_base_model_url(key, base_model_entry["url"])
  685. if "doi" in base_model_entry:
  686. self.gguf.add_base_model_doi(key, base_model_entry["doi"])
  687. if "uuid" in base_model_entry:
  688. self.gguf.add_base_model_uuid(key, base_model_entry["uuid"])
  689. if "repo_url" in base_model_entry:
  690. self.gguf.add_base_model_repo_url(key, base_model_entry["repo_url"])
  691. if metadata.datasets is not None:
  692. self.gguf.add_dataset_count(len(metadata.datasets))
  693. for key, dataset_entry in enumerate(metadata.datasets):
  694. if "name" in dataset_entry:
  695. self.gguf.add_dataset_name(key, dataset_entry["name"])
  696. if "author" in dataset_entry:
  697. self.gguf.add_dataset_author(key, dataset_entry["author"])
  698. if "version" in dataset_entry:
  699. self.gguf.add_dataset_version(key, dataset_entry["version"])
  700. if "organization" in dataset_entry:
  701. self.gguf.add_dataset_organization(key, dataset_entry["organization"])
  702. if "description" in dataset_entry:
  703. self.gguf.add_dataset_description(key, dataset_entry["description"])
  704. if "url" in dataset_entry:
  705. self.gguf.add_dataset_url(key, dataset_entry["url"])
  706. if "doi" in dataset_entry:
  707. self.gguf.add_dataset_doi(key, dataset_entry["doi"])
  708. if "uuid" in dataset_entry:
  709. self.gguf.add_dataset_uuid(key, dataset_entry["uuid"])
  710. if "repo_url" in dataset_entry:
  711. self.gguf.add_dataset_repo_url(key, dataset_entry["repo_url"])
  712. if metadata.tags is not None:
  713. self.gguf.add_tags(metadata.tags)
  714. if metadata.languages is not None:
  715. self.gguf.add_languages(metadata.languages)
  716. def add_meta_arch(self, params: Params) -> None:
  717. # Metadata About The Neural Architecture Itself
  718. self.gguf.add_vocab_size(params.n_vocab)
  719. self.gguf.add_context_length(params.n_ctx)
  720. self.gguf.add_embedding_length(params.n_embd)
  721. self.gguf.add_block_count(params.n_layer)
  722. self.gguf.add_feed_forward_length(params.n_ff)
  723. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  724. self.gguf.add_head_count (params.n_head)
  725. self.gguf.add_head_count_kv (params.n_head_kv)
  726. if params.n_experts:
  727. self.gguf.add_expert_count(params.n_experts)
  728. if params.n_experts_used:
  729. self.gguf.add_expert_used_count(params.n_experts_used)
  730. if params.f_norm_eps:
  731. self.gguf.add_layer_norm_rms_eps(params.f_norm_eps)
  732. else:
  733. raise ValueError('f_norm_eps is None')
  734. if params.f_rope_freq_base is not None:
  735. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  736. if params.rope_scaling_type:
  737. assert params.f_rope_scale is not None
  738. self.gguf.add_rope_scaling_type(params.rope_scaling_type)
  739. self.gguf.add_rope_scaling_factor(params.f_rope_scale)
  740. if params.n_ctx_orig is not None:
  741. self.gguf.add_rope_scaling_orig_ctx_len(params.n_ctx_orig)
  742. if params.rope_finetuned is not None:
  743. self.gguf.add_rope_scaling_finetuned(params.rope_finetuned)
  744. if params.ftype is not None:
  745. self.gguf.add_file_type(params.ftype)
  746. def extract_vocabulary_from_model(self, vocab: Vocab) -> tuple[list[bytes], list[float], list[gguf.TokenType]]:
  747. tokens = []
  748. scores = []
  749. toktypes = []
  750. # NOTE: `all_tokens` returns the base vocabulary and added tokens
  751. for text, score, toktype in vocab.all_tokens():
  752. tokens.append(text)
  753. scores.append(score)
  754. toktypes.append(toktype)
  755. assert len(tokens) == vocab.vocab_size
  756. return tokens, scores, toktypes
  757. def add_meta_vocab(self, vocab: Vocab) -> None:
  758. # Ensure that tokenizer_model is added to the GGUF model
  759. self.gguf.add_tokenizer_model(vocab.tokenizer_model)
  760. # Extract model vocabulary for model conversion
  761. tokens, scores, toktypes = self.extract_vocabulary_from_model(vocab)
  762. # Add extracted token information for model conversion
  763. self.gguf.add_token_list(tokens)
  764. self.gguf.add_token_scores(scores)
  765. self.gguf.add_token_types(toktypes)
  766. def add_meta_special_vocab(self, svocab: gguf.SpecialVocab) -> None:
  767. svocab.add_to_gguf(self.gguf)
  768. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  769. n_elements = int(np.prod(tensor.shape))
  770. raw_dtype = getattr(tensor.data_type, 'ggml_type', None)
  771. data_type = getattr(tensor.data_type, 'quantized_type', None) or tensor.data_type.dtype
  772. data_nbytes = tensor.data_type.elements_to_bytes(n_elements)
  773. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes, raw_dtype=raw_dtype)
  774. def write_meta(self) -> None:
  775. self.gguf.write_header_to_file()
  776. self.gguf.write_kv_data_to_file()
  777. def write_tensor_info(self) -> None:
  778. self.gguf.write_ti_data_to_file()
  779. def write_tensor_data(self, ftype: GGMLFileType, model: LazyModel, concurrency: int) -> None:
  780. ndarrays_inner = bounded_parallel_map(OutputFile.do_item, model.items(), concurrency=concurrency)
  781. if ftype == GGMLFileType.MostlyQ8_0:
  782. ndarrays = bounded_parallel_map(
  783. OutputFile.maybe_do_quantize, ndarrays_inner, concurrency=concurrency, max_workers=concurrency,
  784. use_processpool_executor=True,
  785. )
  786. else:
  787. ndarrays = map(OutputFile.maybe_do_quantize, ndarrays_inner)
  788. start = time.time()
  789. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  790. elapsed = time.time() - start
  791. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  792. padi = len(str(len(model)))
  793. logger.info(
  794. 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}"
  795. )
  796. self.gguf.write_tensor_data(ndarray)
  797. def close(self) -> None:
  798. self.gguf.close()
  799. @staticmethod
  800. def write_vocab_only(
  801. fname_out: Path, params: Params, vocab: Vocab, svocab: gguf.SpecialVocab,
  802. endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE, pad_vocab: bool = False, metadata: gguf.Metadata | None = None,
  803. ) -> None:
  804. check_vocab_size(params, vocab, pad_vocab=pad_vocab)
  805. of = OutputFile(fname_out, endianess=endianess)
  806. # meta data
  807. of.add_meta_model(params, metadata)
  808. of.add_meta_arch(params)
  809. of.add_meta_vocab(vocab)
  810. of.add_meta_special_vocab(svocab)
  811. of.write_meta()
  812. of.close()
  813. @staticmethod
  814. def do_item(item: tuple[str, LazyTensor]) -> tuple[DataType, NDArray]:
  815. name, lazy_tensor = item
  816. tensor = lazy_tensor.load().to_ggml()
  817. return (lazy_tensor.data_type, tensor.ndarray)
  818. @staticmethod
  819. def maybe_do_quantize(item: tuple[DataType, NDArray]) -> NDArray:
  820. dt, arr = item
  821. if not isinstance(dt, QuantizedDataType):
  822. return arr
  823. return dt.quantize(arr)
  824. @staticmethod
  825. def write_all(
  826. fname_out: Path, ftype: GGMLFileType, params: Params, model: LazyModel, vocab: BaseVocab, svocab: gguf.SpecialVocab,
  827. concurrency: int = DEFAULT_CONCURRENCY, endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE,
  828. pad_vocab: bool = False,
  829. metadata: gguf.Metadata | None = None,
  830. ) -> None:
  831. check_vocab_size(params, vocab, pad_vocab=pad_vocab)
  832. of = OutputFile(fname_out, endianess=endianess)
  833. # meta data
  834. of.add_meta_model(params, metadata)
  835. of.add_meta_arch(params)
  836. if isinstance(vocab, Vocab):
  837. of.add_meta_vocab(vocab)
  838. of.add_meta_special_vocab(svocab)
  839. else: # NoVocab
  840. of.gguf.add_tokenizer_model(vocab.tokenizer_model)
  841. # tensor info
  842. for name, lazy_tensor in model.items():
  843. of.add_tensor_info(name, lazy_tensor)
  844. of.write_meta()
  845. of.write_tensor_info()
  846. # tensor data
  847. of.write_tensor_data(ftype, model, concurrency)
  848. of.close()
  849. def pick_output_type(model: LazyModel, output_type_str: str | None) -> GGMLFileType:
  850. wq_type = model[gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0) + ".weight"].data_type
  851. if output_type_str == "f32" or (output_type_str is None and wq_type in (DT_F32, DT_BF16)):
  852. return GGMLFileType.AllF32
  853. if output_type_str == "f16" or (output_type_str is None and wq_type == DT_F16):
  854. return GGMLFileType.MostlyF16
  855. if output_type_str == "q8_0":
  856. return GGMLFileType.MostlyQ8_0
  857. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  858. raise ValueError(f"Unexpected combination of types: {name_to_type}")
  859. def per_model_weight_count_estimation(tensors: Iterable[tuple[str, LazyTensor]]) -> tuple[int, int, int]:
  860. total_params = 0
  861. shared_params = 0
  862. expert_params = 0
  863. for name, lazy_tensor in tensors:
  864. # We don't need these
  865. if name.endswith((".attention.masked_bias", ".attention.bias", ".rotary_emb.inv_freq")):
  866. continue
  867. # Got A Tensor
  868. sum_weights_in_tensor: int = 1
  869. # Tensor Volume
  870. for dim in lazy_tensor.shape:
  871. sum_weights_in_tensor *= dim
  872. if ".experts." in name:
  873. if ".experts.0." in name:
  874. expert_params += sum_weights_in_tensor
  875. else:
  876. shared_params += sum_weights_in_tensor
  877. total_params += sum_weights_in_tensor
  878. return total_params, shared_params, expert_params
  879. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  880. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  881. for (name, tensor) in model.items()}
  882. def convert_model_names(model: LazyModel, params: Params, skip_unknown: bool) -> LazyModel:
  883. tmap = gguf.TensorNameMap(ARCH, params.n_layer)
  884. should_skip = set(gguf.MODEL_TENSOR_SKIP.get(ARCH, []))
  885. tmp = model
  886. # merge experts into one tensor
  887. if params.n_experts and params.n_experts > 0:
  888. for i_l in range(params.n_layer):
  889. for w in range(1, 4):
  890. experts = []
  891. for e in range(params.n_experts):
  892. if f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight" in model:
  893. experts.append(model[f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight"])
  894. del tmp[f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight"]
  895. elif f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight" in model:
  896. experts.append(model[f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight"])
  897. del tmp[f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight"]
  898. else:
  899. raise ValueError(f"Expert tensor not found: layers.{i_l}.feed_forward.experts.{e}.w{w}.weight")
  900. tmp[f"layers.{i_l}.feed_forward.experts.w{w}.weight"] = pack_experts_lazy(experts)
  901. # HF models permut or pack some of the tensors, so we need to undo that
  902. for i in itertools.count():
  903. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  904. logger.debug(f"Permuting layer {i}")
  905. 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)
  906. 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)
  907. # tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  908. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  909. logger.debug(f"Unpacking and permuting layer {i}")
  910. 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)
  911. 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)
  912. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  913. del tmp[f"model.layers.{i}.self_attn.W_pack.weight"]
  914. else:
  915. break
  916. out: LazyModel = {}
  917. for name, lazy_tensor in model.items():
  918. tensor_type, name_new = tmap.get_type_and_name(name, try_suffixes = (".weight", ".bias")) or (None, None)
  919. if name_new is None:
  920. if skip_unknown:
  921. logger.warning(f"Unexpected tensor name: {name} - skipping")
  922. continue
  923. raise ValueError(f"Unexpected tensor name: {name}. Use --skip-unknown to ignore it (e.g. LLaVA)")
  924. if tensor_type in should_skip:
  925. logger.debug(f"skipping tensor {name_new}")
  926. continue
  927. logger.debug(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type.name:6s} | {lazy_tensor.shape}")
  928. out[name_new] = lazy_tensor
  929. return out
  930. def nth_multifile_path(path: Path, n: int) -> Path | None:
  931. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  932. the nth path in the model.
  933. '''
  934. # Support the following patterns:
  935. patterns = [
  936. # - x.00.pth, x.01.pth, etc.
  937. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  938. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  939. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  940. # x.bin, x.bin.1, etc.
  941. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  942. ]
  943. for regex, replacement in patterns:
  944. if re.search(regex, path.name):
  945. new_path = path.with_name(re.sub(regex, replacement, path.name))
  946. if new_path.exists():
  947. return new_path
  948. return None
  949. def find_multifile_paths(path: Path) -> list[Path]:
  950. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  951. the whole list of paths in the model.
  952. '''
  953. ret: list[Path] = []
  954. for i in itertools.count():
  955. nth_path = nth_multifile_path(path, i)
  956. if nth_path is None:
  957. break
  958. ret.append(nth_path)
  959. if not ret:
  960. # No matches. This should only happen if the file was named, e.g.,
  961. # foo.0, and there was no file named foo. Oh well, try to process it
  962. # as a single file.
  963. return [path]
  964. return ret
  965. def load_some_model(path: Path) -> ModelPlus:
  966. '''Load a model of any supported format.'''
  967. # Be extra-friendly and accept either a file or a directory:
  968. if path.is_dir():
  969. # Check if it's a set of safetensors files first
  970. globs = ["model-00001-of-*.safetensors", "model.safetensors", "consolidated.safetensors"]
  971. files = [file for glob in globs for file in path.glob(glob)]
  972. if not files:
  973. # Try the PyTorch patterns too, with lower priority
  974. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  975. files = [file for glob in globs for file in path.glob(glob)]
  976. if not files:
  977. raise FileNotFoundError(f"Can't find model in directory {path}")
  978. if len(files) > 1:
  979. raise ValueError(f"Found multiple models in {path}, not sure which to pick: {files}")
  980. path = files[0]
  981. paths = find_multifile_paths(path)
  982. models_plus: list[ModelPlus] = []
  983. for path in paths:
  984. logger.info(f"Loading model file {path}")
  985. models_plus.append(lazy_load_file(path))
  986. model_plus = merge_multifile_models(models_plus)
  987. return model_plus
  988. class VocabFactory:
  989. _VOCAB_CLASSES: list[type[Vocab]] = [SentencePieceVocab, BpeVocab, LlamaHfVocab]
  990. def __init__(self, path: Path):
  991. self.path = path
  992. def _create_special_vocab(self, vocab: BaseVocab, model_parent_path: Path) -> gguf.SpecialVocab:
  993. load_merges = vocab.name == "bpe"
  994. n_vocab = vocab.vocab_size if isinstance(vocab, Vocab) else None
  995. return gguf.SpecialVocab(
  996. model_parent_path,
  997. load_merges=load_merges,
  998. special_token_types=None, # Predetermined or passed as a parameter
  999. n_vocab=n_vocab,
  1000. )
  1001. def _create_vocab_by_path(self, vocab_types: list[str]) -> Vocab:
  1002. vocab_classes: dict[str, type[Vocab]] = {cls.name: cls for cls in self._VOCAB_CLASSES}
  1003. selected_vocabs: dict[str, type[Vocab]] = {}
  1004. for vtype in vocab_types:
  1005. try:
  1006. selected_vocabs[vtype] = vocab_classes[vtype]
  1007. except KeyError:
  1008. raise ValueError(f"Unsupported vocabulary type {vtype}") from None
  1009. for vtype, cls in selected_vocabs.items():
  1010. try:
  1011. vocab = cls(self.path)
  1012. break
  1013. except FileNotFoundError:
  1014. pass # ignore unavailable tokenizers
  1015. else:
  1016. raise FileNotFoundError(f"Could not find a tokenizer matching any of {vocab_types}")
  1017. logger.info(f"Loaded vocab file {vocab.fname_tokenizer!r}, type {vocab.name!r}")
  1018. return vocab
  1019. def load_vocab(self, vocab_types: list[str] | None, model_parent_path: Path) -> tuple[BaseVocab, gguf.SpecialVocab]:
  1020. vocab: BaseVocab
  1021. if vocab_types is None:
  1022. vocab = NoVocab()
  1023. else:
  1024. vocab = self._create_vocab_by_path(vocab_types)
  1025. # FIXME: Respect --vocab-dir?
  1026. special_vocab = self._create_special_vocab(
  1027. vocab,
  1028. model_parent_path,
  1029. )
  1030. return vocab, special_vocab
  1031. def default_convention_outfile(file_type: GGMLFileType, expert_count: int | None, model_params_count: tuple[int, int, int], metadata: gguf.Metadata) -> str:
  1032. name = metadata.name if metadata.name is not None else None
  1033. basename = metadata.basename if metadata.basename is not None else None
  1034. finetune = metadata.finetune if metadata.finetune is not None else None
  1035. version = metadata.version if metadata.version is not None else None
  1036. size_label = metadata.size_label if metadata.size_label is not None else gguf.size_label(*model_params_count, expert_count=expert_count or 0)
  1037. output_type = {
  1038. GGMLFileType.AllF32: "F32",
  1039. GGMLFileType.MostlyF16: "F16",
  1040. GGMLFileType.MostlyQ8_0: "Q8_0",
  1041. }[file_type]
  1042. return gguf.naming_convention(name, basename, finetune, version, size_label, output_type)
  1043. def default_outfile(model_paths: list[Path], file_type: GGMLFileType, expert_count: int | None, model_params_count: tuple[int, int, int], metadata: gguf.Metadata) -> Path:
  1044. default_filename = default_convention_outfile(file_type, expert_count, model_params_count, metadata)
  1045. ret = model_paths[0].parent / f"{default_filename}.gguf"
  1046. if ret in model_paths:
  1047. logger.error(
  1048. f"Error: Default output path ({ret}) would overwrite the input. "
  1049. "Please explicitly specify a path using --outfile.")
  1050. sys.exit(1)
  1051. return ret
  1052. def do_dump_model(model_plus: ModelPlus) -> None:
  1053. print(f"model_plus.paths = {model_plus.paths!r}") # noqa: NP100
  1054. print(f"model_plus.format = {model_plus.format!r}") # noqa: NP100
  1055. print(f"model_plus.vocab = {model_plus.vocab!r}") # noqa: NP100
  1056. for name, lazy_tensor in model_plus.model.items():
  1057. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}") # noqa: NP100
  1058. def main(args_in: list[str] | None = None) -> None:
  1059. output_choices = ["f32", "f16"]
  1060. if np.uint32(1) == np.uint32(1).newbyteorder("<"):
  1061. # We currently only support Q8_0 output on little endian systems.
  1062. output_choices.append("q8_0")
  1063. parser = argparse.ArgumentParser(description="Convert a LLaMA model to a GGML compatible file")
  1064. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  1065. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  1066. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  1067. parser.add_argument("--no-vocab", action="store_true", help="store model without the vocab")
  1068. parser.add_argument("--outtype", choices=output_choices, help="output format - note: q8_0 may be very slow (default: f16 or f32 based on input)")
  1069. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  1070. parser.add_argument("--vocab-type", help="vocab types to try in order, choose from 'spm', 'bpe', 'hfft' (default: spm,hfft)", default="spm,hfft")
  1071. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  1072. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
  1073. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  1074. parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default=DEFAULT_CONCURRENCY)
  1075. parser.add_argument("--big-endian", action="store_true", help="model is executed on big endian machine")
  1076. parser.add_argument("--pad-vocab", action="store_true", help="add pad tokens when model vocab expects more than tokenizer metadata provides")
  1077. parser.add_argument("--skip-unknown", action="store_true", help="skip unknown tensor names instead of failing")
  1078. parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
  1079. parser.add_argument("--metadata", type=Path, help="Specify the path for an authorship metadata override file")
  1080. parser.add_argument("--get-outfile", action="store_true", help="get calculated default outfile name")
  1081. parser.add_argument("--model-name", type=str, default=None, help="name of the model")
  1082. args = parser.parse_args(args_in)
  1083. if args.verbose:
  1084. logging.basicConfig(level=logging.DEBUG)
  1085. elif args.dump_single or args.dump or args.get_outfile:
  1086. # Avoid printing anything besides the dump output
  1087. logging.basicConfig(level=logging.WARNING)
  1088. else:
  1089. logging.basicConfig(level=logging.INFO)
  1090. model_name = args.model_name
  1091. dir_model = args.model
  1092. metadata = gguf.Metadata.load(args.metadata, dir_model, model_name)
  1093. if args.get_outfile:
  1094. model_plus = load_some_model(dir_model)
  1095. params = Params.load(model_plus)
  1096. model = convert_model_names(model_plus.model, params, args.skip_unknown)
  1097. model_params_count = per_model_weight_count_estimation(model_plus.model.items())
  1098. ftype = pick_output_type(model, args.outtype)
  1099. if (metadata is None or metadata.name is None) and params.path_model is not None:
  1100. metadata.name = params.path_model.name
  1101. print(f"{default_convention_outfile(ftype, params.n_experts, model_params_count, metadata)}") # noqa: NP100
  1102. return
  1103. if args.no_vocab and args.vocab_only:
  1104. raise ValueError("--vocab-only does not make sense with --no-vocab")
  1105. if args.dump_single:
  1106. model_plus = lazy_load_file(dir_model)
  1107. do_dump_model(model_plus)
  1108. return
  1109. if not args.vocab_only:
  1110. model_plus = load_some_model(dir_model)
  1111. else:
  1112. model_plus = ModelPlus(model = {}, paths = [dir_model / 'dummy'], format = 'none', vocab = None)
  1113. if args.dump:
  1114. do_dump_model(model_plus)
  1115. return
  1116. endianess = gguf.GGUFEndian.LITTLE
  1117. if args.big_endian:
  1118. endianess = gguf.GGUFEndian.BIG
  1119. params = None
  1120. if args.pad_vocab or not args.vocab_only:
  1121. params = Params.load(model_plus)
  1122. if params.n_ctx == -1:
  1123. if args.ctx is None:
  1124. msg = """\
  1125. The model doesn't have a context size, and you didn't specify one with --ctx
  1126. Please specify one with --ctx:
  1127. - LLaMA v1: --ctx 2048
  1128. - LLaMA v2: --ctx 4096"""
  1129. parser.error(textwrap.dedent(msg))
  1130. params.n_ctx = args.ctx
  1131. if args.outtype:
  1132. params.ftype = {
  1133. "f32": GGMLFileType.AllF32,
  1134. "f16": GGMLFileType.MostlyF16,
  1135. "q8_0": GGMLFileType.MostlyQ8_0,
  1136. }[args.outtype]
  1137. logger.info(f"params = {params}")
  1138. model_parent_path = model_plus.paths[0].parent
  1139. vocab_path = Path(args.vocab_dir or dir_model or model_parent_path)
  1140. vocab_factory = VocabFactory(vocab_path)
  1141. vocab_types = None if args.no_vocab else args.vocab_type.split(",")
  1142. vocab, special_vocab = vocab_factory.load_vocab(vocab_types, model_parent_path)
  1143. if args.vocab_only:
  1144. assert isinstance(vocab, Vocab)
  1145. if not args.outfile:
  1146. raise ValueError("need --outfile if using --vocab-only")
  1147. outfile = args.outfile
  1148. if params is None:
  1149. params = Params(
  1150. n_vocab = vocab.vocab_size,
  1151. n_embd = 1,
  1152. n_layer = 1,
  1153. n_ctx = 1,
  1154. n_ff = 1,
  1155. n_head = 1,
  1156. n_head_kv = 1,
  1157. f_norm_eps = 1e-5,
  1158. )
  1159. OutputFile.write_vocab_only(outfile, params, vocab, special_vocab,
  1160. endianess=endianess, pad_vocab=args.pad_vocab, metadata=metadata)
  1161. logger.info(f"Wrote {outfile}")
  1162. return
  1163. if model_plus.vocab is not None and args.vocab_dir is None and not args.no_vocab:
  1164. vocab = model_plus.vocab
  1165. assert params is not None
  1166. if metadata.name is None and params.path_model is not None:
  1167. metadata.name = params.path_model.name
  1168. model_params_count = per_model_weight_count_estimation(model_plus.model.items())
  1169. logger.info(f"model parameters count : {model_params_count} ({gguf.model_weight_count_rounded_notation(model_params_count[0])})")
  1170. logger.info(f"Vocab info: {vocab}")
  1171. logger.info(f"Special vocab info: {special_vocab}")
  1172. model = model_plus.model
  1173. model = convert_model_names(model, params, args.skip_unknown)
  1174. ftype = pick_output_type(model, args.outtype)
  1175. model = convert_to_output_type(model, ftype)
  1176. outfile = args.outfile or default_outfile(model_plus.paths, ftype, params.n_experts, model_params_count, metadata=metadata)
  1177. metadata.size_label = gguf.size_label(*model_params_count, expert_count=params.n_experts or 0)
  1178. params.ftype = ftype
  1179. logger.info(f"Writing {outfile}, format {ftype}")
  1180. OutputFile.write_all(outfile, ftype, params, model, vocab, special_vocab,
  1181. concurrency=args.concurrency, endianess=endianess, pad_vocab=args.pad_vocab, metadata=metadata)
  1182. logger.info(f"Wrote {outfile}")
  1183. if __name__ == '__main__':
  1184. main()