gguf_writer.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. from __future__ import annotations
  2. import os
  3. import shutil
  4. import struct
  5. import tempfile
  6. from enum import Enum, auto
  7. from io import BufferedWriter
  8. from typing import IO, Any, Sequence, Mapping
  9. from string import ascii_letters, digits
  10. import numpy as np
  11. from .constants import (
  12. GGUF_DEFAULT_ALIGNMENT,
  13. GGUF_MAGIC,
  14. GGUF_VERSION,
  15. GGMLQuantizationType,
  16. GGUFEndian,
  17. GGUFValueType,
  18. Keys,
  19. RopeScalingType,
  20. PoolingType,
  21. TokenType,
  22. )
  23. class WriterState(Enum):
  24. EMPTY = auto()
  25. HEADER = auto()
  26. KV_DATA = auto()
  27. TI_DATA = auto()
  28. class GGUFWriter:
  29. fout: BufferedWriter
  30. temp_file: tempfile.SpooledTemporaryFile[bytes] | None
  31. tensors: list[np.ndarray[Any, Any]]
  32. _simple_value_packing = {
  33. GGUFValueType.UINT8: "B",
  34. GGUFValueType.INT8: "b",
  35. GGUFValueType.UINT16: "H",
  36. GGUFValueType.INT16: "h",
  37. GGUFValueType.UINT32: "I",
  38. GGUFValueType.INT32: "i",
  39. GGUFValueType.FLOAT32: "f",
  40. GGUFValueType.UINT64: "Q",
  41. GGUFValueType.INT64: "q",
  42. GGUFValueType.FLOAT64: "d",
  43. GGUFValueType.BOOL: "?",
  44. }
  45. def __init__(
  46. self, path: os.PathLike[str] | str, arch: str, use_temp_file: bool = True,
  47. endianess: GGUFEndian = GGUFEndian.LITTLE,
  48. ):
  49. self.fout = open(path, "wb")
  50. self.arch = arch
  51. self.endianess = endianess
  52. self.offset_tensor = 0
  53. self.data_alignment = GGUF_DEFAULT_ALIGNMENT
  54. self.kv_data = bytearray()
  55. self.kv_data_count = 0
  56. self.ti_data = bytearray()
  57. self.ti_data_count = 0
  58. self.use_temp_file = use_temp_file
  59. self.temp_file = None
  60. self.tensors = []
  61. print("gguf: This GGUF file is for {0} Endian only".format(
  62. "Big" if self.endianess == GGUFEndian.BIG else "Little",
  63. ))
  64. self.state = WriterState.EMPTY
  65. self.add_architecture()
  66. def write_header_to_file(self) -> None:
  67. if self.state is not WriterState.EMPTY:
  68. raise ValueError(f'Expected output file to be empty, got {self.state}')
  69. self._write_packed("<I", GGUF_MAGIC, skip_pack_prefix = True)
  70. self._write_packed("I", GGUF_VERSION)
  71. self._write_packed("Q", self.ti_data_count)
  72. self._write_packed("Q", self.kv_data_count)
  73. self.flush()
  74. self.state = WriterState.HEADER
  75. def write_kv_data_to_file(self) -> None:
  76. if self.state is not WriterState.HEADER:
  77. raise ValueError(f'Expected output file to contain the header, got {self.state}')
  78. self.fout.write(self.kv_data)
  79. self.flush()
  80. self.state = WriterState.KV_DATA
  81. def write_ti_data_to_file(self) -> None:
  82. if self.state is not WriterState.KV_DATA:
  83. raise ValueError(f'Expected output file to contain KV data, got {self.state}')
  84. self.fout.write(self.ti_data)
  85. self.flush()
  86. self.state = WriterState.TI_DATA
  87. def add_key(self, key: str) -> None:
  88. self.add_val(key, GGUFValueType.STRING, add_vtype=False)
  89. def add_uint8(self, key: str, val: int) -> None:
  90. self.add_key(key)
  91. self.add_val(val, GGUFValueType.UINT8)
  92. def add_int8(self, key: str, val: int) -> None:
  93. self.add_key(key)
  94. self.add_val(val, GGUFValueType.INT8)
  95. def add_uint16(self, key: str, val: int) -> None:
  96. self.add_key(key)
  97. self.add_val(val, GGUFValueType.UINT16)
  98. def add_int16(self, key: str, val: int) -> None:
  99. self.add_key(key)
  100. self.add_val(val, GGUFValueType.INT16)
  101. def add_uint32(self, key: str, val: int) -> None:
  102. self.add_key(key)
  103. self.add_val(val, GGUFValueType.UINT32)
  104. def add_int32(self, key: str, val: int) -> None:
  105. self.add_key(key)
  106. self.add_val(val, GGUFValueType.INT32)
  107. def add_float32(self, key: str, val: float) -> None:
  108. self.add_key(key)
  109. self.add_val(val, GGUFValueType.FLOAT32)
  110. def add_uint64(self, key: str, val: int) -> None:
  111. self.add_key(key)
  112. self.add_val(val, GGUFValueType.UINT64)
  113. def add_int64(self, key: str, val: int) -> None:
  114. self.add_key(key)
  115. self.add_val(val, GGUFValueType.INT64)
  116. def add_float64(self, key: str, val: float) -> None:
  117. self.add_key(key)
  118. self.add_val(val, GGUFValueType.FLOAT64)
  119. def add_bool(self, key: str, val: bool) -> None:
  120. self.add_key(key)
  121. self.add_val(val, GGUFValueType.BOOL)
  122. def add_string(self, key: str, val: str) -> None:
  123. if not val:
  124. return
  125. self.add_key(key)
  126. self.add_val(val, GGUFValueType.STRING)
  127. def add_array(self, key: str, val: Sequence[Any]) -> None:
  128. if not isinstance(val, Sequence):
  129. raise ValueError("Value must be a sequence for array type")
  130. self.add_key(key)
  131. self.add_val(val, GGUFValueType.ARRAY)
  132. def add_val(self, val: Any, vtype: GGUFValueType | None = None, add_vtype: bool = True) -> None:
  133. if vtype is None:
  134. vtype = GGUFValueType.get_type(val)
  135. if add_vtype:
  136. self.kv_data += self._pack("I", vtype)
  137. self.kv_data_count += 1
  138. pack_fmt = self._simple_value_packing.get(vtype)
  139. if pack_fmt is not None:
  140. self.kv_data += self._pack(pack_fmt, val, skip_pack_prefix = vtype == GGUFValueType.BOOL)
  141. elif vtype == GGUFValueType.STRING:
  142. encoded_val = val.encode("utf8") if isinstance(val, str) else val
  143. self.kv_data += self._pack("Q", len(encoded_val))
  144. self.kv_data += encoded_val
  145. elif vtype == GGUFValueType.ARRAY and isinstance(val, Sequence) and val:
  146. ltype = GGUFValueType.get_type(val[0])
  147. if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
  148. raise ValueError("All items in a GGUF array should be of the same type")
  149. self.kv_data += self._pack("I", ltype)
  150. self.kv_data += self._pack("Q", len(val))
  151. for item in val:
  152. self.add_val(item, add_vtype=False)
  153. else:
  154. raise ValueError("Invalid GGUF metadata value type or value")
  155. @staticmethod
  156. def ggml_pad(x: int, n: int) -> int:
  157. return ((x + n - 1) // n) * n
  158. def add_tensor_info(
  159. self, name: str, tensor_shape: Sequence[int], tensor_dtype: np.dtype[np.float16] | np.dtype[np.float32],
  160. tensor_nbytes: int, raw_dtype: GGMLQuantizationType | None = None,
  161. ) -> None:
  162. if self.state is not WriterState.EMPTY:
  163. raise ValueError(f'Expected output file to be empty, got {self.state}')
  164. encoded_name = name.encode("utf8")
  165. self.ti_data += self._pack("Q", len(encoded_name))
  166. self.ti_data += encoded_name
  167. n_dims = len(tensor_shape)
  168. self.ti_data += self._pack("I", n_dims)
  169. for i in range(n_dims):
  170. self.ti_data += self._pack("Q", tensor_shape[n_dims - 1 - i])
  171. if raw_dtype is None:
  172. if tensor_dtype == np.float16:
  173. dtype = GGMLQuantizationType.F16
  174. elif tensor_dtype == np.float32:
  175. dtype = GGMLQuantizationType.F32
  176. elif tensor_dtype == np.float64:
  177. dtype = GGMLQuantizationType.F64
  178. elif tensor_dtype == np.int8:
  179. dtype = GGMLQuantizationType.I8
  180. elif tensor_dtype == np.int16:
  181. dtype = GGMLQuantizationType.I16
  182. elif tensor_dtype == np.int32:
  183. dtype = GGMLQuantizationType.I32
  184. elif tensor_dtype == np.int64:
  185. dtype = GGMLQuantizationType.I64
  186. else:
  187. raise ValueError("Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now")
  188. else:
  189. dtype = raw_dtype
  190. self.ti_data += self._pack("I", dtype)
  191. self.ti_data += self._pack("Q", self.offset_tensor)
  192. self.offset_tensor += GGUFWriter.ggml_pad(tensor_nbytes, self.data_alignment)
  193. self.ti_data_count += 1
  194. def add_tensor(
  195. self, name: str, tensor: np.ndarray[Any, Any], raw_shape: Sequence[int] | None = None,
  196. raw_dtype: GGMLQuantizationType | None = None,
  197. ) -> None:
  198. if self.endianess == GGUFEndian.BIG:
  199. tensor.byteswap(inplace=True)
  200. if self.use_temp_file and self.temp_file is None:
  201. fp = tempfile.SpooledTemporaryFile(mode="w+b", max_size=256 * 1024 * 1024)
  202. fp.seek(0)
  203. self.temp_file = fp
  204. shape: Sequence[int] = raw_shape if raw_shape is not None else tensor.shape
  205. self.add_tensor_info(name, shape, tensor.dtype, tensor.nbytes, raw_dtype = raw_dtype)
  206. if self.temp_file is None:
  207. self.tensors.append(tensor)
  208. return
  209. tensor.tofile(self.temp_file)
  210. self.write_padding(self.temp_file, tensor.nbytes)
  211. def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
  212. pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
  213. if pad != 0:
  214. fp.write(bytes([0] * pad))
  215. def write_tensor_data(self, tensor: np.ndarray[Any, Any]) -> None:
  216. if self.state is not WriterState.TI_DATA:
  217. raise ValueError(f'Expected output file to contain tensor info, got {self.state}')
  218. if self.endianess == GGUFEndian.BIG:
  219. tensor.byteswap(inplace=True)
  220. self.write_padding(self.fout, self.fout.tell())
  221. tensor.tofile(self.fout)
  222. self.write_padding(self.fout, tensor.nbytes)
  223. def write_tensors_to_file(self) -> None:
  224. self.write_ti_data_to_file()
  225. self.write_padding(self.fout, self.fout.tell())
  226. if self.temp_file is None:
  227. while True:
  228. try:
  229. tensor = self.tensors.pop(0)
  230. except IndexError:
  231. break
  232. tensor.tofile(self.fout)
  233. self.write_padding(self.fout, tensor.nbytes)
  234. return
  235. self.temp_file.seek(0)
  236. shutil.copyfileobj(self.temp_file, self.fout)
  237. self.flush()
  238. self.temp_file.close()
  239. def flush(self) -> None:
  240. self.fout.flush()
  241. def close(self) -> None:
  242. self.fout.close()
  243. def add_architecture(self) -> None:
  244. self.add_string(Keys.General.ARCHITECTURE, self.arch)
  245. def add_author(self, author: str) -> None:
  246. self.add_string(Keys.General.AUTHOR, author)
  247. def add_version(self, version: str) -> None:
  248. self.add_string(Keys.General.VERSION, version)
  249. def add_tensor_data_layout(self, layout: str) -> None:
  250. self.add_string(Keys.LLM.TENSOR_DATA_LAYOUT.format(arch=self.arch), layout)
  251. def add_url(self, url: str) -> None:
  252. self.add_string(Keys.General.URL, url)
  253. def add_description(self, description: str) -> None:
  254. self.add_string(Keys.General.DESCRIPTION, description)
  255. def add_licence(self, licence: str) -> None:
  256. self.add_string(Keys.General.LICENSE, licence)
  257. def add_source_url(self, url: str) -> None:
  258. self.add_string(Keys.General.SOURCE_URL, url)
  259. def add_source_hf_repo(self, repo: str) -> None:
  260. self.add_string(Keys.General.SOURCE_HF_REPO, repo)
  261. def add_file_type(self, ftype: int) -> None:
  262. self.add_uint32(Keys.General.FILE_TYPE, ftype)
  263. def add_name(self, name: str) -> None:
  264. self.add_string(Keys.General.NAME, name)
  265. def add_quantization_version(self, quantization_version: GGMLQuantizationType) -> None:
  266. self.add_uint32(
  267. Keys.General.QUANTIZATION_VERSION, quantization_version)
  268. def add_custom_alignment(self, alignment: int) -> None:
  269. self.data_alignment = alignment
  270. self.add_uint32(Keys.General.ALIGNMENT, alignment)
  271. def add_vocab_size(self, size: int) -> None:
  272. self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)
  273. def add_context_length(self, length: int) -> None:
  274. self.add_uint32(Keys.LLM.CONTEXT_LENGTH.format(arch=self.arch), length)
  275. def add_embedding_length(self, length: int) -> None:
  276. self.add_uint32(Keys.LLM.EMBEDDING_LENGTH.format(arch=self.arch), length)
  277. def add_block_count(self, length: int) -> None:
  278. self.add_uint32(Keys.LLM.BLOCK_COUNT.format(arch=self.arch), length)
  279. def add_feed_forward_length(self, length: int) -> None:
  280. self.add_uint32(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
  281. def add_parallel_residual(self, use: bool) -> None:
  282. self.add_bool(Keys.LLM.USE_PARALLEL_RESIDUAL.format(arch=self.arch), use)
  283. def add_head_count(self, count: int) -> None:
  284. self.add_uint32(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
  285. def add_head_count_kv(self, count: int) -> None:
  286. self.add_uint32(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
  287. def add_key_length(self, length: int) -> None:
  288. self.add_uint32(Keys.Attention.KEY_LENGTH.format(arch=self.arch), length)
  289. def add_value_length(self, length: int) -> None:
  290. self.add_uint32(Keys.Attention.VALUE_LENGTH.format(arch=self.arch), length)
  291. def add_max_alibi_bias(self, bias: float) -> None:
  292. self.add_float32(Keys.Attention.MAX_ALIBI_BIAS.format(arch=self.arch), bias)
  293. def add_clamp_kqv(self, value: float) -> None:
  294. self.add_float32(Keys.Attention.CLAMP_KQV.format(arch=self.arch), value)
  295. def add_logit_scale(self, value: float) -> None:
  296. self.add_float32(Keys.LLM.LOGIT_SCALE.format(arch=self.arch), value)
  297. def add_expert_count(self, count: int) -> None:
  298. self.add_uint32(Keys.LLM.EXPERT_COUNT.format(arch=self.arch), count)
  299. def add_expert_used_count(self, count: int) -> None:
  300. self.add_uint32(Keys.LLM.EXPERT_USED_COUNT.format(arch=self.arch), count)
  301. def add_layer_norm_eps(self, value: float) -> None:
  302. self.add_float32(Keys.Attention.LAYERNORM_EPS.format(arch=self.arch), value)
  303. def add_layer_norm_rms_eps(self, value: float) -> None:
  304. self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
  305. def add_causal_attention(self, value: bool) -> None:
  306. self.add_bool(Keys.Attention.CAUSAL.format(arch=self.arch), value)
  307. def add_pooling_type(self, value: PoolingType) -> None:
  308. self.add_uint32(Keys.LLM.POOLING_TYPE.format(arch=self.arch), value.value)
  309. def add_rope_dimension_count(self, count: int) -> None:
  310. self.add_uint32(Keys.Rope.DIMENSION_COUNT.format(arch=self.arch), count)
  311. def add_rope_freq_base(self, value: float) -> None:
  312. self.add_float32(Keys.Rope.FREQ_BASE.format(arch=self.arch), value)
  313. def add_rope_scaling_type(self, value: RopeScalingType) -> None:
  314. self.add_string(Keys.Rope.SCALING_TYPE.format(arch=self.arch), value.value)
  315. def add_rope_scaling_factor(self, value: float) -> None:
  316. self.add_float32(Keys.Rope.SCALING_FACTOR.format(arch=self.arch), value)
  317. def add_rope_scaling_orig_ctx_len(self, value: int) -> None:
  318. self.add_uint32(Keys.Rope.SCALING_ORIG_CTX_LEN.format(arch=self.arch), value)
  319. def add_rope_scaling_finetuned(self, value: bool) -> None:
  320. self.add_bool(Keys.Rope.SCALING_FINETUNED.format(arch=self.arch), value)
  321. def add_ssm_conv_kernel(self, value: int) -> None:
  322. self.add_uint32(Keys.SSM.CONV_KERNEL.format(arch=self.arch), value)
  323. def add_ssm_inner_size(self, value: int) -> None:
  324. self.add_uint32(Keys.SSM.INNER_SIZE.format(arch=self.arch), value)
  325. def add_ssm_state_size(self, value: int) -> None:
  326. self.add_uint32(Keys.SSM.STATE_SIZE.format(arch=self.arch), value)
  327. def add_ssm_time_step_rank(self, value: int) -> None:
  328. self.add_uint32(Keys.SSM.TIME_STEP_RANK.format(arch=self.arch), value)
  329. def add_tokenizer_model(self, model: str) -> None:
  330. self.add_string(Keys.Tokenizer.MODEL, model)
  331. def add_token_list(self, tokens: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
  332. self.add_array(Keys.Tokenizer.LIST, tokens)
  333. def add_token_merges(self, merges: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
  334. self.add_array(Keys.Tokenizer.MERGES, merges)
  335. def add_token_types(self, types: Sequence[TokenType] | Sequence[int]) -> None:
  336. self.add_array(Keys.Tokenizer.TOKEN_TYPE, types)
  337. def add_token_type_count(self, value: int) -> None:
  338. self.add_uint32(Keys.Tokenizer.TOKEN_TYPE_COUNT, value)
  339. def add_token_scores(self, scores: Sequence[float]) -> None:
  340. self.add_array(Keys.Tokenizer.SCORES, scores)
  341. def add_bos_token_id(self, id: int) -> None:
  342. self.add_uint32(Keys.Tokenizer.BOS_ID, id)
  343. def add_eos_token_id(self, id: int) -> None:
  344. self.add_uint32(Keys.Tokenizer.EOS_ID, id)
  345. def add_unk_token_id(self, id: int) -> None:
  346. self.add_uint32(Keys.Tokenizer.UNK_ID, id)
  347. def add_sep_token_id(self, id: int) -> None:
  348. self.add_uint32(Keys.Tokenizer.SEP_ID, id)
  349. def add_pad_token_id(self, id: int) -> None:
  350. self.add_uint32(Keys.Tokenizer.PAD_ID, id)
  351. def add_cls_token_id(self, id: int) -> None:
  352. self.add_uint32(Keys.Tokenizer.CLS_ID, id)
  353. def add_mask_token_id(self, id: int) -> None:
  354. self.add_uint32(Keys.Tokenizer.MASK_ID, id)
  355. def add_add_bos_token(self, value: bool) -> None:
  356. self.add_bool(Keys.Tokenizer.ADD_BOS, value)
  357. def add_add_eos_token(self, value: bool) -> None:
  358. self.add_bool(Keys.Tokenizer.ADD_EOS, value)
  359. def add_add_space_prefix(self, value: bool) -> None:
  360. self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)
  361. def add_chat_template(self, value: str | Sequence[Mapping[str, str]]) -> None:
  362. if isinstance(value, list):
  363. template_default = None
  364. template_names = set()
  365. for choice in value:
  366. name = choice.get('name', '')
  367. template = choice.get('template')
  368. # Allowing non-alphanumerical characters in template name is probably not a good idea, so filter it
  369. name = ''.join((c if c in ascii_letters + digits else '_' for c in name))
  370. if name and template is not None:
  371. if name == 'default':
  372. template_default = template
  373. else:
  374. template_names.add(name)
  375. self.add_string(Keys.Tokenizer.CHAT_TEMPLATE_N.format(name=name), template)
  376. if template_names:
  377. self.add_array(Keys.Tokenizer.CHAT_TEMPLATES, list(template_names))
  378. if template_default is None:
  379. return
  380. value = template_default
  381. self.add_string(Keys.Tokenizer.CHAT_TEMPLATE, value)
  382. def add_prefix_token_id(self, id: int) -> None:
  383. self.add_uint32(Keys.Tokenizer.PREFIX_ID, id)
  384. def add_suffix_token_id(self, id: int) -> None:
  385. self.add_uint32(Keys.Tokenizer.SUFFIX_ID, id)
  386. def add_middle_token_id(self, id: int) -> None:
  387. self.add_uint32(Keys.Tokenizer.MIDDLE_ID, id)
  388. def add_eot_token_id(self, id: int) -> None:
  389. self.add_uint32(Keys.Tokenizer.EOT_ID, id)
  390. def _pack(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> bytes:
  391. pack_prefix = ''
  392. if not skip_pack_prefix:
  393. pack_prefix = '<' if self.endianess == GGUFEndian.LITTLE else '>'
  394. return struct.pack(f'{pack_prefix}{fmt}', value)
  395. def _write_packed(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> None:
  396. self.fout.write(self._pack(fmt, value, skip_pack_prefix))