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