bigdl-core-cpp 2.1.0b2__py3-none-manylinux2010_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. bigdl/cpp/__init__.py +0 -0
  2. bigdl/cpp/cli/init-llama-cpp +14 -0
  3. bigdl/cpp/cli/init-ollama +8 -0
  4. bigdl/cpp/convert-hf-to-gguf.py +2856 -0
  5. bigdl/cpp/convert.py +1714 -0
  6. bigdl/cpp/gguf-py/__init__.py +0 -0
  7. bigdl/cpp/gguf-py/gguf/__init__.py +7 -0
  8. bigdl/cpp/gguf-py/gguf/constants.py +1033 -0
  9. bigdl/cpp/gguf-py/gguf/gguf.py +15 -0
  10. bigdl/cpp/gguf-py/gguf/gguf_reader.py +296 -0
  11. bigdl/cpp/gguf-py/gguf/gguf_writer.py +554 -0
  12. bigdl/cpp/gguf-py/gguf/lazy.py +236 -0
  13. bigdl/cpp/gguf-py/gguf/py.typed +0 -0
  14. bigdl/cpp/gguf-py/gguf/quants.py +123 -0
  15. bigdl/cpp/gguf-py/gguf/tensor_mapping.py +463 -0
  16. bigdl/cpp/gguf-py/gguf/vocab.py +165 -0
  17. bigdl/cpp/libs/baby-llama +0 -0
  18. bigdl/cpp/libs/batched +0 -0
  19. bigdl/cpp/libs/batched-bench +0 -0
  20. bigdl/cpp/libs/benchmark +0 -0
  21. bigdl/cpp/libs/embedding +0 -0
  22. bigdl/cpp/libs/gguf +0 -0
  23. bigdl/cpp/libs/imatrix +0 -0
  24. bigdl/cpp/libs/llama-bench +0 -0
  25. bigdl/cpp/libs/llava-cli +0 -0
  26. bigdl/cpp/libs/lookahead +0 -0
  27. bigdl/cpp/libs/lookup +0 -0
  28. bigdl/cpp/libs/ls-sycl-device +0 -0
  29. bigdl/cpp/libs/main +0 -0
  30. bigdl/cpp/libs/ollama +0 -0
  31. bigdl/cpp/libs/perplexity +0 -0
  32. bigdl/cpp/libs/quantize +0 -0
  33. bigdl/cpp/libs/quantize-stats +0 -0
  34. bigdl/cpp/libs/save-load-state +0 -0
  35. bigdl/cpp/libs/server +0 -0
  36. bigdl/cpp/libs/speculative +0 -0
  37. bigdl/cpp/libs/tokenize +0 -0
  38. bigdl_core_cpp-2.1.0b2.data/scripts/init-llama-cpp +14 -0
  39. bigdl_core_cpp-2.1.0b2.data/scripts/init-ollama +8 -0
  40. bigdl_core_cpp-2.1.0b2.dist-info/METADATA +18 -0
  41. bigdl_core_cpp-2.1.0b2.dist-info/RECORD +43 -0
  42. bigdl_core_cpp-2.1.0b2.dist-info/WHEEL +5 -0
  43. bigdl_core_cpp-2.1.0b2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,554 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ import shutil
6
+ import struct
7
+ import tempfile
8
+ from enum import Enum, auto
9
+ from io import BufferedWriter
10
+ from typing import IO, Any, Sequence, Mapping
11
+ from string import ascii_letters, digits
12
+
13
+ import numpy as np
14
+
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
+ )
27
+
28
+ from .quants import quant_shape_from_byte_shape
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class WriterState(Enum):
34
+ EMPTY = auto()
35
+ HEADER = auto()
36
+ KV_DATA = auto()
37
+ TI_DATA = auto()
38
+
39
+
40
+ class GGUFWriter:
41
+ fout: BufferedWriter
42
+ temp_file: tempfile.SpooledTemporaryFile[bytes] | None
43
+ tensors: list[np.ndarray[Any, Any]]
44
+ _simple_value_packing = {
45
+ GGUFValueType.UINT8: "B",
46
+ GGUFValueType.INT8: "b",
47
+ GGUFValueType.UINT16: "H",
48
+ GGUFValueType.INT16: "h",
49
+ GGUFValueType.UINT32: "I",
50
+ GGUFValueType.INT32: "i",
51
+ GGUFValueType.FLOAT32: "f",
52
+ GGUFValueType.UINT64: "Q",
53
+ GGUFValueType.INT64: "q",
54
+ GGUFValueType.FLOAT64: "d",
55
+ GGUFValueType.BOOL: "?",
56
+ }
57
+
58
+ def __init__(
59
+ self, path: os.PathLike[str] | str, arch: str, use_temp_file: bool = True,
60
+ endianess: GGUFEndian = GGUFEndian.LITTLE,
61
+ ):
62
+ self.fout = open(path, "wb")
63
+ self.arch = arch
64
+ self.endianess = endianess
65
+ self.offset_tensor = 0
66
+ self.data_alignment = GGUF_DEFAULT_ALIGNMENT
67
+ self.kv_data = bytearray()
68
+ self.kv_data_count = 0
69
+ self.ti_data = bytearray()
70
+ self.ti_data_count = 0
71
+ self.ti_names = set()
72
+ self.use_temp_file = use_temp_file
73
+ self.temp_file = None
74
+ self.tensors = []
75
+ logger.info("gguf: This GGUF file is for {0} Endian only".format(
76
+ "Big" if self.endianess == GGUFEndian.BIG else "Little",
77
+ ))
78
+ self.state = WriterState.EMPTY
79
+
80
+ self.add_architecture()
81
+
82
+ def write_header_to_file(self) -> None:
83
+ if self.state is not WriterState.EMPTY:
84
+ raise ValueError(f'Expected output file to be empty, got {self.state}')
85
+
86
+ self._write_packed("<I", GGUF_MAGIC, skip_pack_prefix = True)
87
+ self._write_packed("I", GGUF_VERSION)
88
+ self._write_packed("Q", self.ti_data_count)
89
+ self._write_packed("Q", self.kv_data_count)
90
+ self.flush()
91
+ self.state = WriterState.HEADER
92
+
93
+ def write_kv_data_to_file(self) -> None:
94
+ if self.state is not WriterState.HEADER:
95
+ raise ValueError(f'Expected output file to contain the header, got {self.state}')
96
+
97
+ self.fout.write(self.kv_data)
98
+ self.flush()
99
+ self.state = WriterState.KV_DATA
100
+
101
+ def write_ti_data_to_file(self) -> None:
102
+ if self.state is not WriterState.KV_DATA:
103
+ raise ValueError(f'Expected output file to contain KV data, got {self.state}')
104
+
105
+ self.fout.write(self.ti_data)
106
+ self.flush()
107
+ self.state = WriterState.TI_DATA
108
+
109
+ def add_key(self, key: str) -> None:
110
+ self.add_val(key, GGUFValueType.STRING, add_vtype=False)
111
+
112
+ def add_uint8(self, key: str, val: int) -> None:
113
+ self.add_key(key)
114
+ self.add_val(val, GGUFValueType.UINT8)
115
+
116
+ def add_int8(self, key: str, val: int) -> None:
117
+ self.add_key(key)
118
+ self.add_val(val, GGUFValueType.INT8)
119
+
120
+ def add_uint16(self, key: str, val: int) -> None:
121
+ self.add_key(key)
122
+ self.add_val(val, GGUFValueType.UINT16)
123
+
124
+ def add_int16(self, key: str, val: int) -> None:
125
+ self.add_key(key)
126
+ self.add_val(val, GGUFValueType.INT16)
127
+
128
+ def add_uint32(self, key: str, val: int) -> None:
129
+ self.add_key(key)
130
+ self.add_val(val, GGUFValueType.UINT32)
131
+
132
+ def add_int32(self, key: str, val: int) -> None:
133
+ self.add_key(key)
134
+ self.add_val(val, GGUFValueType.INT32)
135
+
136
+ def add_float32(self, key: str, val: float) -> None:
137
+ self.add_key(key)
138
+ self.add_val(val, GGUFValueType.FLOAT32)
139
+
140
+ def add_uint64(self, key: str, val: int) -> None:
141
+ self.add_key(key)
142
+ self.add_val(val, GGUFValueType.UINT64)
143
+
144
+ def add_int64(self, key: str, val: int) -> None:
145
+ self.add_key(key)
146
+ self.add_val(val, GGUFValueType.INT64)
147
+
148
+ def add_float64(self, key: str, val: float) -> None:
149
+ self.add_key(key)
150
+ self.add_val(val, GGUFValueType.FLOAT64)
151
+
152
+ def add_bool(self, key: str, val: bool) -> None:
153
+ self.add_key(key)
154
+ self.add_val(val, GGUFValueType.BOOL)
155
+
156
+ def add_string(self, key: str, val: str) -> None:
157
+ if not val:
158
+ return
159
+ self.add_key(key)
160
+ self.add_val(val, GGUFValueType.STRING)
161
+
162
+ def add_array(self, key: str, val: Sequence[Any]) -> None:
163
+ if not isinstance(val, Sequence):
164
+ raise ValueError("Value must be a sequence for array type")
165
+
166
+ self.add_key(key)
167
+ self.add_val(val, GGUFValueType.ARRAY)
168
+
169
+ def add_val(self, val: Any, vtype: GGUFValueType | None = None, add_vtype: bool = True) -> None:
170
+ if vtype is None:
171
+ vtype = GGUFValueType.get_type(val)
172
+
173
+ if add_vtype:
174
+ self.kv_data += self._pack("I", vtype)
175
+ self.kv_data_count += 1
176
+
177
+ pack_fmt = self._simple_value_packing.get(vtype)
178
+ if pack_fmt is not None:
179
+ self.kv_data += self._pack(pack_fmt, val, skip_pack_prefix = vtype == GGUFValueType.BOOL)
180
+ elif vtype == GGUFValueType.STRING:
181
+ encoded_val = val.encode("utf-8") if isinstance(val, str) else val
182
+ self.kv_data += self._pack("Q", len(encoded_val))
183
+ self.kv_data += encoded_val
184
+ elif vtype == GGUFValueType.ARRAY and isinstance(val, Sequence) and val:
185
+ ltype = GGUFValueType.get_type(val[0])
186
+ if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
187
+ raise ValueError("All items in a GGUF array should be of the same type")
188
+ self.kv_data += self._pack("I", ltype)
189
+ self.kv_data += self._pack("Q", len(val))
190
+ for item in val:
191
+ self.add_val(item, add_vtype=False)
192
+ else:
193
+ raise ValueError("Invalid GGUF metadata value type or value")
194
+
195
+ @staticmethod
196
+ def ggml_pad(x: int, n: int) -> int:
197
+ return ((x + n - 1) // n) * n
198
+
199
+ def add_tensor_info(
200
+ self, name: str, tensor_shape: Sequence[int], tensor_dtype: np.dtype,
201
+ tensor_nbytes: int, raw_dtype: GGMLQuantizationType | None = None,
202
+ ) -> None:
203
+ if self.state is not WriterState.EMPTY:
204
+ raise ValueError(f'Expected output file to be empty, got {self.state}')
205
+
206
+ if name in self.ti_names:
207
+ raise ValueError(f'Duplicated tensor name {name}')
208
+ self.ti_names.add(name)
209
+
210
+ encoded_name = name.encode("utf-8")
211
+ self.ti_data += self._pack("Q", len(encoded_name))
212
+ self.ti_data += encoded_name
213
+ if raw_dtype is None:
214
+ if tensor_dtype == np.float16:
215
+ dtype = GGMLQuantizationType.F16
216
+ elif tensor_dtype == np.float32:
217
+ dtype = GGMLQuantizationType.F32
218
+ elif tensor_dtype == np.float64:
219
+ dtype = GGMLQuantizationType.F64
220
+ elif tensor_dtype == np.int8:
221
+ dtype = GGMLQuantizationType.I8
222
+ elif tensor_dtype == np.int16:
223
+ dtype = GGMLQuantizationType.I16
224
+ elif tensor_dtype == np.int32:
225
+ dtype = GGMLQuantizationType.I32
226
+ elif tensor_dtype == np.int64:
227
+ dtype = GGMLQuantizationType.I64
228
+ else:
229
+ raise ValueError("Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now")
230
+ else:
231
+ dtype = raw_dtype
232
+ if tensor_dtype == np.uint8:
233
+ tensor_shape = quant_shape_from_byte_shape(tensor_shape, raw_dtype)
234
+ n_dims = len(tensor_shape)
235
+ self.ti_data += self._pack("I", n_dims)
236
+ for i in range(n_dims):
237
+ self.ti_data += self._pack("Q", tensor_shape[n_dims - 1 - i])
238
+ self.ti_data += self._pack("I", dtype)
239
+ self.ti_data += self._pack("Q", self.offset_tensor)
240
+ self.offset_tensor += GGUFWriter.ggml_pad(tensor_nbytes, self.data_alignment)
241
+ self.ti_data_count += 1
242
+
243
+ def add_tensor(
244
+ self, name: str, tensor: np.ndarray[Any, Any], raw_shape: Sequence[int] | None = None,
245
+ raw_dtype: GGMLQuantizationType | None = None,
246
+ ) -> None:
247
+ if self.endianess == GGUFEndian.BIG:
248
+ tensor.byteswap(inplace=True)
249
+ if self.use_temp_file and self.temp_file is None:
250
+ fp = tempfile.SpooledTemporaryFile(mode="w+b", max_size=256 * 1024 * 1024)
251
+ fp.seek(0)
252
+ self.temp_file = fp
253
+
254
+ shape: Sequence[int] = raw_shape if raw_shape is not None else tensor.shape
255
+ self.add_tensor_info(name, shape, tensor.dtype, tensor.nbytes, raw_dtype = raw_dtype)
256
+
257
+ if self.temp_file is None:
258
+ self.tensors.append(tensor)
259
+ return
260
+
261
+ tensor.tofile(self.temp_file)
262
+ self.write_padding(self.temp_file, tensor.nbytes)
263
+
264
+ def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
265
+ pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
266
+ if pad != 0:
267
+ fp.write(bytes([0] * pad))
268
+
269
+ def write_tensor_data(self, tensor: np.ndarray[Any, Any]) -> None:
270
+ if self.state is not WriterState.TI_DATA:
271
+ raise ValueError(f'Expected output file to contain tensor info, got {self.state}')
272
+
273
+ if self.endianess == GGUFEndian.BIG:
274
+ tensor.byteswap(inplace=True)
275
+ self.write_padding(self.fout, self.fout.tell())
276
+ tensor.tofile(self.fout)
277
+ self.write_padding(self.fout, tensor.nbytes)
278
+
279
+ def write_tensors_to_file(self, *, progress: bool = False) -> None:
280
+ self.write_ti_data_to_file()
281
+
282
+ self.write_padding(self.fout, self.fout.tell())
283
+
284
+ if self.temp_file is None:
285
+ self.tensors.reverse() # to pop from the "beginning" in constant time
286
+
287
+ if progress:
288
+ from tqdm import tqdm
289
+
290
+ total_bytes = sum(t.nbytes for t in self.tensors)
291
+
292
+ bar = tqdm(desc="Writing", total=total_bytes, unit="byte", unit_scale=True)
293
+
294
+ while True:
295
+ try:
296
+ tensor = self.tensors.pop()
297
+ except IndexError:
298
+ break
299
+ tensor.tofile(self.fout)
300
+ bar.update(tensor.nbytes)
301
+ self.write_padding(self.fout, tensor.nbytes)
302
+ return
303
+ while True:
304
+ try:
305
+ tensor = self.tensors.pop()
306
+ except IndexError:
307
+ break
308
+ tensor.tofile(self.fout)
309
+ self.write_padding(self.fout, tensor.nbytes)
310
+ return
311
+
312
+ self.temp_file.seek(0)
313
+
314
+ shutil.copyfileobj(self.temp_file, self.fout)
315
+ self.flush()
316
+ self.temp_file.close()
317
+
318
+ def flush(self) -> None:
319
+ self.fout.flush()
320
+
321
+ def close(self) -> None:
322
+ self.fout.close()
323
+
324
+ def add_architecture(self) -> None:
325
+ self.add_string(Keys.General.ARCHITECTURE, self.arch)
326
+
327
+ def add_author(self, author: str) -> None:
328
+ self.add_string(Keys.General.AUTHOR, author)
329
+
330
+ def add_version(self, version: str) -> None:
331
+ self.add_string(Keys.General.VERSION, version)
332
+
333
+ def add_tensor_data_layout(self, layout: str) -> None:
334
+ self.add_string(Keys.LLM.TENSOR_DATA_LAYOUT.format(arch=self.arch), layout)
335
+
336
+ def add_url(self, url: str) -> None:
337
+ self.add_string(Keys.General.URL, url)
338
+
339
+ def add_description(self, description: str) -> None:
340
+ self.add_string(Keys.General.DESCRIPTION, description)
341
+
342
+ def add_licence(self, licence: str) -> None:
343
+ self.add_string(Keys.General.LICENSE, licence)
344
+
345
+ def add_source_url(self, url: str) -> None:
346
+ self.add_string(Keys.General.SOURCE_URL, url)
347
+
348
+ def add_source_hf_repo(self, repo: str) -> None:
349
+ self.add_string(Keys.General.SOURCE_HF_REPO, repo)
350
+
351
+ def add_file_type(self, ftype: int) -> None:
352
+ self.add_uint32(Keys.General.FILE_TYPE, ftype)
353
+
354
+ def add_name(self, name: str) -> None:
355
+ self.add_string(Keys.General.NAME, name)
356
+
357
+ def add_quantization_version(self, quantization_version: int) -> None:
358
+ self.add_uint32(
359
+ Keys.General.QUANTIZATION_VERSION, quantization_version)
360
+
361
+ def add_custom_alignment(self, alignment: int) -> None:
362
+ self.data_alignment = alignment
363
+ self.add_uint32(Keys.General.ALIGNMENT, alignment)
364
+
365
+ def add_vocab_size(self, size: int) -> None:
366
+ self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)
367
+
368
+ def add_context_length(self, length: int) -> None:
369
+ self.add_uint32(Keys.LLM.CONTEXT_LENGTH.format(arch=self.arch), length)
370
+
371
+ def add_embedding_length(self, length: int) -> None:
372
+ self.add_uint32(Keys.LLM.EMBEDDING_LENGTH.format(arch=self.arch), length)
373
+
374
+ def add_block_count(self, length: int) -> None:
375
+ self.add_uint32(Keys.LLM.BLOCK_COUNT.format(arch=self.arch), length)
376
+
377
+ def add_feed_forward_length(self, length: int) -> None:
378
+ self.add_uint32(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
379
+
380
+ def add_parallel_residual(self, use: bool) -> None:
381
+ self.add_bool(Keys.LLM.USE_PARALLEL_RESIDUAL.format(arch=self.arch), use)
382
+
383
+ def add_head_count(self, count: int) -> None:
384
+ self.add_uint32(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
385
+
386
+ def add_head_count_kv(self, count: int) -> None:
387
+ self.add_uint32(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
388
+
389
+ def add_key_length(self, length: int) -> None:
390
+ self.add_uint32(Keys.Attention.KEY_LENGTH.format(arch=self.arch), length)
391
+
392
+ def add_value_length(self, length: int) -> None:
393
+ self.add_uint32(Keys.Attention.VALUE_LENGTH.format(arch=self.arch), length)
394
+
395
+ def add_max_alibi_bias(self, bias: float) -> None:
396
+ self.add_float32(Keys.Attention.MAX_ALIBI_BIAS.format(arch=self.arch), bias)
397
+
398
+ def add_clamp_kqv(self, value: float) -> None:
399
+ self.add_float32(Keys.Attention.CLAMP_KQV.format(arch=self.arch), value)
400
+
401
+ def add_logit_scale(self, value: float) -> None:
402
+ self.add_float32(Keys.LLM.LOGIT_SCALE.format(arch=self.arch), value)
403
+
404
+ def add_expert_count(self, count: int) -> None:
405
+ self.add_uint32(Keys.LLM.EXPERT_COUNT.format(arch=self.arch), count)
406
+
407
+ def add_expert_used_count(self, count: int) -> None:
408
+ self.add_uint32(Keys.LLM.EXPERT_USED_COUNT.format(arch=self.arch), count)
409
+
410
+ def add_layer_norm_eps(self, value: float) -> None:
411
+ self.add_float32(Keys.Attention.LAYERNORM_EPS.format(arch=self.arch), value)
412
+
413
+ def add_layer_norm_rms_eps(self, value: float) -> None:
414
+ self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
415
+
416
+ def add_causal_attention(self, value: bool) -> None:
417
+ self.add_bool(Keys.Attention.CAUSAL.format(arch=self.arch), value)
418
+
419
+ def add_pooling_type(self, value: PoolingType) -> None:
420
+ self.add_uint32(Keys.LLM.POOLING_TYPE.format(arch=self.arch), value.value)
421
+
422
+ def add_rope_dimension_count(self, count: int) -> None:
423
+ self.add_uint32(Keys.Rope.DIMENSION_COUNT.format(arch=self.arch), count)
424
+
425
+ def add_rope_freq_base(self, value: float) -> None:
426
+ self.add_float32(Keys.Rope.FREQ_BASE.format(arch=self.arch), value)
427
+
428
+ def add_rope_scaling_type(self, value: RopeScalingType) -> None:
429
+ self.add_string(Keys.Rope.SCALING_TYPE.format(arch=self.arch), value.value)
430
+
431
+ def add_rope_scaling_factor(self, value: float) -> None:
432
+ self.add_float32(Keys.Rope.SCALING_FACTOR.format(arch=self.arch), value)
433
+
434
+ def add_rope_scaling_attn_factors(self, value: Sequence[float]) -> None:
435
+ self.add_float32(Keys.Rope.SCALING_ATTN_FACTOR.format(arch=self.arch), value)
436
+
437
+ def add_rope_scaling_orig_ctx_len(self, value: int) -> None:
438
+ self.add_uint32(Keys.Rope.SCALING_ORIG_CTX_LEN.format(arch=self.arch), value)
439
+
440
+ def add_rope_scaling_finetuned(self, value: bool) -> None:
441
+ self.add_bool(Keys.Rope.SCALING_FINETUNED.format(arch=self.arch), value)
442
+
443
+ def add_ssm_conv_kernel(self, value: int) -> None:
444
+ self.add_uint32(Keys.SSM.CONV_KERNEL.format(arch=self.arch), value)
445
+
446
+ def add_ssm_inner_size(self, value: int) -> None:
447
+ self.add_uint32(Keys.SSM.INNER_SIZE.format(arch=self.arch), value)
448
+
449
+ def add_ssm_state_size(self, value: int) -> None:
450
+ self.add_uint32(Keys.SSM.STATE_SIZE.format(arch=self.arch), value)
451
+
452
+ def add_ssm_time_step_rank(self, value: int) -> None:
453
+ self.add_uint32(Keys.SSM.TIME_STEP_RANK.format(arch=self.arch), value)
454
+
455
+ def add_tokenizer_model(self, model: str) -> None:
456
+ self.add_string(Keys.Tokenizer.MODEL, model)
457
+
458
+ def add_tokenizer_pre(self, pre: str) -> None:
459
+ self.add_string(Keys.Tokenizer.PRE, pre)
460
+
461
+ def add_token_list(self, tokens: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
462
+ self.add_array(Keys.Tokenizer.LIST, tokens)
463
+
464
+ def add_token_merges(self, merges: Sequence[str] | Sequence[bytes] | Sequence[bytearray]) -> None:
465
+ self.add_array(Keys.Tokenizer.MERGES, merges)
466
+
467
+ def add_token_types(self, types: Sequence[TokenType] | Sequence[int]) -> None:
468
+ self.add_array(Keys.Tokenizer.TOKEN_TYPE, types)
469
+
470
+ def add_token_type_count(self, value: int) -> None:
471
+ self.add_uint32(Keys.Tokenizer.TOKEN_TYPE_COUNT, value)
472
+
473
+ def add_token_scores(self, scores: Sequence[float]) -> None:
474
+ self.add_array(Keys.Tokenizer.SCORES, scores)
475
+
476
+ def add_bos_token_id(self, id: int) -> None:
477
+ self.add_uint32(Keys.Tokenizer.BOS_ID, id)
478
+
479
+ def add_eos_token_id(self, id: int) -> None:
480
+ self.add_uint32(Keys.Tokenizer.EOS_ID, id)
481
+
482
+ def add_unk_token_id(self, id: int) -> None:
483
+ self.add_uint32(Keys.Tokenizer.UNK_ID, id)
484
+
485
+ def add_sep_token_id(self, id: int) -> None:
486
+ self.add_uint32(Keys.Tokenizer.SEP_ID, id)
487
+
488
+ def add_pad_token_id(self, id: int) -> None:
489
+ self.add_uint32(Keys.Tokenizer.PAD_ID, id)
490
+
491
+ def add_cls_token_id(self, id: int) -> None:
492
+ self.add_uint32(Keys.Tokenizer.CLS_ID, id)
493
+
494
+ def add_mask_token_id(self, id: int) -> None:
495
+ self.add_uint32(Keys.Tokenizer.MASK_ID, id)
496
+
497
+ def add_add_bos_token(self, value: bool) -> None:
498
+ self.add_bool(Keys.Tokenizer.ADD_BOS, value)
499
+
500
+ def add_add_eos_token(self, value: bool) -> None:
501
+ self.add_bool(Keys.Tokenizer.ADD_EOS, value)
502
+
503
+ def add_add_space_prefix(self, value: bool) -> None:
504
+ self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)
505
+
506
+ def add_chat_template(self, value: str | Sequence[Mapping[str, str]]) -> None:
507
+ if not isinstance(value, str):
508
+ template_default = None
509
+ template_names = set()
510
+
511
+ for choice in value:
512
+ name = choice.get('name', '')
513
+ template = choice.get('template')
514
+
515
+ # Allowing non-alphanumerical characters in template name is probably not a good idea, so filter it
516
+ name = ''.join((c if c in ascii_letters + digits else '_' for c in name))
517
+
518
+ if name and template is not None:
519
+ if name == 'default':
520
+ template_default = template
521
+ else:
522
+ template_names.add(name)
523
+ self.add_string(Keys.Tokenizer.CHAT_TEMPLATE_N.format(name=name), template)
524
+
525
+ if template_names:
526
+ self.add_array(Keys.Tokenizer.CHAT_TEMPLATES, list(template_names))
527
+
528
+ if template_default is None:
529
+ return
530
+
531
+ value = template_default
532
+
533
+ self.add_string(Keys.Tokenizer.CHAT_TEMPLATE, value)
534
+
535
+ def add_prefix_token_id(self, id: int) -> None:
536
+ self.add_uint32(Keys.Tokenizer.PREFIX_ID, id)
537
+
538
+ def add_suffix_token_id(self, id: int) -> None:
539
+ self.add_uint32(Keys.Tokenizer.SUFFIX_ID, id)
540
+
541
+ def add_middle_token_id(self, id: int) -> None:
542
+ self.add_uint32(Keys.Tokenizer.MIDDLE_ID, id)
543
+
544
+ def add_eot_token_id(self, id: int) -> None:
545
+ self.add_uint32(Keys.Tokenizer.EOT_ID, id)
546
+
547
+ def _pack(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> bytes:
548
+ pack_prefix = ''
549
+ if not skip_pack_prefix:
550
+ pack_prefix = '<' if self.endianess == GGUFEndian.LITTLE else '>'
551
+ return struct.pack(f'{pack_prefix}{fmt}', value)
552
+
553
+ def _write_packed(self, fmt: str, value: Any, skip_pack_prefix: bool = False) -> None:
554
+ self.fout.write(self._pack(fmt, value, skip_pack_prefix))