gguf_writer.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import shutil
  5. import struct
  6. import tempfile
  7. from dataclasses import dataclass
  8. from enum import Enum, auto
  9. from math import prod
  10. from pathlib import Path
  11. from io import BufferedWriter
  12. from typing import IO, Any, Sequence, Mapping
  13. from string import ascii_letters, digits
  14. import numpy as np
  15. from .constants import (
  16. GGUF_DEFAULT_ALIGNMENT,
  17. GGUF_MAGIC,
  18. GGUF_VERSION,
  19. GGMLQuantizationType,
  20. GGUFEndian,
  21. GGUFValueType,
  22. Keys,
  23. RopeScalingType,
  24. PoolingType,
  25. TokenType,
  26. ExpertGatingFuncType,
  27. )
  28. from .quants import quant_shape_from_byte_shape
  29. logger = logging.getLogger(__name__)
  30. SHARD_NAME_FORMAT = "{:s}-{:05d}-of-{:05d}.gguf"
  31. @dataclass
  32. class TensorInfo:
  33. shape: Sequence[int]
  34. dtype: GGMLQuantizationType
  35. nbytes: int
  36. tensor: np.ndarray[Any, Any] | None = None
  37. @dataclass
  38. class GGUFValue:
  39. value: Any
  40. type: GGUFValueType
  41. class WriterState(Enum):
  42. NO_FILE = auto()
  43. EMPTY = auto()
  44. HEADER = auto()
  45. KV_DATA = auto()
  46. TI_DATA = auto()
  47. WEIGHTS = auto()
  48. class GGUFWriter:
  49. fout: list[BufferedWriter] | None
  50. path: Path | None
  51. temp_file: tempfile.SpooledTemporaryFile[bytes] | None
  52. tensors: list[dict[str, TensorInfo]]
  53. kv_data: list[dict[str, GGUFValue]]
  54. state: WriterState
  55. _simple_value_packing = {
  56. GGUFValueType.UINT8: "B",
  57. GGUFValueType.INT8: "b",
  58. GGUFValueType.UINT16: "H",
  59. GGUFValueType.INT16: "h",
  60. GGUFValueType.UINT32: "I",
  61. GGUFValueType.INT32: "i",
  62. GGUFValueType.FLOAT32: "f",
  63. GGUFValueType.UINT64: "Q",
  64. GGUFValueType.INT64: "q",
  65. GGUFValueType.FLOAT64: "d",
  66. GGUFValueType.BOOL: "?",
  67. }
  68. def __init__(
  69. self, path: os.PathLike[str] | str | None, arch: str, use_temp_file: bool = False, endianess: GGUFEndian = GGUFEndian.LITTLE,
  70. split_max_tensors: int = 0, split_max_size: int = 0, dry_run: bool = False, small_first_shard: bool = False
  71. ):
  72. self.fout = None
  73. self.path = Path(path) if path else None
  74. self.arch = arch
  75. self.endianess = endianess
  76. self.data_alignment = GGUF_DEFAULT_ALIGNMENT
  77. self.use_temp_file = use_temp_file
  78. self.temp_file = None
  79. self.tensors = [{}]
  80. self.kv_data = [{}]
  81. self.split_max_tensors = split_max_tensors
  82. self.split_max_size = split_max_size
  83. self.dry_run = dry_run
  84. self.small_first_shard = small_first_shard
  85. logger.info("gguf: This GGUF file is for {0} Endian only".format(
  86. "Big" if self.endianess == GGUFEndian.BIG else "Little",
  87. ))
  88. self.state = WriterState.NO_FILE
  89. if self.small_first_shard:
  90. self.tensors.append({})
  91. self.add_architecture()
  92. def get_total_parameter_count(self) -> tuple[int, int, int, int]:
  93. total_params = 0
  94. shared_params = 0
  95. expert_params = 0
  96. expert_sum = 0
  97. n_expert_tensors = 0
  98. last_lora_a: tuple[str, TensorInfo] | None = None
  99. for tensors in self.tensors:
  100. for name, info in tensors.items():
  101. shape = info.shape
  102. if name.endswith(".lora_a"):
  103. last_lora_a = (name, info)
  104. continue
  105. elif name.endswith(".lora_b"):
  106. if last_lora_a is None or last_lora_a[0] != name[:-1] + "a":
  107. # Bail when the LoRA pair can't be found trivially
  108. logger.warning("can't measure LoRA size correctly, tensor order is unusual")
  109. return 0, 0, 0, 0
  110. else:
  111. shape = (*shape[:-1], last_lora_a[1].shape[-1])
  112. size = prod(shape)
  113. if "_exps." in name:
  114. expert_params += (size // shape[-3])
  115. expert_sum += shape[-3]
  116. n_expert_tensors += 1
  117. else:
  118. shared_params += size
  119. total_params += size
  120. # Hopefully this should work even for variable-expert-count models
  121. expert_count = (expert_sum // n_expert_tensors) if n_expert_tensors > 0 else 0
  122. # Negate the total to signal it's likely not exact
  123. if last_lora_a is not None:
  124. total_params = -total_params
  125. # NOTE: keep the output in the same order as accepted by 'size_label' in gguf-py/gguf/utility.py
  126. return total_params, shared_params, expert_params, expert_count
  127. def format_shard_names(self, path: Path) -> list[Path]:
  128. if len(self.tensors) == 1:
  129. return [path]
  130. return [path.with_name(SHARD_NAME_FORMAT.format(path.stem, i + 1, len(self.tensors))) for i in range(len(self.tensors))]
  131. def open_output_file(self, path: Path | None = None) -> None:
  132. if self.state is WriterState.EMPTY and self.fout is not None and (path is None or path == self.path):
  133. # allow calling this multiple times as long as the path is the same
  134. return
  135. if self.state is not WriterState.NO_FILE:
  136. raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
  137. if path is not None:
  138. self.path = path
  139. if self.path is not None:
  140. filenames = self.print_plan()
  141. self.fout = [open(filename, "wb") for filename in filenames]
  142. self.state = WriterState.EMPTY
  143. def print_plan(self) -> list[Path]:
  144. logger.info("Writing the following files:")
  145. assert self.path is not None
  146. filenames = self.format_shard_names(self.path)
  147. assert len(filenames) == len(self.tensors)
  148. for name, tensors in zip(filenames, self.tensors):
  149. logger.info(f"{name}: n_tensors = {len(tensors)}, total_size = {GGUFWriter.format_n_bytes_to_str(sum(ti.nbytes for ti in tensors.values()))}")
  150. if self.dry_run:
  151. logger.info("Dry run, not writing files")
  152. for name in filenames:
  153. print(name) # noqa: NP100
  154. exit()
  155. return filenames
  156. def add_shard_kv_data(self) -> None:
  157. if len(self.tensors) == 1:
  158. return
  159. total_tensors = sum(len(t) for t in self.tensors)
  160. assert self.fout is not None
  161. total_splits = len(self.fout)
  162. self.kv_data.extend({} for _ in range(len(self.kv_data), total_splits))
  163. for i, kv_data in enumerate(self.kv_data):
  164. kv_data[Keys.Split.LLM_KV_SPLIT_NO] = GGUFValue(i, GGUFValueType.UINT16)
  165. kv_data[Keys.Split.LLM_KV_SPLIT_COUNT] = GGUFValue(total_splits, GGUFValueType.UINT16)
  166. kv_data[Keys.Split.LLM_KV_SPLIT_TENSORS_COUNT] = GGUFValue(total_tensors, GGUFValueType.INT32)
  167. def write_header_to_file(self, path: Path | None = None) -> None:
  168. if len(self.tensors) == 1 and (self.split_max_tensors != 0 or self.split_max_size != 0):
  169. logger.warning("Model fails split requirements, not splitting")
  170. self.open_output_file(path)
  171. if self.state is not WriterState.EMPTY:
  172. raise ValueError(f'Expected output file to be empty, got {self.state}')
  173. assert self.fout is not None
  174. assert len(self.fout) == len(self.tensors)
  175. assert len(self.kv_data) == 1
  176. self.add_shard_kv_data()
  177. for fout, tensors, kv_data in zip(self.fout, self.tensors, self.kv_data):
  178. fout.write(self._pack("<I", GGUF_MAGIC, skip_pack_prefix = True))
  179. fout.write(self._pack("I", GGUF_VERSION))
  180. fout.write(self._pack("Q", len(tensors)))
  181. fout.write(self._pack("Q", len(kv_data)))
  182. fout.flush()
  183. self.state = WriterState.HEADER
  184. def write_kv_data_to_file(self) -> None:
  185. if self.state is not WriterState.HEADER:
  186. raise ValueError(f'Expected output file to contain the header, got {self.state}')
  187. assert self.fout is not None
  188. for fout, kv_data in zip(self.fout, self.kv_data):
  189. kv_bytes = bytearray()
  190. for key, val in kv_data.items():
  191. kv_bytes += self._pack_val(key, GGUFValueType.STRING, add_vtype=False)
  192. kv_bytes += self._pack_val(val.value, val.type, add_vtype=True)
  193. fout.write(kv_bytes)
  194. self.flush()
  195. self.state = WriterState.KV_DATA
  196. def write_ti_data_to_file(self) -> None:
  197. if self.state is not WriterState.KV_DATA:
  198. raise ValueError(f'Expected output file to contain KV data, got {self.state}')
  199. assert self.fout is not None
  200. for fout, tensors in zip(self.fout, self.tensors):
  201. ti_data = bytearray()
  202. offset_tensor = 0
  203. for name, ti in tensors.items():
  204. ti_data += self._pack_val(name, GGUFValueType.STRING, add_vtype=False)
  205. n_dims = len(ti.shape)
  206. ti_data += self._pack("I", n_dims)
  207. for j in range(n_dims):
  208. ti_data += self._pack("Q", ti.shape[n_dims - 1 - j])
  209. ti_data += self._pack("I", ti.dtype)
  210. ti_data += self._pack("Q", offset_tensor)
  211. offset_tensor += GGUFWriter.ggml_pad(ti.nbytes, self.data_alignment)
  212. fout.write(ti_data)
  213. fout.flush()
  214. self.state = WriterState.TI_DATA
  215. def add_key_value(self, key: str, val: Any, vtype: GGUFValueType) -> None:
  216. if any(key in kv_data for kv_data in self.kv_data):
  217. raise ValueError(f'Duplicated key name {key!r}')
  218. self.kv_data[0][key] = GGUFValue(value=val, type=vtype)
  219. def add_uint8(self, key: str, val: int) -> None:
  220. self.add_key_value(key,val, GGUFValueType.UINT8)
  221. def add_int8(self, key: str, val: int) -> None:
  222. self.add_key_value(key, val, GGUFValueType.INT8)
  223. def add_uint16(self, key: str, val: int) -> None:
  224. self.add_key_value(key, val, GGUFValueType.UINT16)
  225. def add_int16(self, key: str, val: int) -> None:
  226. self.add_key_value(key, val, GGUFValueType.INT16)
  227. def add_uint32(self, key: str, val: int) -> None:
  228. self.add_key_value(key, val, GGUFValueType.UINT32)
  229. def add_int32(self, key: str, val: int) -> None:
  230. self.add_key_value(key, val, GGUFValueType.INT32)
  231. def add_float32(self, key: str, val: float) -> None:
  232. self.add_key_value(key, val, GGUFValueType.FLOAT32)
  233. def add_uint64(self, key: str, val: int) -> None:
  234. self.add_key_value(key, val, GGUFValueType.UINT64)
  235. def add_int64(self, key: str, val: int) -> None:
  236. self.add_key_value(key, val, GGUFValueType.INT64)
  237. def add_float64(self, key: str, val: float) -> None:
  238. self.add_key_value(key, val, GGUFValueType.FLOAT64)
  239. def add_bool(self, key: str, val: bool) -> None:
  240. self.add_key_value(key, val, GGUFValueType.BOOL)
  241. def add_string(self, key: str, val: str) -> None:
  242. if not val:
  243. return
  244. self.add_key_value(key, val, GGUFValueType.STRING)
  245. def add_array(self, key: str, val: Sequence[Any]) -> None:
  246. if len(val) == 0:
  247. return
  248. self.add_key_value(key, val, GGUFValueType.ARRAY)
  249. @staticmethod
  250. def ggml_pad(x: int, n: int) -> int:
  251. return ((x + n - 1) // n) * n
  252. def add_tensor_info(
  253. self, name: str, tensor_shape: Sequence[int], tensor_dtype: np.dtype,
  254. tensor_nbytes: int, raw_dtype: GGMLQuantizationType | None = None,
  255. ) -> None:
  256. if self.state is not WriterState.NO_FILE:
  257. raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
  258. if any(name in tensors for tensors in self.tensors):
  259. raise ValueError(f'Duplicated tensor name {name!r}')
  260. if raw_dtype is None:
  261. if tensor_dtype == np.float16:
  262. dtype = GGMLQuantizationType.F16
  263. elif tensor_dtype == np.float32:
  264. dtype = GGMLQuantizationType.F32
  265. elif tensor_dtype == np.float64:
  266. dtype = GGMLQuantizationType.F64
  267. elif tensor_dtype == np.int8:
  268. dtype = GGMLQuantizationType.I8
  269. elif tensor_dtype == np.int16:
  270. dtype = GGMLQuantizationType.I16
  271. elif tensor_dtype == np.int32:
  272. dtype = GGMLQuantizationType.I32
  273. elif tensor_dtype == np.int64:
  274. dtype = GGMLQuantizationType.I64
  275. else:
  276. raise ValueError("Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now")
  277. else:
  278. dtype = raw_dtype
  279. if tensor_dtype == np.uint8:
  280. tensor_shape = quant_shape_from_byte_shape(tensor_shape, raw_dtype)
  281. # make sure there is at least one tensor before splitting
  282. if len(self.tensors[-1]) > 0:
  283. if ( # split when over tensor limit
  284. self.split_max_tensors != 0
  285. and len(self.tensors[-1]) >= self.split_max_tensors
  286. ) or ( # split when over size limit
  287. self.split_max_size != 0
  288. and sum(ti.nbytes for ti in self.tensors[-1].values()) + tensor_nbytes > self.split_max_size
  289. ):
  290. self.tensors.append({})
  291. self.tensors[-1][name] = TensorInfo(shape=tensor_shape, dtype=dtype, nbytes=tensor_nbytes)
  292. def add_tensor(
  293. self, name: str, tensor: np.ndarray[Any, Any], raw_shape: Sequence[int] | None = None,
  294. raw_dtype: GGMLQuantizationType | None = None,
  295. ) -> None:
  296. if self.endianess == GGUFEndian.BIG:
  297. tensor.byteswap(inplace=True)
  298. if self.use_temp_file and self.temp_file is None:
  299. fp = tempfile.SpooledTemporaryFile(mode="w+b", max_size=256 * 1024 * 1024)
  300. fp.seek(0)
  301. self.temp_file = fp
  302. shape: Sequence[int] = raw_shape if raw_shape is not None else tensor.shape
  303. self.add_tensor_info(name, shape, tensor.dtype, tensor.nbytes, raw_dtype=raw_dtype)
  304. if self.temp_file is None:
  305. self.tensors[-1][name].tensor = tensor
  306. return
  307. tensor.tofile(self.temp_file)
  308. self.write_padding(self.temp_file, tensor.nbytes)
  309. def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
  310. pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
  311. if pad != 0:
  312. fp.write(bytes([0] * pad))
  313. def write_tensor_data(self, tensor: np.ndarray[Any, Any]) -> None:
  314. if self.state is not WriterState.TI_DATA and self.state is not WriterState.WEIGHTS:
  315. raise ValueError(f'Expected output file to contain tensor info or weights, got {self.state}')
  316. assert self.fout is not None
  317. if self.endianess == GGUFEndian.BIG:
  318. tensor.byteswap(inplace=True)
  319. file_id = -1
  320. for i, tensors in enumerate(self.tensors):
  321. if len(tensors) > 0:
  322. file_id = i
  323. break
  324. fout = self.fout[file_id]
  325. # pop the first tensor info
  326. # TODO: cleaner way to get the first key
  327. first_tensor_name = [name for name, _ in zip(self.tensors[file_id].keys(), range(1))][0]
  328. ti = self.tensors[file_id].pop(first_tensor_name)
  329. assert ti.nbytes == tensor.nbytes
  330. self.write_padding(fout, fout.tell())
  331. tensor.tofile(fout)
  332. self.write_padding(fout, tensor.nbytes)
  333. self.state = WriterState.WEIGHTS
  334. def write_tensors_to_file(self, *, progress: bool = False) -> None:
  335. self.write_ti_data_to_file()
  336. assert self.fout is not None
  337. for fout in self.fout:
  338. self.write_padding(fout, fout.tell())
  339. if self.temp_file is None:
  340. shard_bar = None
  341. bar = None
  342. if progress:
  343. from tqdm import tqdm
  344. total_bytes = sum(ti.nbytes for t in self.tensors for ti in t.values())
  345. if len(self.fout) > 1:
  346. shard_bar = tqdm(desc=f"Shard (0/{len(self.fout)})", total=None, unit="byte", unit_scale=True)
  347. bar = tqdm(desc="Writing", total=total_bytes, unit="byte", unit_scale=True)
  348. for i, (fout, tensors) in enumerate(zip(self.fout, self.tensors)):
  349. if shard_bar is not None:
  350. shard_bar.set_description(f"Shard ({i + 1}/{len(self.fout)})")
  351. total = sum(ti.nbytes for ti in tensors.values())
  352. shard_bar.reset(total=(total if total > 0 else None))
  353. # relying on the fact that Python dicts preserve insertion order (since 3.7)
  354. for ti in tensors.values():
  355. assert ti.tensor is not None # can only iterate once over the tensors
  356. assert ti.tensor.nbytes == ti.nbytes
  357. ti.tensor.tofile(fout)
  358. if shard_bar is not None:
  359. shard_bar.update(ti.nbytes)
  360. if bar is not None:
  361. bar.update(ti.nbytes)
  362. self.write_padding(fout, ti.nbytes)
  363. ti.tensor = None
  364. else:
  365. self.temp_file.seek(0)
  366. shutil.copyfileobj(self.temp_file, self.fout[0 if not self.small_first_shard else 1])
  367. self.flush()
  368. self.temp_file.close()
  369. self.state = WriterState.WEIGHTS
  370. def flush(self) -> None:
  371. assert self.fout is not None
  372. for fout in self.fout:
  373. fout.flush()
  374. def close(self) -> None:
  375. if self.fout is not None:
  376. for fout in self.fout:
  377. fout.close()
  378. self.fout = None
  379. def add_type(self, type_name: str) -> None:
  380. self.add_string(Keys.General.TYPE, type_name)
  381. def add_architecture(self) -> None:
  382. self.add_string(Keys.General.ARCHITECTURE, self.arch)
  383. def add_quantization_version(self, quantization_version: int) -> None:
  384. self.add_uint32(Keys.General.QUANTIZATION_VERSION, quantization_version)
  385. def add_custom_alignment(self, alignment: int) -> None:
  386. self.data_alignment = alignment
  387. self.add_uint32(Keys.General.ALIGNMENT, alignment)
  388. def add_file_type(self, ftype: int) -> None:
  389. self.add_uint32(Keys.General.FILE_TYPE, ftype)
  390. def add_name(self, name: str) -> None:
  391. self.add_string(Keys.General.NAME, name)
  392. def add_author(self, author: str) -> None:
  393. self.add_string(Keys.General.AUTHOR, author)
  394. def add_version(self, version: str) -> None:
  395. self.add_string(Keys.General.VERSION, version)
  396. def add_organization(self, organization: str) -> None:
  397. self.add_string(Keys.General.ORGANIZATION, organization)
  398. def add_finetune(self, finetune: str) -> None:
  399. self.add_string(Keys.General.FINETUNE, finetune)
  400. def add_basename(self, basename: str) -> None:
  401. self.add_string(Keys.General.BASENAME, basename)
  402. def add_description(self, description: str) -> None:
  403. self.add_string(Keys.General.DESCRIPTION, description)
  404. def add_quantized_by(self, quantized: str) -> None:
  405. self.add_string(Keys.General.QUANTIZED_BY, quantized)
  406. def add_size_label(self, size_label: str) -> None:
  407. self.add_string(Keys.General.SIZE_LABEL, size_label)
  408. def add_license(self, license: str) -> None:
  409. self.add_string(Keys.General.LICENSE, license)
  410. def add_license_name(self, license: str) -> None:
  411. self.add_string(Keys.General.LICENSE_NAME, license)
  412. def add_license_link(self, license: str) -> None:
  413. self.add_string(Keys.General.LICENSE_LINK, license)
  414. def add_url(self, url: str) -> None:
  415. self.add_string(Keys.General.URL, url)
  416. def add_doi(self, doi: str) -> None:
  417. self.add_string(Keys.General.DOI, doi)
  418. def add_uuid(self, uuid: str) -> None:
  419. self.add_string(Keys.General.UUID, uuid)
  420. def add_repo_url(self, repo_url: str) -> None:
  421. self.add_string(Keys.General.REPO_URL, repo_url)
  422. def add_source_url(self, url: str) -> None:
  423. self.add_string(Keys.General.SOURCE_URL, url)
  424. def add_source_doi(self, doi: str) -> None:
  425. self.add_string(Keys.General.SOURCE_DOI, doi)
  426. def add_source_uuid(self, uuid: str) -> None:
  427. self.add_string(Keys.General.SOURCE_UUID, uuid)
  428. def add_source_repo_url(self, repo_url: str) -> None:
  429. self.add_string(Keys.General.SOURCE_REPO_URL, repo_url)
  430. def add_base_model_count(self, source_count: int) -> None:
  431. self.add_uint32(Keys.General.BASE_MODEL_COUNT, source_count)
  432. def add_base_model_name(self, source_id: int, name: str) -> None:
  433. self.add_string(Keys.General.BASE_MODEL_NAME.format(id=source_id), name)
  434. def add_base_model_author(self, source_id: int, author: str) -> None:
  435. self.add_string(Keys.General.BASE_MODEL_AUTHOR.format(id=source_id), author)
  436. def add_base_model_version(self, source_id: int, version: str) -> None:
  437. self.add_string(Keys.General.BASE_MODEL_VERSION.format(id=source_id), version)
  438. def add_base_model_organization(self, source_id: int, organization: str) -> None:
  439. self.add_string(Keys.General.BASE_MODEL_ORGANIZATION.format(id=source_id), organization)
  440. def add_base_model_description(self, source_id: int, description: str) -> None:
  441. self.add_string(Keys.General.BASE_MODEL_DESCRIPTION.format(id=source_id), description)
  442. def add_base_model_url(self, source_id: int, url: str) -> None:
  443. self.add_string(Keys.General.BASE_MODEL_URL.format(id=source_id), url)
  444. def add_base_model_doi(self, source_id: int, doi: str) -> None:
  445. self.add_string(Keys.General.BASE_MODEL_DOI.format(id=source_id), doi)
  446. def add_base_model_uuid(self, source_id: int, uuid: str) -> None:
  447. self.add_string(Keys.General.BASE_MODEL_UUID.format(id=source_id), uuid)
  448. def add_base_model_repo_url(self, source_id: int, repo_url: str) -> None:
  449. self.add_string(Keys.General.BASE_MODEL_REPO_URL.format(id=source_id), repo_url)
  450. def add_dataset_count(self, source_count: int) -> None:
  451. self.add_uint32(Keys.General.DATASET_COUNT, source_count)
  452. def add_dataset_name(self, source_id: int, name: str) -> None:
  453. self.add_string(Keys.General.DATASET_NAME.format(id=source_id), name)
  454. def add_dataset_author(self, source_id: int, author: str) -> None:
  455. self.add_string(Keys.General.DATASET_AUTHOR.format(id=source_id), author)
  456. def add_dataset_version(self, source_id: int, version: str) -> None:
  457. self.add_string(Keys.General.DATASET_VERSION.format(id=source_id), version)
  458. def add_dataset_organization(self, source_id: int, organization: str) -> None:
  459. self.add_string(Keys.General.DATASET_ORGANIZATION.format(id=source_id), organization)
  460. def add_dataset_description(self, source_id: int, description: str) -> None:
  461. self.add_string(Keys.General.DATASET_DESCRIPTION.format(id=source_id), description)
  462. def add_dataset_url(self, source_id: int, url: str) -> None:
  463. self.add_string(Keys.General.DATASET_URL.format(id=source_id), url)
  464. def add_dataset_doi(self, source_id: int, doi: str) -> None:
  465. self.add_string(Keys.General.DATASET_DOI.format(id=source_id), doi)
  466. def add_dataset_uuid(self, source_id: int, uuid: str) -> None:
  467. self.add_string(Keys.General.DATASET_UUID.format(id=source_id), uuid)
  468. def add_dataset_repo_url(self, source_id: int, repo_url: str) -> None:
  469. self.add_string(Keys.General.DATASET_REPO_URL.format(id=source_id), repo_url)
  470. def add_tags(self, tags: Sequence[str]) -> None:
  471. self.add_array(Keys.General.TAGS, tags)
  472. def add_languages(self, languages: Sequence[str]) -> None:
  473. self.add_array(Keys.General.LANGUAGES, languages)
  474. def add_tensor_data_layout(self, layout: str) -> None:
  475. self.add_string(Keys.LLM.TENSOR_DATA_LAYOUT.format(arch=self.arch), layout)
  476. def add_vocab_size(self, size: int) -> None:
  477. self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)
  478. def add_context_length(self, length: int) -> None:
  479. self.add_uint32(Keys.LLM.CONTEXT_LENGTH.format(arch=self.arch), length)
  480. def add_embedding_length(self, length: int) -> None:
  481. self.add_uint32(Keys.LLM.EMBEDDING_LENGTH.format(arch=self.arch), length)
  482. def add_features_length(self, length: int) -> None:
  483. self.add_uint32(Keys.LLM.FEATURES_LENGTH.format(arch=self.arch), length)
  484. def add_posnet_embedding_length(self, length: int) -> None:
  485. self.add_uint32(Keys.PosNet.EMBEDDING_LENGTH.format(arch=self.arch), length)
  486. def add_posnet_block_count(self, length: int) -> None:
  487. self.add_uint32(Keys.PosNet.BLOCK_COUNT.format(arch=self.arch), length)
  488. def add_convnext_embedding_length(self, length: int) -> None:
  489. self.add_uint32(Keys.ConvNext.EMBEDDING_LENGTH.format(arch=self.arch), length)
  490. def add_convnext_block_count(self, length: int) -> None:
  491. self.add_uint32(Keys.ConvNext.BLOCK_COUNT.format(arch=self.arch), length)
  492. def add_block_count(self, length: int) -> None:
  493. self.add_uint32(Keys.LLM.BLOCK_COUNT.format(arch=self.arch), length)
  494. def add_leading_dense_block_count(self, length: int) -> None:
  495. self.add_uint32(Keys.LLM.LEADING_DENSE_BLOCK_COUNT.format(arch=self.arch), length)
  496. def add_feed_forward_length(self, length: int | Sequence[int]) -> None:
  497. if isinstance(length, int):
  498. self.add_uint32(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  499. else:
  500. self.add_array(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  501. def add_expert_feed_forward_length(self, length: int) -> None:
  502. self.add_uint32(Keys.LLM.EXPERT_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  503. def add_expert_shared_feed_forward_length(self, length: int) -> None:
  504. self.add_uint32(Keys.LLM.EXPERT_SHARED_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  505. def add_parallel_residual(self, use: bool) -> None:
  506. self.add_bool(Keys.LLM.USE_PARALLEL_RESIDUAL.format(arch=self.arch), use)
  507. def add_decoder_start_token_id(self, id: int) -> None:
  508. self.add_uint32(Keys.LLM.DECODER_START_TOKEN_ID.format(arch=self.arch), id)
  509. def add_head_count(self, count: int | Sequence[int]) -> None:
  510. if isinstance(count, int):
  511. self.add_uint32(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
  512. else:
  513. self.add_array(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
  514. def add_head_count_kv(self, count: int | Sequence[int]) -> None:
  515. if isinstance(count, int):
  516. self.add_uint32(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
  517. else:
  518. self.add_array(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
  519. def add_key_length(self, length: int) -> None:
  520. self.add_uint32(Keys.Attention.KEY_LENGTH.format(arch=self.arch), length)
  521. def add_value_length(self, length: int) -> None:
  522. self.add_uint32(Keys.Attention.VALUE_LENGTH.format(arch=self.arch), length)
  523. def add_max_alibi_bias(self, bias: float) -> None:
  524. self.add_float32(Keys.Attention.MAX_ALIBI_BIAS.format(arch=self.arch), bias)
  525. def add_clamp_kqv(self, value: float) -> None:
  526. self.add_float32(Keys.Attention.CLAMP_KQV.format(arch=self.arch), value)
  527. def add_logit_scale(self, value: float) -> None:
  528. self.add_float32(Keys.LLM.LOGIT_SCALE.format(arch=self.arch), value)
  529. def add_attn_logit_softcapping(self, value: float) -> None:
  530. self.add_float32(Keys.LLM.ATTN_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
  531. def add_final_logit_softcapping(self, value: float) -> None:
  532. self.add_float32(Keys.LLM.FINAL_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
  533. def add_expert_count(self, count: int) -> None:
  534. self.add_uint32(Keys.LLM.EXPERT_COUNT.format(arch=self.arch), count)
  535. def add_expert_used_count(self, count: int) -> None:
  536. self.add_uint32(Keys.LLM.EXPERT_USED_COUNT.format(arch=self.arch), count)
  537. def add_expert_shared_count(self, count: int) -> None:
  538. self.add_uint32(Keys.LLM.EXPERT_SHARED_COUNT.format(arch=self.arch), count)
  539. def add_expert_weights_scale(self, value: float) -> None:
  540. self.add_float32(Keys.LLM.EXPERT_WEIGHTS_SCALE.format(arch=self.arch), value)
  541. def add_expert_weights_norm(self, value: bool) -> None:
  542. self.add_bool(Keys.LLM.EXPERT_WEIGHTS_NORM.format(arch=self.arch), value)
  543. def add_expert_gating_func(self, value: ExpertGatingFuncType) -> None:
  544. self.add_uint32(Keys.LLM.EXPERT_GATING_FUNC.format(arch=self.arch), value.value)
  545. def add_swin_norm(self, value: bool) -> None:
  546. self.add_bool(Keys.LLM.SWIN_NORM.format(arch=self.arch), value)
  547. def add_rescale_every_n_layers(self, count: int) -> None:
  548. self.add_uint32(Keys.LLM.RESCALE_EVERY_N_LAYERS.format(arch=self.arch), count)
  549. def add_time_mix_extra_dim(self, dim: int) -> None:
  550. self.add_uint32(Keys.LLM.TIME_MIX_EXTRA_DIM.format(arch=self.arch), dim)
  551. def add_time_decay_extra_dim(self, dim: int) -> None:
  552. self.add_uint32(Keys.LLM.TIME_DECAY_EXTRA_DIM.format(arch=self.arch), dim)
  553. def add_residual_scale(self, value: float) -> None:
  554. self.add_float32(Keys.LLM.RESIDUAL_SCALE.format(arch=self.arch), value)
  555. def add_embedding_scale(self, value: float) -> None:
  556. self.add_float32(Keys.LLM.EMBEDDING_SCALE.format(arch=self.arch), value)
  557. def add_wkv_head_size(self, size: int) -> None:
  558. self.add_uint32(Keys.WKV.HEAD_SIZE.format(arch=self.arch), size)
  559. def add_token_shift_count(self, count: int) -> None:
  560. self.add_uint32(Keys.LLM.TOKEN_SHIFT_COUNT.format(arch=self.arch), count)
  561. def add_layer_norm_eps(self, value: float) -> None:
  562. self.add_float32(Keys.Attention.LAYERNORM_EPS.format(arch=self.arch), value)
  563. def add_layer_norm_rms_eps(self, value: float) -> None:
  564. self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
  565. def add_group_norm_eps(self, value: float) -> None:
  566. self.add_float32(Keys.Attention.GROUPNORM_EPS.format(arch=self.arch), value)
  567. def add_group_norm_groups(self, value: int) -> None:
  568. self.add_uint32(Keys.Attention.GROUPNORM_GROUPS.format(arch=self.arch), value)
  569. def add_causal_attention(self, value: bool) -> None:
  570. self.add_bool(Keys.Attention.CAUSAL.format(arch=self.arch), value)
  571. def add_q_lora_rank(self, length: int) -> None:
  572. self.add_uint32(Keys.Attention.Q_LORA_RANK.format(arch=self.arch), length)
  573. def add_kv_lora_rank(self, length: int) -> None:
  574. self.add_uint32(Keys.Attention.KV_LORA_RANK.format(arch=self.arch), length)
  575. def add_relative_attn_buckets_count(self, value: int) -> None:
  576. self.add_uint32(Keys.Attention.REL_BUCKETS_COUNT.format(arch=self.arch), value)
  577. def add_sliding_window(self, value: int) -> None:
  578. self.add_uint32(Keys.Attention.SLIDING_WINDOW.format(arch=self.arch), value)
  579. def add_attention_scale(self, value: float) -> None:
  580. self.add_float32(Keys.Attention.SCALE.format(arch=self.arch), value)
  581. def add_pooling_type(self, value: PoolingType) -> None:
  582. self.add_uint32(Keys.LLM.POOLING_TYPE.format(arch=self.arch), value.value)
  583. def add_rope_dimension_count(self, count: int) -> None:
  584. self.add_uint32(Keys.Rope.DIMENSION_COUNT.format(arch=self.arch), count)
  585. def add_rope_dimension_sections(self, dims: Sequence[int]) -> None:
  586. self.add_array(Keys.Rope.DIMENSION_SECTIONS.format(arch=self.arch), dims)
  587. def add_rope_freq_base(self, value: float) -> None:
  588. self.add_float32(Keys.Rope.FREQ_BASE.format(arch=self.arch), value)
  589. def add_rope_scaling_type(self, value: RopeScalingType) -> None:
  590. self.add_string(Keys.Rope.SCALING_TYPE.format(arch=self.arch), value.value)
  591. def add_rope_scaling_factor(self, value: float) -> None:
  592. self.add_float32(Keys.Rope.SCALING_FACTOR.format(arch=self.arch), value)
  593. def add_rope_scaling_attn_factors(self, value: float) -> None:
  594. self.add_float32(Keys.Rope.SCALING_ATTN_FACTOR.format(arch=self.arch), value)
  595. def add_rope_scaling_orig_ctx_len(self, value: int) -> None:
  596. self.add_uint32(Keys.Rope.SCALING_ORIG_CTX_LEN.format(arch=self.arch), value)
  597. def add_rope_scaling_finetuned(self, value: bool) -> None:
  598. self.add_bool(Keys.Rope.SCALING_FINETUNED.format(arch=self.arch), value)
  599. def add_rope_scaling_yarn_log_mul(self, value: float) -> None:
  600. self.add_float32(Keys.Rope.SCALING_YARN_LOG_MUL.format(arch=self.arch), value)
  601. def add_ssm_conv_kernel(self, value: int) -> None:
  602. self.add_uint32(Keys.SSM.CONV_KERNEL.format(arch=self.arch), value)
  603. def add_ssm_inner_size(self, value: int) -> None:
  604. self.add_uint32(Keys.SSM.INNER_SIZE.format(arch=self.arch), value)
  605. def add_ssm_state_size(self, value: int) -> None:
  606. self.add_uint32(Keys.SSM.STATE_SIZE.format(arch=self.arch), value)
  607. def add_ssm_time_step_rank(self, value: int) -> None:
  608. self.add_uint32(Keys.SSM.TIME_STEP_RANK.format(arch=self.arch), value)
  609. def add_ssm_dt_b_c_rms(self, value: bool) -> None:
  610. self.add_bool(Keys.SSM.DT_B_C_RMS.format(arch=self.arch), value)
  611. def add_tokenizer_model(self, model: str) -> None:
  612. self.add_string(Keys.Tokenizer.MODEL, model)
  613. def add_tokenizer_pre(self, pre: str) -> None:
  614. self.add_string(Keys.Tokenizer.PRE, pre)
  615. def add_token_list(self, tokens: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
  616. self.add_array(Keys.Tokenizer.LIST, tokens)
  617. def add_token_merges(self, merges: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
  618. self.add_array(Keys.Tokenizer.MERGES, merges)
  619. def add_token_types(self, types: Sequence[TokenType] | Sequence[int]) -> None:
  620. self.add_array(Keys.Tokenizer.TOKEN_TYPE, types)
  621. def add_token_type_count(self, value: int) -> None:
  622. self.add_uint32(Keys.Tokenizer.TOKEN_TYPE_COUNT, value)
  623. def add_token_scores(self, scores: Sequence[float]) -> None:
  624. self.add_array(Keys.Tokenizer.SCORES, scores)
  625. def add_bos_token_id(self, id: int) -> None:
  626. self.add_uint32(Keys.Tokenizer.BOS_ID, id)
  627. def add_eos_token_id(self, id: int) -> None:
  628. self.add_uint32(Keys.Tokenizer.EOS_ID, id)
  629. def add_unk_token_id(self, id: int) -> None:
  630. self.add_uint32(Keys.Tokenizer.UNK_ID, id)
  631. def add_sep_token_id(self, id: int) -> None:
  632. self.add_uint32(Keys.Tokenizer.SEP_ID, id)
  633. def add_pad_token_id(self, id: int) -> None:
  634. self.add_uint32(Keys.Tokenizer.PAD_ID, id)
  635. def add_mask_token_id(self, id: int) -> None:
  636. self.add_uint32(Keys.Tokenizer.MASK_ID, id)
  637. def add_add_bos_token(self, value: bool) -> None:
  638. self.add_bool(Keys.Tokenizer.ADD_BOS, value)
  639. def add_add_eos_token(self, value: bool) -> None:
  640. self.add_bool(Keys.Tokenizer.ADD_EOS, value)
  641. def add_add_space_prefix(self, value: bool) -> None:
  642. self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)
  643. def add_remove_extra_whitespaces(self, value: bool) -> None:
  644. self.add_bool(Keys.Tokenizer.REMOVE_EXTRA_WS, value)
  645. def add_precompiled_charsmap(self, charsmap: Sequence[bytes]) -> None:
  646. self.add_array(Keys.Tokenizer.PRECOMPILED_CHARSMAP, charsmap)
  647. def add_chat_template(self, value: str | Sequence[Mapping[str, str]]) -> None:
  648. if not isinstance(value, str):
  649. template_default = None
  650. template_names = set()
  651. for choice in value:
  652. name = choice.get('name', '')
  653. template = choice.get('template')
  654. # Allowing non-alphanumerical characters in template name is probably not a good idea, so filter it
  655. name = ''.join((c if c in ascii_letters + digits else '_' for c in name))
  656. if name and template is not None:
  657. if name == 'default':
  658. template_default = template
  659. else:
  660. template_names.add(name)
  661. self.add_string(Keys.Tokenizer.CHAT_TEMPLATE_N.format(name=name), template)
  662. if template_names:
  663. self.add_array(Keys.Tokenizer.CHAT_TEMPLATES, list(template_names))
  664. if template_default is None:
  665. return
  666. value = template_default
  667. self.add_string(Keys.Tokenizer.CHAT_TEMPLATE, value)
  668. def add_eot_token_id(self, id: int) -> None:
  669. self.add_uint32(Keys.Tokenizer.EOT_ID, id)
  670. def add_eom_token_id(self, id: int) -> None:
  671. self.add_uint32(Keys.Tokenizer.EOM_ID, id)
  672. def _pack(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> bytes:
  673. pack_prefix = ''
  674. if not skip_pack_prefix:
  675. pack_prefix = '<' if self.endianess == GGUFEndian.LITTLE else '>'
  676. return struct.pack(f'{pack_prefix}{fmt}', value)
  677. def _pack_val(self, val: Any, vtype: GGUFValueType, add_vtype: bool) -> bytes:
  678. kv_data = bytearray()
  679. if add_vtype:
  680. kv_data += self._pack("I", vtype)
  681. pack_fmt = self._simple_value_packing.get(vtype)
  682. if pack_fmt is not None:
  683. kv_data += self._pack(pack_fmt, val, skip_pack_prefix = vtype == GGUFValueType.BOOL)
  684. elif vtype == GGUFValueType.STRING:
  685. encoded_val = val.encode("utf-8") if isinstance(val, str) else val
  686. kv_data += self._pack("Q", len(encoded_val))
  687. kv_data += encoded_val
  688. elif vtype == GGUFValueType.ARRAY:
  689. if not isinstance(val, Sequence):
  690. raise ValueError("Invalid GGUF metadata array, expecting sequence")
  691. if len(val) == 0:
  692. raise ValueError("Invalid GGUF metadata array. Empty array")
  693. if isinstance(val, bytes):
  694. ltype = GGUFValueType.UINT8
  695. else:
  696. ltype = GGUFValueType.get_type(val[0])
  697. if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
  698. raise ValueError("All items in a GGUF array should be of the same type")
  699. kv_data += self._pack("I", ltype)
  700. kv_data += self._pack("Q", len(val))
  701. for item in val:
  702. kv_data += self._pack_val(item, ltype, add_vtype=False)
  703. else:
  704. raise ValueError("Invalid GGUF metadata value type or value")
  705. return kv_data
  706. @staticmethod
  707. def format_n_bytes_to_str(num: int) -> str:
  708. if num == 0:
  709. return "negligible - metadata only"
  710. fnum = float(num)
  711. for unit in ("", "K", "M", "G"):
  712. if abs(fnum) < 1000.0:
  713. return f"{fnum:3.1f}{unit}"
  714. fnum /= 1000.0
  715. return f"{fnum:.1f}T - over 1TB, split recommended"