gguf_writer.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import shutil
  5. import struct
  6. import sys
  7. import tempfile
  8. from dataclasses import dataclass
  9. from enum import Enum, auto
  10. from math import prod
  11. from pathlib import Path
  12. from io import BufferedWriter
  13. from typing import IO, Any, Sequence, Mapping
  14. from string import ascii_letters, digits
  15. import numpy as np
  16. from .constants import (
  17. GGUF_DEFAULT_ALIGNMENT,
  18. GGUF_MAGIC,
  19. GGUF_VERSION,
  20. GGMLQuantizationType,
  21. GGUFEndian,
  22. GGUFValueType,
  23. Keys,
  24. RopeScalingType,
  25. PoolingType,
  26. TokenType,
  27. ExpertGatingFuncType,
  28. )
  29. from .quants import quant_shape_from_byte_shape
  30. logger = logging.getLogger(__name__)
  31. SHARD_NAME_FORMAT = "{:s}-{:05d}-of-{:05d}.gguf"
  32. @dataclass
  33. class TensorInfo:
  34. shape: Sequence[int]
  35. dtype: GGMLQuantizationType
  36. nbytes: int
  37. tensor: np.ndarray[Any, Any] | None = None
  38. @dataclass
  39. class GGUFValue:
  40. value: Any
  41. type: GGUFValueType
  42. sub_type: GGUFValueType | None = None
  43. class WriterState(Enum):
  44. NO_FILE = auto()
  45. EMPTY = auto()
  46. HEADER = auto()
  47. KV_DATA = auto()
  48. TI_DATA = auto()
  49. WEIGHTS = auto()
  50. class GGUFWriter:
  51. fout: list[BufferedWriter] | None
  52. path: Path | None
  53. temp_file: tempfile.SpooledTemporaryFile[bytes] | None
  54. tensors: list[dict[str, TensorInfo]]
  55. kv_data: list[dict[str, GGUFValue]]
  56. state: WriterState
  57. _simple_value_packing = {
  58. GGUFValueType.UINT8: "B",
  59. GGUFValueType.INT8: "b",
  60. GGUFValueType.UINT16: "H",
  61. GGUFValueType.INT16: "h",
  62. GGUFValueType.UINT32: "I",
  63. GGUFValueType.INT32: "i",
  64. GGUFValueType.FLOAT32: "f",
  65. GGUFValueType.UINT64: "Q",
  66. GGUFValueType.INT64: "q",
  67. GGUFValueType.FLOAT64: "d",
  68. GGUFValueType.BOOL: "?",
  69. }
  70. def __init__(
  71. self, path: os.PathLike[str] | str | None, arch: str, use_temp_file: bool = False, endianess: GGUFEndian = GGUFEndian.LITTLE,
  72. split_max_tensors: int = 0, split_max_size: int = 0, dry_run: bool = False, small_first_shard: bool = False
  73. ):
  74. self.fout = None
  75. self.path = Path(path) if path else None
  76. self.arch = arch
  77. self.endianess = endianess
  78. self.data_alignment = GGUF_DEFAULT_ALIGNMENT
  79. self.use_temp_file = use_temp_file
  80. self.temp_file = None
  81. self.tensors = [{}]
  82. self.kv_data = [{}]
  83. self.split_max_tensors = split_max_tensors
  84. self.split_max_size = split_max_size
  85. self.dry_run = dry_run
  86. self.small_first_shard = small_first_shard
  87. logger.info("gguf: This GGUF file is for {0} Endian only".format(
  88. "Big" if self.endianess == GGUFEndian.BIG else "Little",
  89. ))
  90. self.state = WriterState.NO_FILE
  91. if self.small_first_shard:
  92. self.tensors.append({})
  93. self.add_architecture()
  94. def get_total_parameter_count(self) -> tuple[int, int, int, int]:
  95. total_params = 0
  96. shared_params = 0
  97. expert_params = 0
  98. expert_sum = 0
  99. n_expert_tensors = 0
  100. last_lora_a: tuple[str, TensorInfo] | None = None
  101. for tensors in self.tensors:
  102. for name, info in tensors.items():
  103. shape = info.shape
  104. if name.endswith(".lora_a"):
  105. last_lora_a = (name, info)
  106. continue
  107. elif name.endswith(".lora_b"):
  108. if last_lora_a is None or last_lora_a[0] != name[:-1] + "a":
  109. # Bail when the LoRA pair can't be found trivially
  110. logger.warning("can't measure LoRA size correctly, tensor order is unusual")
  111. return 0, 0, 0, 0
  112. else:
  113. shape = (*shape[:-1], last_lora_a[1].shape[-1])
  114. size = prod(shape)
  115. if "_exps." in name:
  116. expert_count = shape[-2 if ".bias" in name else -3]
  117. expert_params += (size // expert_count)
  118. expert_sum += expert_count
  119. n_expert_tensors += 1
  120. else:
  121. shared_params += size
  122. total_params += size
  123. # Hopefully this should work even for variable-expert-count models
  124. expert_count = (expert_sum // n_expert_tensors) if n_expert_tensors > 0 else 0
  125. # Negate the total to signal it's likely not exact
  126. if last_lora_a is not None:
  127. total_params = -total_params
  128. # NOTE: keep the output in the same order as accepted by 'size_label' in gguf-py/gguf/utility.py
  129. return total_params, shared_params, expert_params, expert_count
  130. def format_shard_names(self, path: Path) -> list[Path]:
  131. if len(self.tensors) == 1:
  132. return [path]
  133. return [path.with_name(SHARD_NAME_FORMAT.format(path.stem, i + 1, len(self.tensors))) for i in range(len(self.tensors))]
  134. def open_output_file(self, path: Path | None = None) -> None:
  135. if self.state is WriterState.EMPTY and self.fout is not None and (path is None or path == self.path):
  136. # allow calling this multiple times as long as the path is the same
  137. return
  138. if self.state is not WriterState.NO_FILE:
  139. raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
  140. if path is not None:
  141. self.path = path
  142. if self.path is not None:
  143. filenames = self.print_plan()
  144. self.fout = [open(filename, "wb") for filename in filenames]
  145. self.state = WriterState.EMPTY
  146. def print_plan(self) -> list[Path]:
  147. logger.info("Writing the following files:")
  148. assert self.path is not None
  149. filenames = self.format_shard_names(self.path)
  150. assert len(filenames) == len(self.tensors)
  151. for name, tensors in zip(filenames, self.tensors):
  152. logger.info(f"{name}: n_tensors = {len(tensors)}, total_size = {GGUFWriter.format_n_bytes_to_str(sum(ti.nbytes for ti in tensors.values()))}")
  153. if self.dry_run:
  154. logger.info("Dry run, not writing files")
  155. for name in filenames:
  156. print(name) # noqa: NP100
  157. exit()
  158. return filenames
  159. def add_shard_kv_data(self) -> None:
  160. if len(self.tensors) == 1:
  161. return
  162. total_tensors = sum(len(t) for t in self.tensors)
  163. assert self.fout is not None
  164. total_splits = len(self.fout)
  165. self.kv_data.extend({} for _ in range(len(self.kv_data), total_splits))
  166. for i, kv_data in enumerate(self.kv_data):
  167. kv_data[Keys.Split.LLM_KV_SPLIT_NO] = GGUFValue(i, GGUFValueType.UINT16)
  168. kv_data[Keys.Split.LLM_KV_SPLIT_COUNT] = GGUFValue(total_splits, GGUFValueType.UINT16)
  169. kv_data[Keys.Split.LLM_KV_SPLIT_TENSORS_COUNT] = GGUFValue(total_tensors, GGUFValueType.INT32)
  170. def write_header_to_file(self, path: Path | None = None) -> None:
  171. if len(self.tensors) == 1 and (self.split_max_tensors != 0 or self.split_max_size != 0):
  172. logger.warning("Model fails split requirements, not splitting")
  173. self.open_output_file(path)
  174. if self.state is not WriterState.EMPTY:
  175. raise ValueError(f'Expected output file to be empty, got {self.state}')
  176. assert self.fout is not None
  177. assert len(self.fout) == len(self.tensors)
  178. assert len(self.kv_data) == 1
  179. self.add_shard_kv_data()
  180. for fout, tensors, kv_data in zip(self.fout, self.tensors, self.kv_data):
  181. fout.write(self._pack("<I", GGUF_MAGIC, skip_pack_prefix = True))
  182. fout.write(self._pack("I", GGUF_VERSION))
  183. fout.write(self._pack("Q", len(tensors)))
  184. fout.write(self._pack("Q", len(kv_data)))
  185. fout.flush()
  186. self.state = WriterState.HEADER
  187. def write_kv_data_to_file(self) -> None:
  188. if self.state is not WriterState.HEADER:
  189. raise ValueError(f'Expected output file to contain the header, got {self.state}')
  190. assert self.fout is not None
  191. for fout, kv_data in zip(self.fout, self.kv_data):
  192. kv_bytes = bytearray()
  193. for key, val in kv_data.items():
  194. kv_bytes += self._pack_val(key, GGUFValueType.STRING, add_vtype=False)
  195. kv_bytes += self._pack_val(val.value, val.type, add_vtype=True, sub_type=val.sub_type)
  196. fout.write(kv_bytes)
  197. self.flush()
  198. self.state = WriterState.KV_DATA
  199. def write_ti_data_to_file(self) -> None:
  200. if self.state is not WriterState.KV_DATA:
  201. raise ValueError(f'Expected output file to contain KV data, got {self.state}')
  202. assert self.fout is not None
  203. for fout, tensors in zip(self.fout, self.tensors):
  204. ti_data = bytearray()
  205. offset_tensor = 0
  206. for name, ti in tensors.items():
  207. ti_data += self._pack_val(name, GGUFValueType.STRING, add_vtype=False)
  208. n_dims = len(ti.shape)
  209. ti_data += self._pack("I", n_dims)
  210. for j in range(n_dims):
  211. ti_data += self._pack("Q", ti.shape[n_dims - 1 - j])
  212. ti_data += self._pack("I", ti.dtype)
  213. ti_data += self._pack("Q", offset_tensor)
  214. offset_tensor += GGUFWriter.ggml_pad(ti.nbytes, self.data_alignment)
  215. fout.write(ti_data)
  216. fout.flush()
  217. self.state = WriterState.TI_DATA
  218. def add_key_value(self, key: str, val: Any, vtype: GGUFValueType, sub_type: GGUFValueType | None = None) -> None:
  219. if any(key in kv_data for kv_data in self.kv_data):
  220. logger.warning(f'Duplicated key name {key!r}, overwriting it with new value {val!r} of type {vtype.name}')
  221. self.kv_data[0][key] = GGUFValue(value=val, type=vtype, sub_type=sub_type)
  222. def add_uint8(self, key: str, val: int) -> None:
  223. self.add_key_value(key,val, GGUFValueType.UINT8)
  224. def add_int8(self, key: str, val: int) -> None:
  225. self.add_key_value(key, val, GGUFValueType.INT8)
  226. def add_uint16(self, key: str, val: int) -> None:
  227. self.add_key_value(key, val, GGUFValueType.UINT16)
  228. def add_int16(self, key: str, val: int) -> None:
  229. self.add_key_value(key, val, GGUFValueType.INT16)
  230. def add_uint32(self, key: str, val: int) -> None:
  231. self.add_key_value(key, val, GGUFValueType.UINT32)
  232. def add_int32(self, key: str, val: int) -> None:
  233. self.add_key_value(key, val, GGUFValueType.INT32)
  234. def add_float32(self, key: str, val: float) -> None:
  235. self.add_key_value(key, val, GGUFValueType.FLOAT32)
  236. def add_uint64(self, key: str, val: int) -> None:
  237. self.add_key_value(key, val, GGUFValueType.UINT64)
  238. def add_int64(self, key: str, val: int) -> None:
  239. self.add_key_value(key, val, GGUFValueType.INT64)
  240. def add_float64(self, key: str, val: float) -> None:
  241. self.add_key_value(key, val, GGUFValueType.FLOAT64)
  242. def add_bool(self, key: str, val: bool) -> None:
  243. self.add_key_value(key, val, GGUFValueType.BOOL)
  244. def add_string(self, key: str, val: str) -> None:
  245. if not val:
  246. return
  247. self.add_key_value(key, val, GGUFValueType.STRING)
  248. def add_array(self, key: str, val: Sequence[Any]) -> None:
  249. if len(val) == 0:
  250. return
  251. self.add_key_value(key, val, GGUFValueType.ARRAY)
  252. @staticmethod
  253. def ggml_pad(x: int, n: int) -> int:
  254. return ((x + n - 1) // n) * n
  255. def add_tensor_info(
  256. self, name: str, tensor_shape: Sequence[int], tensor_dtype: np.dtype,
  257. tensor_nbytes: int, raw_dtype: GGMLQuantizationType | None = None,
  258. ) -> None:
  259. if self.state is not WriterState.NO_FILE:
  260. raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
  261. if any(name in tensors for tensors in self.tensors):
  262. raise ValueError(f'Duplicated tensor name {name!r}')
  263. if raw_dtype is None:
  264. if tensor_dtype == np.float16:
  265. dtype = GGMLQuantizationType.F16
  266. elif tensor_dtype == np.float32:
  267. dtype = GGMLQuantizationType.F32
  268. elif tensor_dtype == np.float64:
  269. dtype = GGMLQuantizationType.F64
  270. elif tensor_dtype == np.int8:
  271. dtype = GGMLQuantizationType.I8
  272. elif tensor_dtype == np.int16:
  273. dtype = GGMLQuantizationType.I16
  274. elif tensor_dtype == np.int32:
  275. dtype = GGMLQuantizationType.I32
  276. elif tensor_dtype == np.int64:
  277. dtype = GGMLQuantizationType.I64
  278. else:
  279. raise ValueError("Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now")
  280. else:
  281. dtype = raw_dtype
  282. if tensor_dtype == np.uint8:
  283. tensor_shape = quant_shape_from_byte_shape(tensor_shape, raw_dtype)
  284. # make sure there is at least one tensor before splitting
  285. if len(self.tensors[-1]) > 0:
  286. if ( # split when over tensor limit
  287. self.split_max_tensors != 0
  288. and len(self.tensors[-1]) >= self.split_max_tensors
  289. ) or ( # split when over size limit
  290. self.split_max_size != 0
  291. and sum(ti.nbytes for ti in self.tensors[-1].values()) + tensor_nbytes > self.split_max_size
  292. ):
  293. self.tensors.append({})
  294. self.tensors[-1][name] = TensorInfo(shape=tensor_shape, dtype=dtype, nbytes=tensor_nbytes)
  295. def add_tensor(
  296. self, name: str, tensor: np.ndarray[Any, Any], raw_shape: Sequence[int] | None = None,
  297. raw_dtype: GGMLQuantizationType | None = None, tensor_endianess: GGUFEndian | None = None
  298. ) -> None:
  299. # if tensor endianness is not passed, assume it's native to system
  300. if tensor_endianess is None:
  301. tensor_endianess = GGUFEndian.BIG if sys.byteorder == 'big' else GGUFEndian.LITTLE
  302. if tensor_endianess != self.endianess:
  303. # Don't byteswap inplace since lazy copies cannot handle it
  304. tensor = tensor.byteswap(inplace=False)
  305. if self.use_temp_file and self.temp_file is None:
  306. fp = tempfile.SpooledTemporaryFile(mode="w+b", max_size=256 * 1024 * 1024)
  307. fp.seek(0)
  308. self.temp_file = fp
  309. shape: Sequence[int] = raw_shape if raw_shape is not None else tensor.shape
  310. self.add_tensor_info(name, shape, tensor.dtype, tensor.nbytes, raw_dtype=raw_dtype)
  311. if self.temp_file is None:
  312. self.tensors[-1][name].tensor = tensor
  313. return
  314. tensor.tofile(self.temp_file)
  315. self.write_padding(self.temp_file, tensor.nbytes)
  316. def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
  317. pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
  318. if pad != 0:
  319. fp.write(bytes([0] * pad))
  320. def write_tensor_data(self, tensor: np.ndarray[Any, Any], tensor_endianess: GGUFEndian | None = None) -> None:
  321. if self.state is not WriterState.TI_DATA and self.state is not WriterState.WEIGHTS:
  322. raise ValueError(f'Expected output file to contain tensor info or weights, got {self.state}')
  323. assert self.fout is not None
  324. # if tensor endianness is not passed, assume it's native to system
  325. if tensor_endianess is None:
  326. tensor_endianess = GGUFEndian.BIG if sys.byteorder == 'big' else GGUFEndian.LITTLE
  327. if tensor_endianess != self.endianess:
  328. # Don't byteswap inplace since lazy copies cannot handle it
  329. tensor = tensor.byteswap(inplace=False)
  330. file_id = -1
  331. for i, tensors in enumerate(self.tensors):
  332. if len(tensors) > 0:
  333. file_id = i
  334. break
  335. fout = self.fout[file_id]
  336. # pop the first tensor info
  337. # TODO: cleaner way to get the first key
  338. first_tensor_name = [name for name, _ in zip(self.tensors[file_id].keys(), range(1))][0]
  339. ti = self.tensors[file_id].pop(first_tensor_name)
  340. assert ti.nbytes == tensor.nbytes
  341. self.write_padding(fout, fout.tell())
  342. tensor.tofile(fout)
  343. self.write_padding(fout, tensor.nbytes)
  344. self.state = WriterState.WEIGHTS
  345. def write_tensors_to_file(self, *, progress: bool = False) -> None:
  346. self.write_ti_data_to_file()
  347. assert self.fout is not None
  348. for fout in self.fout:
  349. self.write_padding(fout, fout.tell())
  350. if self.temp_file is None:
  351. shard_bar = None
  352. bar = None
  353. if progress:
  354. from tqdm import tqdm
  355. total_bytes = sum(ti.nbytes for t in self.tensors for ti in t.values())
  356. if len(self.fout) > 1:
  357. shard_bar = tqdm(desc=f"Shard (0/{len(self.fout)})", total=None, unit="byte", unit_scale=True)
  358. bar = tqdm(desc="Writing", total=total_bytes, unit="byte", unit_scale=True)
  359. for i, (fout, tensors) in enumerate(zip(self.fout, self.tensors)):
  360. if shard_bar is not None:
  361. shard_bar.set_description(f"Shard ({i + 1}/{len(self.fout)})")
  362. total = sum(ti.nbytes for ti in tensors.values())
  363. shard_bar.reset(total=(total if total > 0 else None))
  364. # relying on the fact that Python dicts preserve insertion order (since 3.7)
  365. for ti in tensors.values():
  366. assert ti.tensor is not None # can only iterate once over the tensors
  367. assert ti.tensor.nbytes == ti.nbytes
  368. ti.tensor.tofile(fout)
  369. if shard_bar is not None:
  370. shard_bar.update(ti.nbytes)
  371. if bar is not None:
  372. bar.update(ti.nbytes)
  373. self.write_padding(fout, ti.nbytes)
  374. ti.tensor = None
  375. else:
  376. self.temp_file.seek(0)
  377. shutil.copyfileobj(self.temp_file, self.fout[0 if not self.small_first_shard else 1])
  378. self.flush()
  379. self.temp_file.close()
  380. self.state = WriterState.WEIGHTS
  381. def flush(self) -> None:
  382. assert self.fout is not None
  383. for fout in self.fout:
  384. fout.flush()
  385. def close(self) -> None:
  386. if self.fout is not None:
  387. for fout in self.fout:
  388. fout.close()
  389. self.fout = None
  390. def add_type(self, type_name: str) -> None:
  391. self.add_string(Keys.General.TYPE, type_name)
  392. def add_architecture(self) -> None:
  393. self.add_string(Keys.General.ARCHITECTURE, self.arch)
  394. def add_quantization_version(self, quantization_version: int) -> None:
  395. self.add_uint32(Keys.General.QUANTIZATION_VERSION, quantization_version)
  396. def add_custom_alignment(self, alignment: int) -> None:
  397. self.data_alignment = alignment
  398. self.add_uint32(Keys.General.ALIGNMENT, alignment)
  399. def add_file_type(self, ftype: int) -> None:
  400. self.add_uint32(Keys.General.FILE_TYPE, ftype)
  401. def add_sampling_sequence(self, sequence: str) -> None:
  402. self.add_string(Keys.General.SAMPLING_SEQUENCE, sequence)
  403. def add_sampling_top_k(self, top_k: int) -> None:
  404. self.add_int32(Keys.General.SAMPLING_TOP_K, top_k)
  405. def add_sampling_top_p(self, top_p: float) -> None:
  406. self.add_float32(Keys.General.SAMPLING_TOP_P, top_p)
  407. def add_sampling_min_p(self, min_p: float) -> None:
  408. self.add_float32(Keys.General.SAMPLING_MIN_P, min_p)
  409. def add_sampling_xtc_probability(self, xtc_probability: float) -> None:
  410. self.add_float32(Keys.General.SAMPLING_XTC_PROBABILITY, xtc_probability)
  411. def add_sampling_xtc_threshold(self, xtc_threshold: float) -> None:
  412. self.add_float32(Keys.General.SAMPLING_XTC_THRESHOLD, xtc_threshold)
  413. def add_sampling_temp(self, temp: float) -> None:
  414. self.add_float32(Keys.General.SAMPLING_TEMP, temp)
  415. def add_sampling_penalty_last_n(self, penalty_last_n: int) -> None:
  416. self.add_int32(Keys.General.SAMPLING_PENALTY_LAST_N, penalty_last_n)
  417. def add_sampling_penalty_repeat(self, penalty_repeat: float) -> None:
  418. self.add_float32(Keys.General.SAMPLING_PENALTY_REPEAT, penalty_repeat)
  419. def add_sampling_mirostat(self, mirostat: int) -> None:
  420. self.add_int32(Keys.General.SAMPLING_MIROSTAT, mirostat)
  421. def add_sampling_mirostat_tau(self, mirostat_tau: float) -> None:
  422. self.add_float32(Keys.General.SAMPLING_MIROSTAT_TAU, mirostat_tau)
  423. def add_sampling_mirostat_eta(self, mirostat_eta: float) -> None:
  424. self.add_float32(Keys.General.SAMPLING_MIROSTAT_ETA, mirostat_eta)
  425. def add_name(self, name: str) -> None:
  426. self.add_string(Keys.General.NAME, name)
  427. def add_author(self, author: str) -> None:
  428. self.add_string(Keys.General.AUTHOR, author)
  429. def add_version(self, version: str) -> None:
  430. self.add_string(Keys.General.VERSION, version)
  431. def add_organization(self, organization: str) -> None:
  432. self.add_string(Keys.General.ORGANIZATION, organization)
  433. def add_finetune(self, finetune: str) -> None:
  434. self.add_string(Keys.General.FINETUNE, finetune)
  435. def add_basename(self, basename: str) -> None:
  436. self.add_string(Keys.General.BASENAME, basename)
  437. def add_description(self, description: str) -> None:
  438. self.add_string(Keys.General.DESCRIPTION, description)
  439. def add_quantized_by(self, quantized: str) -> None:
  440. self.add_string(Keys.General.QUANTIZED_BY, quantized)
  441. def add_size_label(self, size_label: str) -> None:
  442. self.add_string(Keys.General.SIZE_LABEL, size_label)
  443. def add_license(self, license: str) -> None:
  444. self.add_string(Keys.General.LICENSE, license)
  445. def add_license_name(self, license: str) -> None:
  446. self.add_string(Keys.General.LICENSE_NAME, license)
  447. def add_license_link(self, license: str) -> None:
  448. self.add_string(Keys.General.LICENSE_LINK, license)
  449. def add_url(self, url: str) -> None:
  450. self.add_string(Keys.General.URL, url)
  451. def add_doi(self, doi: str) -> None:
  452. self.add_string(Keys.General.DOI, doi)
  453. def add_uuid(self, uuid: str) -> None:
  454. self.add_string(Keys.General.UUID, uuid)
  455. def add_repo_url(self, repo_url: str) -> None:
  456. self.add_string(Keys.General.REPO_URL, repo_url)
  457. def add_source_url(self, url: str) -> None:
  458. self.add_string(Keys.General.SOURCE_URL, url)
  459. def add_source_doi(self, doi: str) -> None:
  460. self.add_string(Keys.General.SOURCE_DOI, doi)
  461. def add_source_uuid(self, uuid: str) -> None:
  462. self.add_string(Keys.General.SOURCE_UUID, uuid)
  463. def add_source_repo_url(self, repo_url: str) -> None:
  464. self.add_string(Keys.General.SOURCE_REPO_URL, repo_url)
  465. def add_base_model_count(self, source_count: int) -> None:
  466. self.add_uint32(Keys.General.BASE_MODEL_COUNT, source_count)
  467. def add_base_model_name(self, source_id: int, name: str) -> None:
  468. self.add_string(Keys.General.BASE_MODEL_NAME.format(id=source_id), name)
  469. def add_base_model_author(self, source_id: int, author: str) -> None:
  470. self.add_string(Keys.General.BASE_MODEL_AUTHOR.format(id=source_id), author)
  471. def add_base_model_version(self, source_id: int, version: str) -> None:
  472. self.add_string(Keys.General.BASE_MODEL_VERSION.format(id=source_id), version)
  473. def add_base_model_organization(self, source_id: int, organization: str) -> None:
  474. self.add_string(Keys.General.BASE_MODEL_ORGANIZATION.format(id=source_id), organization)
  475. def add_base_model_description(self, source_id: int, description: str) -> None:
  476. self.add_string(Keys.General.BASE_MODEL_DESCRIPTION.format(id=source_id), description)
  477. def add_base_model_url(self, source_id: int, url: str) -> None:
  478. self.add_string(Keys.General.BASE_MODEL_URL.format(id=source_id), url)
  479. def add_base_model_doi(self, source_id: int, doi: str) -> None:
  480. self.add_string(Keys.General.BASE_MODEL_DOI.format(id=source_id), doi)
  481. def add_base_model_uuid(self, source_id: int, uuid: str) -> None:
  482. self.add_string(Keys.General.BASE_MODEL_UUID.format(id=source_id), uuid)
  483. def add_base_model_repo_url(self, source_id: int, repo_url: str) -> None:
  484. self.add_string(Keys.General.BASE_MODEL_REPO_URL.format(id=source_id), repo_url)
  485. def add_dataset_count(self, source_count: int) -> None:
  486. self.add_uint32(Keys.General.DATASET_COUNT, source_count)
  487. def add_dataset_name(self, source_id: int, name: str) -> None:
  488. self.add_string(Keys.General.DATASET_NAME.format(id=source_id), name)
  489. def add_dataset_author(self, source_id: int, author: str) -> None:
  490. self.add_string(Keys.General.DATASET_AUTHOR.format(id=source_id), author)
  491. def add_dataset_version(self, source_id: int, version: str) -> None:
  492. self.add_string(Keys.General.DATASET_VERSION.format(id=source_id), version)
  493. def add_dataset_organization(self, source_id: int, organization: str) -> None:
  494. self.add_string(Keys.General.DATASET_ORGANIZATION.format(id=source_id), organization)
  495. def add_dataset_description(self, source_id: int, description: str) -> None:
  496. self.add_string(Keys.General.DATASET_DESCRIPTION.format(id=source_id), description)
  497. def add_dataset_url(self, source_id: int, url: str) -> None:
  498. self.add_string(Keys.General.DATASET_URL.format(id=source_id), url)
  499. def add_dataset_doi(self, source_id: int, doi: str) -> None:
  500. self.add_string(Keys.General.DATASET_DOI.format(id=source_id), doi)
  501. def add_dataset_uuid(self, source_id: int, uuid: str) -> None:
  502. self.add_string(Keys.General.DATASET_UUID.format(id=source_id), uuid)
  503. def add_dataset_repo_url(self, source_id: int, repo_url: str) -> None:
  504. self.add_string(Keys.General.DATASET_REPO_URL.format(id=source_id), repo_url)
  505. def add_tags(self, tags: Sequence[str]) -> None:
  506. self.add_array(Keys.General.TAGS, tags)
  507. def add_languages(self, languages: Sequence[str]) -> None:
  508. self.add_array(Keys.General.LANGUAGES, languages)
  509. def add_tensor_data_layout(self, layout: str) -> None:
  510. self.add_string(Keys.LLM.TENSOR_DATA_LAYOUT.format(arch=self.arch), layout)
  511. def add_vocab_size(self, size: int) -> None:
  512. self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)
  513. def add_context_length(self, length: int) -> None:
  514. self.add_uint32(Keys.LLM.CONTEXT_LENGTH.format(arch=self.arch), length)
  515. def add_embedding_length(self, length: int) -> None:
  516. self.add_uint32(Keys.LLM.EMBEDDING_LENGTH.format(arch=self.arch), length)
  517. def add_features_length(self, length: int) -> None:
  518. self.add_uint32(Keys.LLM.FEATURES_LENGTH.format(arch=self.arch), length)
  519. def add_posnet_embedding_length(self, length: int) -> None:
  520. self.add_uint32(Keys.PosNet.EMBEDDING_LENGTH.format(arch=self.arch), length)
  521. def add_posnet_block_count(self, length: int) -> None:
  522. self.add_uint32(Keys.PosNet.BLOCK_COUNT.format(arch=self.arch), length)
  523. def add_convnext_embedding_length(self, length: int) -> None:
  524. self.add_uint32(Keys.ConvNext.EMBEDDING_LENGTH.format(arch=self.arch), length)
  525. def add_convnext_block_count(self, length: int) -> None:
  526. self.add_uint32(Keys.ConvNext.BLOCK_COUNT.format(arch=self.arch), length)
  527. def add_shortconv_l_cache(self, length: int) -> None:
  528. self.add_uint32(Keys.ShortConv.L_CACHE.format(arch=self.arch), length)
  529. def add_block_count(self, length: int) -> None:
  530. self.add_uint32(Keys.LLM.BLOCK_COUNT.format(arch=self.arch), length)
  531. def add_leading_dense_block_count(self, length: int) -> None:
  532. self.add_uint32(Keys.LLM.LEADING_DENSE_BLOCK_COUNT.format(arch=self.arch), length)
  533. def add_feed_forward_length(self, length: int | Sequence[int]) -> None:
  534. if isinstance(length, int):
  535. self.add_uint32(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  536. else:
  537. self.add_array(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  538. def add_expert_feed_forward_length(self, length: int) -> None:
  539. self.add_uint32(Keys.LLM.EXPERT_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  540. def add_expert_shared_feed_forward_length(self, length: int) -> None:
  541. self.add_uint32(Keys.LLM.EXPERT_SHARED_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  542. def add_expert_chunk_feed_forward_length(self, length: int) -> None:
  543. self.add_uint32(Keys.LLM.EXPERT_CHUNK_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  544. def add_parallel_residual(self, use: bool) -> None:
  545. self.add_bool(Keys.LLM.USE_PARALLEL_RESIDUAL.format(arch=self.arch), use)
  546. def add_decoder_start_token_id(self, id: int) -> None:
  547. self.add_uint32(Keys.LLM.DECODER_START_TOKEN_ID.format(arch=self.arch), id)
  548. def add_decoder_block_count(self, value: int) -> None:
  549. self.add_uint32(Keys.LLM.DECODER_BLOCK_COUNT.format(arch=self.arch), value)
  550. def add_embedding_length_per_layer_input(self, value: int) -> None:
  551. self.add_uint32(Keys.LLM.EMBD_LENGTH_PER_LAYER_INP.format(arch=self.arch), value)
  552. def add_altup_active_idx(self, val: int) -> None:
  553. self.add_uint32(Keys.LLM.ALTUP_ACTIVE_IDX.format(arch=self.arch), val)
  554. def add_altup_num_inputs(self, val: int) -> None:
  555. self.add_uint32(Keys.LLM.ALTUP_NUM_INPUTS.format(arch=self.arch), val)
  556. def add_activation_sparsity_scale(self, values: Sequence[float]) -> None:
  557. self.add_array(Keys.LLM.ACTIVATION_SPARSITY_SCALE.format(arch=self.arch), values)
  558. def add_head_count(self, count: int | Sequence[int]) -> None:
  559. if isinstance(count, int):
  560. self.add_uint32(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
  561. else:
  562. self.add_array(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
  563. def add_head_count_kv(self, count: int | Sequence[int]) -> None:
  564. if isinstance(count, int):
  565. self.add_uint32(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
  566. else:
  567. self.add_array(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
  568. def add_key_length(self, length: int) -> None:
  569. self.add_uint32(Keys.Attention.KEY_LENGTH.format(arch=self.arch), length)
  570. def add_value_length(self, length: int) -> None:
  571. self.add_uint32(Keys.Attention.VALUE_LENGTH.format(arch=self.arch), length)
  572. def add_key_length_mla(self, length: int) -> None:
  573. self.add_uint32(Keys.Attention.KEY_LENGTH_MLA.format(arch=self.arch), length)
  574. def add_value_length_mla(self, length: int) -> None:
  575. self.add_uint32(Keys.Attention.VALUE_LENGTH_MLA.format(arch=self.arch), length)
  576. def add_max_alibi_bias(self, bias: float) -> None:
  577. self.add_float32(Keys.Attention.MAX_ALIBI_BIAS.format(arch=self.arch), bias)
  578. def add_clamp_kqv(self, value: float) -> None:
  579. self.add_float32(Keys.Attention.CLAMP_KQV.format(arch=self.arch), value)
  580. def add_shared_kv_layers(self, value: int) -> None:
  581. self.add_uint32(Keys.Attention.SHARED_KV_LAYERS.format(arch=self.arch), value)
  582. def add_sliding_window_pattern(self, value: Sequence[bool]) -> None:
  583. self.add_array(Keys.Attention.SLIDING_WINDOW_PATTERN.format(arch=self.arch), value)
  584. def add_dense_features_dims(self, dense:str, in_f:int, out_f:int) -> None:
  585. self.add_uint32(Keys.LLM.DENSE_FEAT_IN_SIZE.format(arch=self.arch, dense=dense), in_f)
  586. self.add_uint32(Keys.LLM.DENSE_FEAT_OUT_SIZE.format(arch=self.arch, dense=dense), out_f)
  587. def add_logit_scale(self, value: float) -> None:
  588. self.add_float32(Keys.LLM.LOGIT_SCALE.format(arch=self.arch), value)
  589. def add_attn_logit_softcapping(self, value: float) -> None:
  590. self.add_float32(Keys.LLM.ATTN_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
  591. def add_router_logit_softcapping(self, value: float) -> None:
  592. self.add_float32(Keys.LLM.ROUTER_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
  593. def add_final_logit_softcapping(self, value: float) -> None:
  594. self.add_float32(Keys.LLM.FINAL_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
  595. def add_expert_count(self, count: int) -> None:
  596. self.add_uint32(Keys.LLM.EXPERT_COUNT.format(arch=self.arch), count)
  597. def add_expert_used_count(self, count: int) -> None:
  598. self.add_uint32(Keys.LLM.EXPERT_USED_COUNT.format(arch=self.arch), count)
  599. def add_expert_shared_count(self, count: int) -> None:
  600. self.add_uint32(Keys.LLM.EXPERT_SHARED_COUNT.format(arch=self.arch), count)
  601. def add_expert_group_count(self, count: int) -> None:
  602. self.add_uint32(Keys.LLM.EXPERT_GROUP_COUNT.format(arch=self.arch), count)
  603. def add_expert_group_used_count(self, count: int) -> None:
  604. self.add_uint32(Keys.LLM.EXPERT_GROUP_USED_COUNT.format(arch=self.arch), count)
  605. def add_expert_weights_scale(self, value: float) -> None:
  606. self.add_float32(Keys.LLM.EXPERT_WEIGHTS_SCALE.format(arch=self.arch), value)
  607. def add_expert_weights_norm(self, value: bool) -> None:
  608. self.add_bool(Keys.LLM.EXPERT_WEIGHTS_NORM.format(arch=self.arch), value)
  609. def add_expert_gating_func(self, value: ExpertGatingFuncType) -> None:
  610. self.add_uint32(Keys.LLM.EXPERT_GATING_FUNC.format(arch=self.arch), value.value)
  611. def add_expert_group_scale(self, value: float) -> None:
  612. self.add_float32(Keys.LLM.EXPERT_GROUP_SCALE.format(arch=self.arch), value)
  613. def add_experts_per_group(self, count: int) -> None:
  614. self.add_uint32(Keys.LLM.EXPERTS_PER_GROUP.format(arch=self.arch), count)
  615. def add_moe_every_n_layers(self, value: int) -> None:
  616. self.add_uint32(Keys.LLM.MOE_EVERY_N_LAYERS.format(arch=self.arch), value)
  617. def add_nextn_predict_layers(self, count: int) -> None:
  618. self.add_uint32(Keys.LLM.NEXTN_PREDICT_LAYERS.format(arch=self.arch), count)
  619. def add_swin_norm(self, value: bool) -> None:
  620. self.add_bool(Keys.LLM.SWIN_NORM.format(arch=self.arch), value)
  621. def add_rescale_every_n_layers(self, count: int) -> None:
  622. self.add_uint32(Keys.LLM.RESCALE_EVERY_N_LAYERS.format(arch=self.arch), count)
  623. def add_time_mix_extra_dim(self, dim: int) -> None:
  624. self.add_uint32(Keys.LLM.TIME_MIX_EXTRA_DIM.format(arch=self.arch), dim)
  625. def add_time_decay_extra_dim(self, dim: int) -> None:
  626. self.add_uint32(Keys.LLM.TIME_DECAY_EXTRA_DIM.format(arch=self.arch), dim)
  627. def add_residual_scale(self, value: float) -> None:
  628. self.add_float32(Keys.LLM.RESIDUAL_SCALE.format(arch=self.arch), value)
  629. def add_embedding_scale(self, value: float) -> None:
  630. self.add_float32(Keys.LLM.EMBEDDING_SCALE.format(arch=self.arch), value)
  631. def add_wkv_head_size(self, size: int) -> None:
  632. self.add_uint32(Keys.WKV.HEAD_SIZE.format(arch=self.arch), size)
  633. def add_token_shift_count(self, count: int) -> None:
  634. self.add_uint32(Keys.LLM.TOKEN_SHIFT_COUNT.format(arch=self.arch), count)
  635. def add_interleave_moe_layer_step(self, value: int) -> None:
  636. self.add_uint32(Keys.LLM.INTERLEAVE_MOE_LAYER_STEP.format(arch=self.arch), value)
  637. def add_layer_norm_eps(self, value: float) -> None:
  638. self.add_float32(Keys.Attention.LAYERNORM_EPS.format(arch=self.arch), value)
  639. def add_layer_norm_rms_eps(self, value: float) -> None:
  640. self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
  641. def add_group_norm_eps(self, value: float) -> None:
  642. self.add_float32(Keys.Attention.GROUPNORM_EPS.format(arch=self.arch), value)
  643. def add_group_norm_groups(self, value: int) -> None:
  644. self.add_uint32(Keys.Attention.GROUPNORM_GROUPS.format(arch=self.arch), value)
  645. def add_causal_attention(self, value: bool) -> None:
  646. self.add_bool(Keys.Attention.CAUSAL.format(arch=self.arch), value)
  647. def add_q_lora_rank(self, length: int) -> None:
  648. self.add_uint32(Keys.Attention.Q_LORA_RANK.format(arch=self.arch), length)
  649. def add_kv_lora_rank(self, length: int) -> None:
  650. self.add_uint32(Keys.Attention.KV_LORA_RANK.format(arch=self.arch), length)
  651. def add_decay_lora_rank(self, length: int) -> None:
  652. self.add_uint32(Keys.Attention.DECAY_LORA_RANK.format(arch=self.arch), length)
  653. def add_iclr_lora_rank(self, length: int) -> None:
  654. self.add_uint32(Keys.Attention.ICLR_LORA_RANK.format(arch=self.arch), length)
  655. def add_value_residual_mix_lora_rank(self, length: int) -> None:
  656. self.add_uint32(Keys.Attention.VALUE_RESIDUAL_MIX_LORA_RANK.format(arch=self.arch), length)
  657. def add_gate_lora_rank(self, length: int) -> None:
  658. self.add_uint32(Keys.Attention.GATE_LORA_RANK.format(arch=self.arch), length)
  659. def add_relative_attn_buckets_count(self, value: int) -> None:
  660. self.add_uint32(Keys.Attention.REL_BUCKETS_COUNT.format(arch=self.arch), value)
  661. def add_sliding_window(self, value: int) -> None:
  662. self.add_uint32(Keys.Attention.SLIDING_WINDOW.format(arch=self.arch), value)
  663. def add_attention_scale(self, value: float) -> None:
  664. self.add_float32(Keys.Attention.SCALE.format(arch=self.arch), value)
  665. def add_attn_output_scale(self, value: float) -> None:
  666. self.add_float32(Keys.Attention.OUTPUT_SCALE.format(arch=self.arch), value)
  667. def add_attn_temperature_length(self, value: int) -> None:
  668. self.add_uint32(Keys.Attention.TEMPERATURE_LENGTH.format(arch=self.arch), value)
  669. def add_attn_temperature_scale(self, value: float) -> None:
  670. self.add_float32(Keys.Attention.TEMPERATURE_SCALE.format(arch=self.arch), value)
  671. def add_pooling_type(self, value: PoolingType) -> None:
  672. self.add_uint32(Keys.LLM.POOLING_TYPE.format(arch=self.arch), value.value)
  673. def add_num_deepstack_layers(self, count: int) -> None:
  674. self.add_uint32(Keys.LLM.NUM_DEEPSTACK_LAYERS.format(arch=self.arch), count)
  675. def add_rope_dimension_count(self, count: int) -> None:
  676. self.add_uint32(Keys.Rope.DIMENSION_COUNT.format(arch=self.arch), count)
  677. def add_rope_dimension_sections(self, dims: Sequence[int]) -> None:
  678. self.add_array(Keys.Rope.DIMENSION_SECTIONS.format(arch=self.arch), dims)
  679. def add_rope_freq_base(self, value: float) -> None:
  680. self.add_float32(Keys.Rope.FREQ_BASE.format(arch=self.arch), value)
  681. def add_rope_scaling_type(self, value: RopeScalingType) -> None:
  682. self.add_string(Keys.Rope.SCALING_TYPE.format(arch=self.arch), value.value)
  683. def add_rope_scaling_factor(self, value: float) -> None:
  684. self.add_float32(Keys.Rope.SCALING_FACTOR.format(arch=self.arch), value)
  685. def add_rope_scaling_attn_factors(self, value: float) -> None:
  686. self.add_float32(Keys.Rope.SCALING_ATTN_FACTOR.format(arch=self.arch), value)
  687. def add_rope_scaling_orig_ctx_len(self, value: int) -> None:
  688. self.add_uint32(Keys.Rope.SCALING_ORIG_CTX_LEN.format(arch=self.arch), value)
  689. def add_rope_scaling_finetuned(self, value: bool) -> None:
  690. self.add_bool(Keys.Rope.SCALING_FINETUNED.format(arch=self.arch), value)
  691. def add_rope_scaling_yarn_log_mul(self, value: float) -> None:
  692. self.add_float32(Keys.Rope.SCALING_YARN_LOG_MUL.format(arch=self.arch), value)
  693. def add_rope_scaling_yarn_ext_factor(self, value: float) -> None:
  694. self.add_float32(Keys.Rope.SCALING_YARN_EXT_FACTOR.format(arch=self.arch), value)
  695. def add_rope_scaling_yarn_attn_factor(self, value: float) -> None:
  696. self.add_float32(Keys.Rope.SCALING_YARN_ATTN_FACTOR.format(arch=self.arch), value)
  697. def add_rope_scaling_yarn_beta_fast(self, value: float) -> None:
  698. self.add_float32(Keys.Rope.SCALING_YARN_BETA_FAST.format(arch=self.arch), value)
  699. def add_rope_scaling_yarn_beta_slow(self, value: float) -> None:
  700. self.add_float32(Keys.Rope.SCALING_YARN_BETA_SLOW.format(arch=self.arch), value)
  701. def add_ssm_conv_kernel(self, value: int) -> None:
  702. self.add_uint32(Keys.SSM.CONV_KERNEL.format(arch=self.arch), value)
  703. def add_ssm_inner_size(self, value: int) -> None:
  704. self.add_uint32(Keys.SSM.INNER_SIZE.format(arch=self.arch), value)
  705. def add_ssm_state_size(self, value: int) -> None:
  706. self.add_uint32(Keys.SSM.STATE_SIZE.format(arch=self.arch), value)
  707. def add_ssm_time_step_rank(self, value: int) -> None:
  708. self.add_uint32(Keys.SSM.TIME_STEP_RANK.format(arch=self.arch), value)
  709. def add_ssm_group_count(self, value: int) -> None:
  710. self.add_uint32(Keys.SSM.GROUP_COUNT.format(arch=self.arch), value)
  711. def add_ssm_dt_b_c_rms(self, value: bool) -> None:
  712. self.add_bool(Keys.SSM.DT_B_C_RMS.format(arch=self.arch), value)
  713. def add_tokenizer_model(self, model: str) -> None:
  714. self.add_string(Keys.Tokenizer.MODEL, model)
  715. def add_tokenizer_pre(self, pre: str) -> None:
  716. self.add_string(Keys.Tokenizer.PRE, pre)
  717. def add_token_list(self, tokens: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
  718. self.add_array(Keys.Tokenizer.LIST, tokens)
  719. def add_token_merges(self, merges: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
  720. self.add_array(Keys.Tokenizer.MERGES, merges)
  721. def add_token_types(self, types: Sequence[TokenType] | Sequence[int]) -> None:
  722. self.add_array(Keys.Tokenizer.TOKEN_TYPE, types)
  723. def add_token_type_count(self, value: int) -> None:
  724. self.add_uint32(Keys.Tokenizer.TOKEN_TYPE_COUNT, value)
  725. def add_token_scores(self, scores: Sequence[float]) -> None:
  726. self.add_array(Keys.Tokenizer.SCORES, scores)
  727. def add_bos_token_id(self, id: int) -> None:
  728. self.add_uint32(Keys.Tokenizer.BOS_ID, id)
  729. def add_eos_token_id(self, id: int) -> None:
  730. self.add_uint32(Keys.Tokenizer.EOS_ID, id)
  731. def add_unk_token_id(self, id: int) -> None:
  732. self.add_uint32(Keys.Tokenizer.UNK_ID, id)
  733. def add_sep_token_id(self, id: int) -> None:
  734. self.add_uint32(Keys.Tokenizer.SEP_ID, id)
  735. def add_pad_token_id(self, id: int) -> None:
  736. self.add_uint32(Keys.Tokenizer.PAD_ID, id)
  737. def add_mask_token_id(self, id: int) -> None:
  738. self.add_uint32(Keys.Tokenizer.MASK_ID, id)
  739. def add_add_bos_token(self, value: bool) -> None:
  740. self.add_bool(Keys.Tokenizer.ADD_BOS, value)
  741. def add_add_eos_token(self, value: bool) -> None:
  742. self.add_bool(Keys.Tokenizer.ADD_EOS, value)
  743. def add_add_sep_token(self, value: bool) -> None:
  744. self.add_bool(Keys.Tokenizer.ADD_SEP, value)
  745. def add_add_space_prefix(self, value: bool) -> None:
  746. self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)
  747. def add_remove_extra_whitespaces(self, value: bool) -> None:
  748. self.add_bool(Keys.Tokenizer.REMOVE_EXTRA_WS, value)
  749. def add_precompiled_charsmap(self, charsmap: bytes) -> None:
  750. self.add_array(Keys.Tokenizer.PRECOMPILED_CHARSMAP, charsmap)
  751. def add_chat_template(self, value: str | Sequence[Mapping[str, str]]) -> None:
  752. if not isinstance(value, str):
  753. template_default = None
  754. template_names = set()
  755. for choice in value:
  756. name = choice.get('name', '')
  757. template = choice.get('template')
  758. # Allowing non-alphanumerical characters in template name is probably not a good idea, so filter it
  759. name = ''.join((c if c in ascii_letters + digits else '_' for c in name))
  760. if name and template is not None:
  761. if name == 'default':
  762. template_default = template
  763. else:
  764. template_names.add(name)
  765. self.add_string(Keys.Tokenizer.CHAT_TEMPLATE_N.format(name=name), template)
  766. if template_names:
  767. self.add_array(Keys.Tokenizer.CHAT_TEMPLATES, list(template_names))
  768. if template_default is None:
  769. return
  770. value = template_default
  771. self.add_string(Keys.Tokenizer.CHAT_TEMPLATE, value)
  772. def add_eot_token_id(self, id: int) -> None:
  773. self.add_uint32(Keys.Tokenizer.EOT_ID, id)
  774. def add_eom_token_id(self, id: int) -> None:
  775. self.add_uint32(Keys.Tokenizer.EOM_ID, id)
  776. def add_classifier_output_labels(self, labels: Sequence[str]) -> None:
  777. self.add_array(Keys.Classifier.OUTPUT_LABELS.format(arch=self.arch), labels)
  778. # for vision models
  779. def add_clip_has_vision_encoder(self, value: bool) -> None:
  780. self.add_bool(Keys.Clip.HAS_VISION_ENCODER, value)
  781. def add_clip_has_audio_encoder(self, value: bool) -> None:
  782. self.add_bool(Keys.Clip.HAS_AUDIO_ENCODER, value)
  783. def add_clip_projector_type(self, value: str) -> None:
  784. self.add_string(Keys.Clip.PROJECTOR_TYPE, value)
  785. def add_vision_projection_dim(self, value: int) -> None:
  786. self.add_uint32(Keys.ClipVision.PROJECTION_DIM, value)
  787. def add_vision_patch_size(self, value: int) -> None:
  788. self.add_uint32(Keys.ClipVision.PATCH_SIZE, value)
  789. def add_vision_embedding_length(self, value: int) -> None:
  790. self.add_uint32(Keys.ClipVision.EMBEDDING_LENGTH, value)
  791. def add_vision_feed_forward_length(self, value: int) -> None:
  792. self.add_uint32(Keys.ClipVision.FEED_FORWARD_LENGTH, value)
  793. def add_vision_block_count(self, value: int) -> None:
  794. self.add_uint32(Keys.ClipVision.BLOCK_COUNT, value)
  795. def add_vision_head_count(self, value: int) -> None:
  796. self.add_uint32(Keys.ClipVision.Attention.HEAD_COUNT, value)
  797. def add_vision_attention_layernorm_eps(self, value: float) -> None:
  798. self.add_float32(Keys.ClipVision.Attention.LAYERNORM_EPS, value)
  799. def add_vision_image_size(self, value: int) -> None:
  800. self.add_uint32(Keys.ClipVision.IMAGE_SIZE, value)
  801. def add_vision_preproc_image_size(self, value: int) -> None:
  802. self.add_uint32(Keys.ClipVision.PREPROC_IMAGE_SIZE, value)
  803. def add_vision_image_mean(self, values: Sequence[float]) -> None:
  804. self.add_array(Keys.ClipVision.IMAGE_MEAN, values)
  805. def add_vision_image_std(self, values: Sequence[float]) -> None:
  806. self.add_array(Keys.ClipVision.IMAGE_STD, values)
  807. def add_vision_spatial_merge_size(self, value: int) -> None:
  808. self.add_uint32(Keys.ClipVision.SPATIAL_MERGE_SIZE, value)
  809. def add_vision_use_gelu(self, value: bool) -> None:
  810. self.add_bool(Keys.ClipVision.USE_GELU, value)
  811. def add_vision_use_silu(self, value: bool) -> None:
  812. self.add_bool(Keys.ClipVision.USE_SILU, value)
  813. def add_vision_projector_scale_factor(self, value: int) -> None:
  814. self.add_uint32(Keys.ClipVision.Projector.SCALE_FACTOR, value)
  815. def add_vision_n_wa_pattern(self, value: int) -> None:
  816. self.add_uint32(Keys.ClipVision.N_WA_PATTERN, value)
  817. def add_vision_is_deepstack_layers(self, layers: Sequence[bool]) -> None:
  818. self.add_array(Keys.ClipVision.IS_DEEPSTACK_LAYERS, layers)
  819. # audio models
  820. def add_audio_projection_dim(self, value: int) -> None:
  821. self.add_uint32(Keys.ClipAudio.PROJECTION_DIM, value)
  822. def add_audio_embedding_length(self, value: int) -> None:
  823. self.add_uint32(Keys.ClipAudio.EMBEDDING_LENGTH, value)
  824. def add_audio_feed_forward_length(self, value: int) -> None:
  825. self.add_uint32(Keys.ClipAudio.FEED_FORWARD_LENGTH, value)
  826. def add_audio_block_count(self, value: int) -> None:
  827. self.add_uint32(Keys.ClipAudio.BLOCK_COUNT, value)
  828. def add_audio_head_count(self, value: int) -> None:
  829. self.add_uint32(Keys.ClipAudio.Attention.HEAD_COUNT, value)
  830. def add_audio_attention_layernorm_eps(self, value: float) -> None:
  831. self.add_float32(Keys.ClipAudio.Attention.LAYERNORM_EPS, value)
  832. def add_audio_num_mel_bins(self, value: int) -> None:
  833. self.add_uint32(Keys.ClipAudio.NUM_MEL_BINS, value)
  834. def add_audio_stack_factor(self, value: int) -> None:
  835. self.add_uint32(Keys.ClipAudio.Projector.STACK_FACTOR, value)
  836. def add_xielu_alpha_p(self, values: Sequence[float]):
  837. self.add_array(Keys.xIELU.ALPHA_P, values)
  838. def add_xielu_alpha_n(self, values: Sequence[float]):
  839. self.add_array(Keys.xIELU.ALPHA_N, values)
  840. def add_xielu_beta(self, values: Sequence[float]):
  841. self.add_array(Keys.xIELU.BETA, values)
  842. def add_xielu_eps(self, values: Sequence[float]):
  843. self.add_array(Keys.xIELU.EPS, values)
  844. # diffusion models
  845. def add_diffusion_shift_logits(self, value: bool) -> None:
  846. self.add_bool(Keys.Diffusion.SHIFT_LOGITS, value)
  847. def _pack(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> bytes:
  848. pack_prefix = ''
  849. if not skip_pack_prefix:
  850. pack_prefix = '<' if self.endianess == GGUFEndian.LITTLE else '>'
  851. return struct.pack(f'{pack_prefix}{fmt}', value)
  852. def _pack_val(self, val: Any, vtype: GGUFValueType, add_vtype: bool, sub_type: GGUFValueType | None = None) -> bytes:
  853. kv_data = bytearray()
  854. if add_vtype:
  855. kv_data += self._pack("I", vtype)
  856. pack_fmt = self._simple_value_packing.get(vtype)
  857. if pack_fmt is not None:
  858. kv_data += self._pack(pack_fmt, val, skip_pack_prefix = vtype == GGUFValueType.BOOL)
  859. elif vtype == GGUFValueType.STRING:
  860. encoded_val = val.encode("utf-8") if isinstance(val, str) else val
  861. kv_data += self._pack("Q", len(encoded_val))
  862. kv_data += encoded_val
  863. elif vtype == GGUFValueType.ARRAY:
  864. if not isinstance(val, Sequence):
  865. raise ValueError("Invalid GGUF metadata array, expecting sequence")
  866. if len(val) == 0:
  867. raise ValueError("Invalid GGUF metadata array. Empty array")
  868. if sub_type is not None:
  869. ltype = sub_type
  870. elif isinstance(val, bytes):
  871. ltype = GGUFValueType.UINT8
  872. else:
  873. ltype = GGUFValueType.get_type(val[0])
  874. if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
  875. raise ValueError("All items in a GGUF array should be of the same type")
  876. kv_data += self._pack("I", ltype)
  877. kv_data += self._pack("Q", len(val))
  878. for item in val:
  879. kv_data += self._pack_val(item, ltype, add_vtype=False)
  880. else:
  881. raise ValueError("Invalid GGUF metadata value type or value")
  882. return kv_data
  883. @staticmethod
  884. def format_n_bytes_to_str(num: int) -> str:
  885. if num == 0:
  886. return "negligible - metadata only"
  887. fnum = float(num)
  888. for unit in ("", "K", "M", "G"):
  889. if abs(fnum) < 1000.0:
  890. return f"{fnum:3.1f}{unit}"
  891. fnum /= 1000.0
  892. return f"{fnum:.1f}T - over 1TB, split recommended"