bigdl-core-cpp 2.5.0b20240724__py3-none-win_amd64.whl → 2.5.0b20240726__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.
- bigdl/cpp/convert-hf-to-gguf.py +1148 -315
- bigdl/cpp/gguf-py/gguf/__init__.py +2 -0
- bigdl/cpp/gguf-py/gguf/constants.py +463 -167
- bigdl/cpp/gguf-py/gguf/gguf.py +1 -1
- bigdl/cpp/gguf-py/gguf/gguf_reader.py +29 -8
- bigdl/cpp/gguf-py/gguf/gguf_writer.py +475 -156
- bigdl/cpp/gguf-py/gguf/lazy.py +24 -49
- bigdl/cpp/gguf-py/gguf/tensor_mapping.py +209 -23
- bigdl/cpp/libs/baby-llama.exe +0 -0
- bigdl/cpp/libs/batched-bench.exe +0 -0
- bigdl/cpp/libs/batched.exe +0 -0
- bigdl/cpp/libs/beam-search.exe +0 -0
- bigdl/cpp/libs/benchmark.exe +0 -0
- bigdl/cpp/libs/common.lib +0 -0
- bigdl/cpp/libs/convert-llama2c-to-ggml.exe +0 -0
- bigdl/cpp/libs/dist/windows-amd64/ollama_runners/cpu/ollama_llama_server.exe +0 -0
- bigdl/cpp/libs/dist/windows-amd64/ollama_runners/cpu_avx/ollama_llama_server.exe +0 -0
- bigdl/cpp/libs/dist/windows-amd64/ollama_runners/cpu_avx2/ollama_llama_server.exe +0 -0
- bigdl/cpp/libs/embedding.exe +0 -0
- bigdl/cpp/libs/export-lora.exe +0 -0
- bigdl/cpp/libs/finetune.exe +0 -0
- bigdl/cpp/libs/ggml_shared.dll +0 -0
- bigdl/cpp/libs/gguf.exe +0 -0
- bigdl/cpp/libs/gritlm.exe +0 -0
- bigdl/cpp/libs/imatrix.exe +0 -0
- bigdl/cpp/libs/infill.exe +0 -0
- bigdl/cpp/libs/llama-bench.exe +0 -0
- bigdl/cpp/libs/llama.dll +0 -0
- bigdl/cpp/libs/llava-cli.exe +0 -0
- bigdl/cpp/libs/llava_shared.dll +0 -0
- bigdl/cpp/libs/lookahead.exe +0 -0
- bigdl/cpp/libs/lookup.exe +0 -0
- bigdl/cpp/libs/ls-sycl-device.exe +0 -0
- bigdl/cpp/libs/main.exe +0 -0
- bigdl/cpp/libs/ollama.exe +0 -0
- bigdl/cpp/libs/parallel.exe +0 -0
- bigdl/cpp/libs/passkey.exe +0 -0
- bigdl/cpp/libs/perplexity.exe +0 -0
- bigdl/cpp/libs/q8dot.exe +0 -0
- bigdl/cpp/libs/quantize-stats.exe +0 -0
- bigdl/cpp/libs/quantize.exe +0 -0
- bigdl/cpp/libs/save-load-state.exe +0 -0
- bigdl/cpp/libs/server.exe +0 -0
- bigdl/cpp/libs/simple.exe +0 -0
- bigdl/cpp/libs/speculative.exe +0 -0
- bigdl/cpp/libs/tokenize.exe +0 -0
- bigdl/cpp/libs/train-text-from-scratch.exe +0 -0
- bigdl/cpp/libs/vdot.exe +0 -0
- {bigdl_core_cpp-2.5.0b20240724.dist-info → bigdl_core_cpp-2.5.0b20240726.dist-info}/METADATA +1 -1
- bigdl_core_cpp-2.5.0b20240726.dist-info/RECORD +61 -0
- bigdl_core_cpp-2.5.0b20240724.dist-info/RECORD +0 -61
- {bigdl_core_cpp-2.5.0b20240724.data → bigdl_core_cpp-2.5.0b20240726.data}/scripts/init-llama-cpp.bat +0 -0
- {bigdl_core_cpp-2.5.0b20240724.data → bigdl_core_cpp-2.5.0b20240726.data}/scripts/init-llama-cpp.ps1 +0 -0
- {bigdl_core_cpp-2.5.0b20240724.data → bigdl_core_cpp-2.5.0b20240726.data}/scripts/init-ollama.bat +0 -0
- {bigdl_core_cpp-2.5.0b20240724.dist-info → bigdl_core_cpp-2.5.0b20240726.dist-info}/WHEEL +0 -0
- {bigdl_core_cpp-2.5.0b20240724.dist-info → bigdl_core_cpp-2.5.0b20240726.dist-info}/top_level.txt +0 -0
@@ -5,7 +5,10 @@ import os
|
|
5
5
|
import shutil
|
6
6
|
import struct
|
7
7
|
import tempfile
|
8
|
+
from dataclasses import dataclass
|
8
9
|
from enum import Enum, auto
|
10
|
+
from math import prod
|
11
|
+
from pathlib import Path
|
9
12
|
from io import BufferedWriter
|
10
13
|
from typing import IO, Any, Sequence, Mapping
|
11
14
|
from string import ascii_letters, digits
|
@@ -30,17 +33,39 @@ from .quants import quant_shape_from_byte_shape
|
|
30
33
|
logger = logging.getLogger(__name__)
|
31
34
|
|
32
35
|
|
36
|
+
SHARD_NAME_FORMAT = "{:s}-{:05d}-of-{:05d}.gguf"
|
37
|
+
|
38
|
+
|
39
|
+
@dataclass
|
40
|
+
class TensorInfo:
|
41
|
+
shape: Sequence[int]
|
42
|
+
dtype: GGMLQuantizationType
|
43
|
+
nbytes: int
|
44
|
+
tensor: np.ndarray[Any, Any] | None = None
|
45
|
+
|
46
|
+
|
47
|
+
@dataclass
|
48
|
+
class GGUFValue:
|
49
|
+
value: Any
|
50
|
+
type: GGUFValueType
|
51
|
+
|
52
|
+
|
33
53
|
class WriterState(Enum):
|
54
|
+
NO_FILE = auto()
|
34
55
|
EMPTY = auto()
|
35
56
|
HEADER = auto()
|
36
57
|
KV_DATA = auto()
|
37
58
|
TI_DATA = auto()
|
59
|
+
WEIGHTS = auto()
|
38
60
|
|
39
61
|
|
40
62
|
class GGUFWriter:
|
41
|
-
fout: BufferedWriter
|
63
|
+
fout: list[BufferedWriter] | None
|
64
|
+
path: Path | None
|
42
65
|
temp_file: tempfile.SpooledTemporaryFile[bytes] | None
|
43
|
-
tensors: list[
|
66
|
+
tensors: list[dict[str, TensorInfo]]
|
67
|
+
kv_data: list[dict[str, GGUFValue]]
|
68
|
+
state: WriterState
|
44
69
|
_simple_value_packing = {
|
45
70
|
GGUFValueType.UINT8: "B",
|
46
71
|
GGUFValueType.INT8: "b",
|
@@ -56,141 +81,238 @@ class GGUFWriter:
|
|
56
81
|
}
|
57
82
|
|
58
83
|
def __init__(
|
59
|
-
self, path: os.PathLike[str] | str, arch: str, use_temp_file: bool =
|
60
|
-
|
84
|
+
self, path: os.PathLike[str] | str | None, arch: str, use_temp_file: bool = False, endianess: GGUFEndian = GGUFEndian.LITTLE,
|
85
|
+
split_max_tensors: int = 0, split_max_size: int = 0, dry_run: bool = False, small_first_shard: bool = False
|
61
86
|
):
|
62
|
-
self.fout =
|
87
|
+
self.fout = None
|
88
|
+
self.path = Path(path) if path else None
|
63
89
|
self.arch = arch
|
64
90
|
self.endianess = endianess
|
65
|
-
self.offset_tensor = 0
|
66
91
|
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
92
|
self.use_temp_file = use_temp_file
|
73
93
|
self.temp_file = None
|
74
|
-
self.tensors = []
|
94
|
+
self.tensors = [{}]
|
95
|
+
self.kv_data = [{}]
|
96
|
+
self.split_max_tensors = split_max_tensors
|
97
|
+
self.split_max_size = split_max_size
|
98
|
+
self.dry_run = dry_run
|
99
|
+
self.small_first_shard = small_first_shard
|
75
100
|
logger.info("gguf: This GGUF file is for {0} Endian only".format(
|
76
101
|
"Big" if self.endianess == GGUFEndian.BIG else "Little",
|
77
102
|
))
|
78
|
-
self.state = WriterState.
|
103
|
+
self.state = WriterState.NO_FILE
|
104
|
+
|
105
|
+
if self.small_first_shard:
|
106
|
+
self.tensors.append({})
|
79
107
|
|
80
108
|
self.add_architecture()
|
81
109
|
|
82
|
-
def
|
110
|
+
def get_total_parameter_count(self) -> tuple[int, int, int, int]:
|
111
|
+
total_params = 0
|
112
|
+
shared_params = 0
|
113
|
+
expert_params = 0
|
114
|
+
|
115
|
+
expert_sum = 0
|
116
|
+
n_expert_tensors = 0
|
117
|
+
|
118
|
+
last_lora_a: tuple[str, TensorInfo] | None = None
|
119
|
+
|
120
|
+
for tensors in self.tensors:
|
121
|
+
for name, info in tensors.items():
|
122
|
+
|
123
|
+
shape = info.shape
|
124
|
+
|
125
|
+
if name.endswith(".lora_a"):
|
126
|
+
last_lora_a = (name, info)
|
127
|
+
continue
|
128
|
+
elif name.endswith(".lora_b"):
|
129
|
+
if last_lora_a is None or last_lora_a[0] != name[:-1] + "a":
|
130
|
+
# Bail when the LoRA pair can't be found trivially
|
131
|
+
logger.warning("can't measure LoRA size correctly, tensor order is unusual")
|
132
|
+
return 0, 0, 0, 0
|
133
|
+
else:
|
134
|
+
shape = (*shape[:-1], last_lora_a[1].shape[-1])
|
135
|
+
|
136
|
+
size = prod(shape)
|
137
|
+
|
138
|
+
if "_exps." in name:
|
139
|
+
expert_params += (size // shape[-3])
|
140
|
+
expert_sum += shape[-3]
|
141
|
+
n_expert_tensors += 1
|
142
|
+
else:
|
143
|
+
shared_params += size
|
144
|
+
|
145
|
+
total_params += size
|
146
|
+
|
147
|
+
# Hopefully this should work even for variable-expert-count models
|
148
|
+
expert_count = (expert_sum // n_expert_tensors) if n_expert_tensors > 0 else 0
|
149
|
+
|
150
|
+
# Negate the total to signal it's likely not exact
|
151
|
+
if last_lora_a is not None:
|
152
|
+
total_params = -total_params
|
153
|
+
|
154
|
+
# NOTE: keep the output in the same order as accepted by 'size_label' in gguf-py/gguf/utility.py
|
155
|
+
return total_params, shared_params, expert_params, expert_count
|
156
|
+
|
157
|
+
def format_shard_names(self, path: Path) -> list[Path]:
|
158
|
+
if len(self.tensors) == 1:
|
159
|
+
return [path]
|
160
|
+
return [path.with_name(SHARD_NAME_FORMAT.format(path.stem, i + 1, len(self.tensors))) for i in range(len(self.tensors))]
|
161
|
+
|
162
|
+
def open_output_file(self, path: Path | None = None) -> None:
|
163
|
+
if self.state is WriterState.EMPTY and self.fout is not None and (path is None or path == self.path):
|
164
|
+
# allow calling this multiple times as long as the path is the same
|
165
|
+
return
|
166
|
+
|
167
|
+
if self.state is not WriterState.NO_FILE:
|
168
|
+
raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
|
169
|
+
|
170
|
+
if path is not None:
|
171
|
+
self.path = path
|
172
|
+
|
173
|
+
if self.path is not None:
|
174
|
+
filenames = self.print_plan()
|
175
|
+
self.fout = [open(filename, "wb") for filename in filenames]
|
176
|
+
self.state = WriterState.EMPTY
|
177
|
+
|
178
|
+
def print_plan(self) -> list[Path]:
|
179
|
+
logger.info("Writing the following files:")
|
180
|
+
assert self.path is not None
|
181
|
+
filenames = self.format_shard_names(self.path)
|
182
|
+
assert len(filenames) == len(self.tensors)
|
183
|
+
for name, tensors in zip(filenames, self.tensors):
|
184
|
+
logger.info(f"{name}: n_tensors = {len(tensors)}, total_size = {GGUFWriter.format_n_bytes_to_str(sum(ti.nbytes for ti in tensors.values()))}")
|
185
|
+
|
186
|
+
if self.dry_run:
|
187
|
+
logger.info("Dry run, not writing files")
|
188
|
+
for name in filenames:
|
189
|
+
print(name) # noqa: NP100
|
190
|
+
exit()
|
191
|
+
|
192
|
+
return filenames
|
193
|
+
|
194
|
+
def add_shard_kv_data(self) -> None:
|
195
|
+
if len(self.tensors) == 1:
|
196
|
+
return
|
197
|
+
|
198
|
+
total_tensors = sum(len(t) for t in self.tensors)
|
199
|
+
assert self.fout is not None
|
200
|
+
total_splits = len(self.fout)
|
201
|
+
self.kv_data.extend({} for _ in range(len(self.kv_data), total_splits))
|
202
|
+
for i, kv_data in enumerate(self.kv_data):
|
203
|
+
kv_data[Keys.Split.LLM_KV_SPLIT_NO] = GGUFValue(i, GGUFValueType.UINT16)
|
204
|
+
kv_data[Keys.Split.LLM_KV_SPLIT_COUNT] = GGUFValue(total_splits, GGUFValueType.UINT16)
|
205
|
+
kv_data[Keys.Split.LLM_KV_SPLIT_TENSORS_COUNT] = GGUFValue(total_tensors, GGUFValueType.INT32)
|
206
|
+
|
207
|
+
def write_header_to_file(self, path: Path | None = None) -> None:
|
208
|
+
if len(self.tensors) == 1 and (self.split_max_tensors != 0 or self.split_max_size != 0):
|
209
|
+
logger.warning("Model fails split requirements, not splitting")
|
210
|
+
|
211
|
+
self.open_output_file(path)
|
212
|
+
|
83
213
|
if self.state is not WriterState.EMPTY:
|
84
214
|
raise ValueError(f'Expected output file to be empty, got {self.state}')
|
85
215
|
|
86
|
-
self.
|
87
|
-
self.
|
88
|
-
|
89
|
-
|
90
|
-
self.
|
216
|
+
assert self.fout is not None
|
217
|
+
assert len(self.fout) == len(self.tensors)
|
218
|
+
assert len(self.kv_data) == 1
|
219
|
+
|
220
|
+
self.add_shard_kv_data()
|
221
|
+
|
222
|
+
for fout, tensors, kv_data in zip(self.fout, self.tensors, self.kv_data):
|
223
|
+
fout.write(self._pack("<I", GGUF_MAGIC, skip_pack_prefix = True))
|
224
|
+
fout.write(self._pack("I", GGUF_VERSION))
|
225
|
+
fout.write(self._pack("Q", len(tensors)))
|
226
|
+
fout.write(self._pack("Q", len(kv_data)))
|
227
|
+
fout.flush()
|
91
228
|
self.state = WriterState.HEADER
|
92
229
|
|
93
230
|
def write_kv_data_to_file(self) -> None:
|
94
231
|
if self.state is not WriterState.HEADER:
|
95
232
|
raise ValueError(f'Expected output file to contain the header, got {self.state}')
|
233
|
+
assert self.fout is not None
|
234
|
+
|
235
|
+
for fout, kv_data in zip(self.fout, self.kv_data):
|
236
|
+
kv_bytes = bytearray()
|
237
|
+
|
238
|
+
for key, val in kv_data.items():
|
239
|
+
kv_bytes += self._pack_val(key, GGUFValueType.STRING, add_vtype=False)
|
240
|
+
kv_bytes += self._pack_val(val.value, val.type, add_vtype=True)
|
241
|
+
|
242
|
+
fout.write(kv_bytes)
|
96
243
|
|
97
|
-
self.fout.write(self.kv_data)
|
98
244
|
self.flush()
|
99
245
|
self.state = WriterState.KV_DATA
|
100
246
|
|
101
247
|
def write_ti_data_to_file(self) -> None:
|
102
248
|
if self.state is not WriterState.KV_DATA:
|
103
249
|
raise ValueError(f'Expected output file to contain KV data, got {self.state}')
|
104
|
-
|
105
|
-
|
106
|
-
self.
|
250
|
+
assert self.fout is not None
|
251
|
+
|
252
|
+
for fout, tensors in zip(self.fout, self.tensors):
|
253
|
+
ti_data = bytearray()
|
254
|
+
offset_tensor = 0
|
255
|
+
|
256
|
+
for name, ti in tensors.items():
|
257
|
+
ti_data += self._pack_val(name, GGUFValueType.STRING, add_vtype=False)
|
258
|
+
n_dims = len(ti.shape)
|
259
|
+
ti_data += self._pack("I", n_dims)
|
260
|
+
for j in range(n_dims):
|
261
|
+
ti_data += self._pack("Q", ti.shape[n_dims - 1 - j])
|
262
|
+
ti_data += self._pack("I", ti.dtype)
|
263
|
+
ti_data += self._pack("Q", offset_tensor)
|
264
|
+
offset_tensor += GGUFWriter.ggml_pad(ti.nbytes, self.data_alignment)
|
265
|
+
|
266
|
+
fout.write(ti_data)
|
267
|
+
fout.flush()
|
107
268
|
self.state = WriterState.TI_DATA
|
108
269
|
|
109
|
-
def
|
110
|
-
|
270
|
+
def add_key_value(self, key: str, val: Any, vtype: GGUFValueType) -> None:
|
271
|
+
if any(key in kv_data for kv_data in self.kv_data):
|
272
|
+
raise ValueError(f'Duplicated key name {key!r}')
|
273
|
+
|
274
|
+
self.kv_data[0][key] = GGUFValue(value=val, type=vtype)
|
111
275
|
|
112
276
|
def add_uint8(self, key: str, val: int) -> None:
|
113
|
-
self.
|
114
|
-
self.add_val(val, GGUFValueType.UINT8)
|
277
|
+
self.add_key_value(key,val, GGUFValueType.UINT8)
|
115
278
|
|
116
279
|
def add_int8(self, key: str, val: int) -> None:
|
117
|
-
self.
|
118
|
-
self.add_val(val, GGUFValueType.INT8)
|
280
|
+
self.add_key_value(key, val, GGUFValueType.INT8)
|
119
281
|
|
120
282
|
def add_uint16(self, key: str, val: int) -> None:
|
121
|
-
self.
|
122
|
-
self.add_val(val, GGUFValueType.UINT16)
|
283
|
+
self.add_key_value(key, val, GGUFValueType.UINT16)
|
123
284
|
|
124
285
|
def add_int16(self, key: str, val: int) -> None:
|
125
|
-
self.
|
126
|
-
self.add_val(val, GGUFValueType.INT16)
|
286
|
+
self.add_key_value(key, val, GGUFValueType.INT16)
|
127
287
|
|
128
288
|
def add_uint32(self, key: str, val: int) -> None:
|
129
|
-
self.
|
130
|
-
self.add_val(val, GGUFValueType.UINT32)
|
289
|
+
self.add_key_value(key, val, GGUFValueType.UINT32)
|
131
290
|
|
132
291
|
def add_int32(self, key: str, val: int) -> None:
|
133
|
-
self.
|
134
|
-
self.add_val(val, GGUFValueType.INT32)
|
292
|
+
self.add_key_value(key, val, GGUFValueType.INT32)
|
135
293
|
|
136
294
|
def add_float32(self, key: str, val: float) -> None:
|
137
|
-
self.
|
138
|
-
self.add_val(val, GGUFValueType.FLOAT32)
|
295
|
+
self.add_key_value(key, val, GGUFValueType.FLOAT32)
|
139
296
|
|
140
297
|
def add_uint64(self, key: str, val: int) -> None:
|
141
|
-
self.
|
142
|
-
self.add_val(val, GGUFValueType.UINT64)
|
298
|
+
self.add_key_value(key, val, GGUFValueType.UINT64)
|
143
299
|
|
144
300
|
def add_int64(self, key: str, val: int) -> None:
|
145
|
-
self.
|
146
|
-
self.add_val(val, GGUFValueType.INT64)
|
301
|
+
self.add_key_value(key, val, GGUFValueType.INT64)
|
147
302
|
|
148
303
|
def add_float64(self, key: str, val: float) -> None:
|
149
|
-
self.
|
150
|
-
self.add_val(val, GGUFValueType.FLOAT64)
|
304
|
+
self.add_key_value(key, val, GGUFValueType.FLOAT64)
|
151
305
|
|
152
306
|
def add_bool(self, key: str, val: bool) -> None:
|
153
|
-
self.
|
154
|
-
self.add_val(val, GGUFValueType.BOOL)
|
307
|
+
self.add_key_value(key, val, GGUFValueType.BOOL)
|
155
308
|
|
156
309
|
def add_string(self, key: str, val: str) -> None:
|
157
310
|
if not val:
|
158
311
|
return
|
159
|
-
self.
|
160
|
-
self.add_val(val, GGUFValueType.STRING)
|
312
|
+
self.add_key_value(key, val, GGUFValueType.STRING)
|
161
313
|
|
162
314
|
def add_array(self, key: str, val: Sequence[Any]) -> None:
|
163
|
-
|
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")
|
315
|
+
self.add_key_value(key, val, GGUFValueType.ARRAY)
|
194
316
|
|
195
317
|
@staticmethod
|
196
318
|
def ggml_pad(x: int, n: int) -> int:
|
@@ -200,16 +322,12 @@ class GGUFWriter:
|
|
200
322
|
self, name: str, tensor_shape: Sequence[int], tensor_dtype: np.dtype,
|
201
323
|
tensor_nbytes: int, raw_dtype: GGMLQuantizationType | None = None,
|
202
324
|
) -> None:
|
203
|
-
if self.state is not WriterState.
|
204
|
-
raise ValueError(f'Expected output file to be
|
325
|
+
if self.state is not WriterState.NO_FILE:
|
326
|
+
raise ValueError(f'Expected output file to be not yet opened, got {self.state}')
|
205
327
|
|
206
|
-
if name in self.
|
207
|
-
raise ValueError(f'Duplicated tensor name {name}')
|
208
|
-
self.ti_names.add(name)
|
328
|
+
if any(name in tensors for tensors in self.tensors):
|
329
|
+
raise ValueError(f'Duplicated tensor name {name!r}')
|
209
330
|
|
210
|
-
encoded_name = name.encode("utf-8")
|
211
|
-
self.ti_data += self._pack("Q", len(encoded_name))
|
212
|
-
self.ti_data += encoded_name
|
213
331
|
if raw_dtype is None:
|
214
332
|
if tensor_dtype == np.float16:
|
215
333
|
dtype = GGMLQuantizationType.F16
|
@@ -231,14 +349,19 @@ class GGUFWriter:
|
|
231
349
|
dtype = raw_dtype
|
232
350
|
if tensor_dtype == np.uint8:
|
233
351
|
tensor_shape = quant_shape_from_byte_shape(tensor_shape, raw_dtype)
|
234
|
-
|
235
|
-
|
236
|
-
|
237
|
-
|
238
|
-
|
239
|
-
|
240
|
-
|
241
|
-
|
352
|
+
|
353
|
+
# make sure there is at least one tensor before splitting
|
354
|
+
if len(self.tensors[-1]) > 0:
|
355
|
+
if ( # split when over tensor limit
|
356
|
+
self.split_max_tensors != 0
|
357
|
+
and len(self.tensors[-1]) >= self.split_max_tensors
|
358
|
+
) or ( # split when over size limit
|
359
|
+
self.split_max_size != 0
|
360
|
+
and sum(ti.nbytes for ti in self.tensors[-1].values()) + tensor_nbytes > self.split_max_size
|
361
|
+
):
|
362
|
+
self.tensors.append({})
|
363
|
+
|
364
|
+
self.tensors[-1][name] = TensorInfo(shape=tensor_shape, dtype=dtype, nbytes=tensor_nbytes)
|
242
365
|
|
243
366
|
def add_tensor(
|
244
367
|
self, name: str, tensor: np.ndarray[Any, Any], raw_shape: Sequence[int] | None = None,
|
@@ -252,10 +375,10 @@ class GGUFWriter:
|
|
252
375
|
self.temp_file = fp
|
253
376
|
|
254
377
|
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
|
378
|
+
self.add_tensor_info(name, shape, tensor.dtype, tensor.nbytes, raw_dtype=raw_dtype)
|
256
379
|
|
257
380
|
if self.temp_file is None:
|
258
|
-
self.tensors.
|
381
|
+
self.tensors[-1][name].tensor = tensor
|
259
382
|
return
|
260
383
|
|
261
384
|
tensor.tofile(self.temp_file)
|
@@ -267,100 +390,205 @@ class GGUFWriter:
|
|
267
390
|
fp.write(bytes([0] * pad))
|
268
391
|
|
269
392
|
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}')
|
393
|
+
if self.state is not WriterState.TI_DATA and self.state is not WriterState.WEIGHTS:
|
394
|
+
raise ValueError(f'Expected output file to contain tensor info or weights, got {self.state}')
|
395
|
+
assert self.fout is not None
|
272
396
|
|
273
397
|
if self.endianess == GGUFEndian.BIG:
|
274
398
|
tensor.byteswap(inplace=True)
|
275
|
-
|
276
|
-
|
277
|
-
|
399
|
+
|
400
|
+
file_id = -1
|
401
|
+
for i, tensors in enumerate(self.tensors):
|
402
|
+
if len(tensors) > 0:
|
403
|
+
file_id = i
|
404
|
+
break
|
405
|
+
|
406
|
+
fout = self.fout[file_id]
|
407
|
+
|
408
|
+
# pop the first tensor info
|
409
|
+
# TODO: cleaner way to get the first key
|
410
|
+
first_tensor_name = [name for name, _ in zip(self.tensors[file_id].keys(), range(1))][0]
|
411
|
+
ti = self.tensors[file_id].pop(first_tensor_name)
|
412
|
+
assert ti.nbytes == tensor.nbytes
|
413
|
+
|
414
|
+
self.write_padding(fout, fout.tell())
|
415
|
+
tensor.tofile(fout)
|
416
|
+
self.write_padding(fout, tensor.nbytes)
|
417
|
+
|
418
|
+
self.state = WriterState.WEIGHTS
|
278
419
|
|
279
420
|
def write_tensors_to_file(self, *, progress: bool = False) -> None:
|
280
421
|
self.write_ti_data_to_file()
|
281
422
|
|
282
|
-
self.
|
423
|
+
assert self.fout is not None
|
424
|
+
|
425
|
+
for fout in self.fout:
|
426
|
+
self.write_padding(fout, fout.tell())
|
283
427
|
|
284
428
|
if self.temp_file is None:
|
285
|
-
|
429
|
+
shard_bar = None
|
430
|
+
bar = None
|
286
431
|
|
287
432
|
if progress:
|
288
433
|
from tqdm import tqdm
|
289
434
|
|
290
|
-
total_bytes = sum(
|
435
|
+
total_bytes = sum(ti.nbytes for t in self.tensors for ti in t.values())
|
291
436
|
|
437
|
+
if len(self.fout) > 1:
|
438
|
+
shard_bar = tqdm(desc=f"Shard (0/{len(self.fout)})", total=None, unit="byte", unit_scale=True)
|
292
439
|
bar = tqdm(desc="Writing", total=total_bytes, unit="byte", unit_scale=True)
|
293
440
|
|
294
|
-
|
295
|
-
|
296
|
-
|
297
|
-
|
298
|
-
|
299
|
-
|
300
|
-
|
301
|
-
|
302
|
-
|
303
|
-
|
304
|
-
|
305
|
-
|
306
|
-
|
307
|
-
|
308
|
-
|
309
|
-
|
310
|
-
|
441
|
+
for i, (fout, tensors) in enumerate(zip(self.fout, self.tensors)):
|
442
|
+
if shard_bar is not None:
|
443
|
+
shard_bar.set_description(f"Shard ({i + 1}/{len(self.fout)})")
|
444
|
+
total = sum(ti.nbytes for ti in tensors.values())
|
445
|
+
shard_bar.reset(total=(total if total > 0 else None))
|
446
|
+
|
447
|
+
# relying on the fact that Python dicts preserve insertion order (since 3.7)
|
448
|
+
for ti in tensors.values():
|
449
|
+
assert ti.tensor is not None # can only iterate once over the tensors
|
450
|
+
assert ti.tensor.nbytes == ti.nbytes
|
451
|
+
ti.tensor.tofile(fout)
|
452
|
+
if shard_bar is not None:
|
453
|
+
shard_bar.update(ti.nbytes)
|
454
|
+
if bar is not None:
|
455
|
+
bar.update(ti.nbytes)
|
456
|
+
self.write_padding(fout, ti.nbytes)
|
457
|
+
ti.tensor = None
|
458
|
+
else:
|
459
|
+
self.temp_file.seek(0)
|
311
460
|
|
312
|
-
|
461
|
+
shutil.copyfileobj(self.temp_file, self.fout[0 if not self.small_first_shard else 1])
|
462
|
+
self.flush()
|
463
|
+
self.temp_file.close()
|
313
464
|
|
314
|
-
|
315
|
-
self.flush()
|
316
|
-
self.temp_file.close()
|
465
|
+
self.state = WriterState.WEIGHTS
|
317
466
|
|
318
467
|
def flush(self) -> None:
|
319
|
-
self.fout
|
468
|
+
assert self.fout is not None
|
469
|
+
for fout in self.fout:
|
470
|
+
fout.flush()
|
320
471
|
|
321
472
|
def close(self) -> None:
|
322
|
-
self.fout
|
473
|
+
if self.fout is not None:
|
474
|
+
for fout in self.fout:
|
475
|
+
fout.close()
|
476
|
+
self.fout = None
|
477
|
+
|
478
|
+
def add_type(self, type_name: str) -> None:
|
479
|
+
self.add_string(Keys.General.TYPE, type_name)
|
323
480
|
|
324
481
|
def add_architecture(self) -> None:
|
325
482
|
self.add_string(Keys.General.ARCHITECTURE, self.arch)
|
326
483
|
|
484
|
+
def add_quantization_version(self, quantization_version: int) -> None:
|
485
|
+
self.add_uint32(Keys.General.QUANTIZATION_VERSION, quantization_version)
|
486
|
+
|
487
|
+
def add_custom_alignment(self, alignment: int) -> None:
|
488
|
+
self.data_alignment = alignment
|
489
|
+
self.add_uint32(Keys.General.ALIGNMENT, alignment)
|
490
|
+
|
491
|
+
def add_file_type(self, ftype: int) -> None:
|
492
|
+
self.add_uint32(Keys.General.FILE_TYPE, ftype)
|
493
|
+
|
494
|
+
def add_name(self, name: str) -> None:
|
495
|
+
self.add_string(Keys.General.NAME, name)
|
496
|
+
|
327
497
|
def add_author(self, author: str) -> None:
|
328
498
|
self.add_string(Keys.General.AUTHOR, author)
|
329
499
|
|
330
500
|
def add_version(self, version: str) -> None:
|
331
501
|
self.add_string(Keys.General.VERSION, version)
|
332
502
|
|
333
|
-
def
|
334
|
-
self.add_string(Keys.
|
503
|
+
def add_organization(self, organization: str) -> None:
|
504
|
+
self.add_string(Keys.General.ORGANIZATION, organization)
|
335
505
|
|
336
|
-
def
|
337
|
-
self.add_string(Keys.General.
|
506
|
+
def add_finetune(self, finetune: str) -> None:
|
507
|
+
self.add_string(Keys.General.FINETUNE, finetune)
|
508
|
+
|
509
|
+
def add_basename(self, basename: str) -> None:
|
510
|
+
self.add_string(Keys.General.BASENAME, basename)
|
338
511
|
|
339
512
|
def add_description(self, description: str) -> None:
|
340
513
|
self.add_string(Keys.General.DESCRIPTION, description)
|
341
514
|
|
342
|
-
def
|
343
|
-
self.add_string(Keys.General.
|
515
|
+
def add_quantized_by(self, quantized: str) -> None:
|
516
|
+
self.add_string(Keys.General.QUANTIZED_BY, quantized)
|
517
|
+
|
518
|
+
def add_size_label(self, size_label: str) -> None:
|
519
|
+
self.add_string(Keys.General.SIZE_LABEL, size_label)
|
520
|
+
|
521
|
+
def add_license(self, license: str) -> None:
|
522
|
+
self.add_string(Keys.General.LICENSE, license)
|
523
|
+
|
524
|
+
def add_license_name(self, license: str) -> None:
|
525
|
+
self.add_string(Keys.General.LICENSE_NAME, license)
|
526
|
+
|
527
|
+
def add_license_link(self, license: str) -> None:
|
528
|
+
self.add_string(Keys.General.LICENSE_LINK, license)
|
529
|
+
|
530
|
+
def add_url(self, url: str) -> None:
|
531
|
+
self.add_string(Keys.General.URL, url)
|
532
|
+
|
533
|
+
def add_doi(self, doi: str) -> None:
|
534
|
+
self.add_string(Keys.General.DOI, doi)
|
535
|
+
|
536
|
+
def add_uuid(self, uuid: str) -> None:
|
537
|
+
self.add_string(Keys.General.UUID, uuid)
|
538
|
+
|
539
|
+
def add_repo_url(self, repo_url: str) -> None:
|
540
|
+
self.add_string(Keys.General.REPO_URL, repo_url)
|
344
541
|
|
345
542
|
def add_source_url(self, url: str) -> None:
|
346
543
|
self.add_string(Keys.General.SOURCE_URL, url)
|
347
544
|
|
348
|
-
def
|
349
|
-
self.add_string(Keys.General.
|
545
|
+
def add_source_doi(self, doi: str) -> None:
|
546
|
+
self.add_string(Keys.General.SOURCE_DOI, doi)
|
350
547
|
|
351
|
-
def
|
352
|
-
self.
|
548
|
+
def add_source_uuid(self, uuid: str) -> None:
|
549
|
+
self.add_string(Keys.General.SOURCE_UUID, uuid)
|
353
550
|
|
354
|
-
def
|
355
|
-
self.add_string(Keys.General.
|
551
|
+
def add_source_repo_url(self, repo_url: str) -> None:
|
552
|
+
self.add_string(Keys.General.SOURCE_REPO_URL, repo_url)
|
356
553
|
|
357
|
-
def
|
358
|
-
self.add_uint32(
|
359
|
-
Keys.General.QUANTIZATION_VERSION, quantization_version)
|
554
|
+
def add_base_model_count(self, source_count: int) -> None:
|
555
|
+
self.add_uint32(Keys.General.BASE_MODEL_COUNT, source_count)
|
360
556
|
|
361
|
-
def
|
362
|
-
self.
|
363
|
-
|
557
|
+
def add_base_model_name(self, source_id: int, name: str) -> None:
|
558
|
+
self.add_string(Keys.General.BASE_MODEL_NAME.format(id=source_id), name)
|
559
|
+
|
560
|
+
def add_base_model_author(self, source_id: int, author: str) -> None:
|
561
|
+
self.add_string(Keys.General.BASE_MODEL_AUTHOR.format(id=source_id), author)
|
562
|
+
|
563
|
+
def add_base_model_version(self, source_id: int, version: str) -> None:
|
564
|
+
self.add_string(Keys.General.BASE_MODEL_VERSION.format(id=source_id), version)
|
565
|
+
|
566
|
+
def add_base_model_organization(self, source_id: int, organization: str) -> None:
|
567
|
+
self.add_string(Keys.General.BASE_MODEL_ORGANIZATION.format(id=source_id), organization)
|
568
|
+
|
569
|
+
def add_base_model_url(self, source_id: int, url: str) -> None:
|
570
|
+
self.add_string(Keys.General.BASE_MODEL_URL.format(id=source_id), url)
|
571
|
+
|
572
|
+
def add_base_model_doi(self, source_id: int, doi: str) -> None:
|
573
|
+
self.add_string(Keys.General.BASE_MODEL_DOI.format(id=source_id), doi)
|
574
|
+
|
575
|
+
def add_base_model_uuid(self, source_id: int, uuid: str) -> None:
|
576
|
+
self.add_string(Keys.General.BASE_MODEL_UUID.format(id=source_id), uuid)
|
577
|
+
|
578
|
+
def add_base_model_repo_url(self, source_id: int, repo_url: str) -> None:
|
579
|
+
self.add_string(Keys.General.BASE_MODEL_REPO_URL.format(id=source_id), repo_url)
|
580
|
+
|
581
|
+
def add_tags(self, tags: Sequence[str]) -> None:
|
582
|
+
self.add_array(Keys.General.TAGS, tags)
|
583
|
+
|
584
|
+
def add_languages(self, languages: Sequence[str]) -> None:
|
585
|
+
self.add_array(Keys.General.LANGUAGES, languages)
|
586
|
+
|
587
|
+
def add_datasets(self, datasets: Sequence[str]) -> None:
|
588
|
+
self.add_array(Keys.General.DATASETS, datasets)
|
589
|
+
|
590
|
+
def add_tensor_data_layout(self, layout: str) -> None:
|
591
|
+
self.add_string(Keys.LLM.TENSOR_DATA_LAYOUT.format(arch=self.arch), layout)
|
364
592
|
|
365
593
|
def add_vocab_size(self, size: int) -> None:
|
366
594
|
self.add_uint32(Keys.LLM.VOCAB_SIZE.format(arch=self.arch), size)
|
@@ -374,17 +602,38 @@ class GGUFWriter:
|
|
374
602
|
def add_block_count(self, length: int) -> None:
|
375
603
|
self.add_uint32(Keys.LLM.BLOCK_COUNT.format(arch=self.arch), length)
|
376
604
|
|
377
|
-
def
|
378
|
-
self.add_uint32(Keys.LLM.
|
605
|
+
def add_leading_dense_block_count(self, length: int) -> None:
|
606
|
+
self.add_uint32(Keys.LLM.LEADING_DENSE_BLOCK_COUNT.format(arch=self.arch), length)
|
607
|
+
|
608
|
+
def add_feed_forward_length(self, length: int | Sequence[int]) -> None:
|
609
|
+
if isinstance(length, int):
|
610
|
+
self.add_uint32(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
|
611
|
+
else:
|
612
|
+
self.add_array(Keys.LLM.FEED_FORWARD_LENGTH.format(arch=self.arch), length)
|
613
|
+
|
614
|
+
def add_expert_feed_forward_length(self, length: int) -> None:
|
615
|
+
self.add_uint32(Keys.LLM.EXPERT_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
|
616
|
+
|
617
|
+
def add_expert_shared_feed_forward_length(self, length: int) -> None:
|
618
|
+
self.add_uint32(Keys.LLM.EXPERT_SHARED_FEED_FORWARD_LENGTH.format(arch=self.arch), length)
|
379
619
|
|
380
620
|
def add_parallel_residual(self, use: bool) -> None:
|
381
621
|
self.add_bool(Keys.LLM.USE_PARALLEL_RESIDUAL.format(arch=self.arch), use)
|
382
622
|
|
383
|
-
def
|
384
|
-
self.add_uint32(Keys.
|
623
|
+
def add_decoder_start_token_id(self, id: int) -> None:
|
624
|
+
self.add_uint32(Keys.LLM.DECODER_START_TOKEN_ID.format(arch=self.arch), id)
|
385
625
|
|
386
|
-
def
|
387
|
-
|
626
|
+
def add_head_count(self, count: int | Sequence[int]) -> None:
|
627
|
+
if isinstance(count, int):
|
628
|
+
self.add_uint32(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
|
629
|
+
else:
|
630
|
+
self.add_array(Keys.Attention.HEAD_COUNT.format(arch=self.arch), count)
|
631
|
+
|
632
|
+
def add_head_count_kv(self, count: int | Sequence[int]) -> None:
|
633
|
+
if isinstance(count, int):
|
634
|
+
self.add_uint32(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
|
635
|
+
else:
|
636
|
+
self.add_array(Keys.Attention.HEAD_COUNT_KV.format(arch=self.arch), count)
|
388
637
|
|
389
638
|
def add_key_length(self, length: int) -> None:
|
390
639
|
self.add_uint32(Keys.Attention.KEY_LENGTH.format(arch=self.arch), length)
|
@@ -401,12 +650,24 @@ class GGUFWriter:
|
|
401
650
|
def add_logit_scale(self, value: float) -> None:
|
402
651
|
self.add_float32(Keys.LLM.LOGIT_SCALE.format(arch=self.arch), value)
|
403
652
|
|
653
|
+
def add_attn_logit_softcapping(self, value: float) -> None:
|
654
|
+
self.add_float32(Keys.LLM.ATTN_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
|
655
|
+
|
656
|
+
def add_final_logit_softcapping(self, value: float) -> None:
|
657
|
+
self.add_float32(Keys.LLM.FINAL_LOGIT_SOFTCAPPING.format(arch=self.arch), value)
|
658
|
+
|
404
659
|
def add_expert_count(self, count: int) -> None:
|
405
660
|
self.add_uint32(Keys.LLM.EXPERT_COUNT.format(arch=self.arch), count)
|
406
661
|
|
407
662
|
def add_expert_used_count(self, count: int) -> None:
|
408
663
|
self.add_uint32(Keys.LLM.EXPERT_USED_COUNT.format(arch=self.arch), count)
|
409
664
|
|
665
|
+
def add_expert_shared_count(self, count: int) -> None:
|
666
|
+
self.add_uint32(Keys.LLM.EXPERT_SHARED_COUNT.format(arch=self.arch), count)
|
667
|
+
|
668
|
+
def add_expert_weights_scale(self, value: float) -> None:
|
669
|
+
self.add_float32(Keys.LLM.EXPERT_WEIGHTS_SCALE.format(arch=self.arch), value)
|
670
|
+
|
410
671
|
def add_layer_norm_eps(self, value: float) -> None:
|
411
672
|
self.add_float32(Keys.Attention.LAYERNORM_EPS.format(arch=self.arch), value)
|
412
673
|
|
@@ -416,6 +677,18 @@ class GGUFWriter:
|
|
416
677
|
def add_causal_attention(self, value: bool) -> None:
|
417
678
|
self.add_bool(Keys.Attention.CAUSAL.format(arch=self.arch), value)
|
418
679
|
|
680
|
+
def add_q_lora_rank(self, length: int) -> None:
|
681
|
+
self.add_uint32(Keys.Attention.Q_LORA_RANK.format(arch=self.arch), length)
|
682
|
+
|
683
|
+
def add_kv_lora_rank(self, length: int) -> None:
|
684
|
+
self.add_uint32(Keys.Attention.KV_LORA_RANK.format(arch=self.arch), length)
|
685
|
+
|
686
|
+
def add_relative_attn_buckets_count(self, value: int) -> None:
|
687
|
+
self.add_uint32(Keys.Attention.REL_BUCKETS_COUNT.format(arch=self.arch), value)
|
688
|
+
|
689
|
+
def add_sliding_window(self, value: int) -> None:
|
690
|
+
self.add_uint32(Keys.Attention.SLIDING_WINDOW.format(arch=self.arch), value)
|
691
|
+
|
419
692
|
def add_pooling_type(self, value: PoolingType) -> None:
|
420
693
|
self.add_uint32(Keys.LLM.POOLING_TYPE.format(arch=self.arch), value.value)
|
421
694
|
|
@@ -431,7 +704,7 @@ class GGUFWriter:
|
|
431
704
|
def add_rope_scaling_factor(self, value: float) -> None:
|
432
705
|
self.add_float32(Keys.Rope.SCALING_FACTOR.format(arch=self.arch), value)
|
433
706
|
|
434
|
-
def add_rope_scaling_attn_factors(self, value:
|
707
|
+
def add_rope_scaling_attn_factors(self, value: float) -> None:
|
435
708
|
self.add_float32(Keys.Rope.SCALING_ATTN_FACTOR.format(arch=self.arch), value)
|
436
709
|
|
437
710
|
def add_rope_scaling_orig_ctx_len(self, value: int) -> None:
|
@@ -440,6 +713,9 @@ class GGUFWriter:
|
|
440
713
|
def add_rope_scaling_finetuned(self, value: bool) -> None:
|
441
714
|
self.add_bool(Keys.Rope.SCALING_FINETUNED.format(arch=self.arch), value)
|
442
715
|
|
716
|
+
def add_rope_scaling_yarn_log_mul(self, value: float) -> None:
|
717
|
+
self.add_float32(Keys.Rope.SCALING_YARN_LOG_MUL.format(arch=self.arch), value)
|
718
|
+
|
443
719
|
def add_ssm_conv_kernel(self, value: int) -> None:
|
444
720
|
self.add_uint32(Keys.SSM.CONV_KERNEL.format(arch=self.arch), value)
|
445
721
|
|
@@ -503,6 +779,12 @@ class GGUFWriter:
|
|
503
779
|
def add_add_space_prefix(self, value: bool) -> None:
|
504
780
|
self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)
|
505
781
|
|
782
|
+
def add_remove_extra_whitespaces(self, value: bool) -> None:
|
783
|
+
self.add_bool(Keys.Tokenizer.REMOVE_EXTRA_WS, value)
|
784
|
+
|
785
|
+
def add_precompiled_charsmap(self, charsmap: Sequence[bytes]) -> None:
|
786
|
+
self.add_array(Keys.Tokenizer.PRECOMPILED_CHARSMAP, charsmap)
|
787
|
+
|
506
788
|
def add_chat_template(self, value: str | Sequence[Mapping[str, str]]) -> None:
|
507
789
|
if not isinstance(value, str):
|
508
790
|
template_default = None
|
@@ -550,5 +832,42 @@ class GGUFWriter:
|
|
550
832
|
pack_prefix = '<' if self.endianess == GGUFEndian.LITTLE else '>'
|
551
833
|
return struct.pack(f'{pack_prefix}{fmt}', value)
|
552
834
|
|
553
|
-
def
|
554
|
-
|
835
|
+
def _pack_val(self, val: Any, vtype: GGUFValueType, add_vtype: bool) -> bytes:
|
836
|
+
kv_data = bytearray()
|
837
|
+
|
838
|
+
if add_vtype:
|
839
|
+
kv_data += self._pack("I", vtype)
|
840
|
+
|
841
|
+
pack_fmt = self._simple_value_packing.get(vtype)
|
842
|
+
if pack_fmt is not None:
|
843
|
+
kv_data += self._pack(pack_fmt, val, skip_pack_prefix = vtype == GGUFValueType.BOOL)
|
844
|
+
elif vtype == GGUFValueType.STRING:
|
845
|
+
encoded_val = val.encode("utf-8") if isinstance(val, str) else val
|
846
|
+
kv_data += self._pack("Q", len(encoded_val))
|
847
|
+
kv_data += encoded_val
|
848
|
+
elif vtype == GGUFValueType.ARRAY and isinstance(val, Sequence) and val:
|
849
|
+
if isinstance(val, bytes):
|
850
|
+
ltype = GGUFValueType.UINT8
|
851
|
+
else:
|
852
|
+
ltype = GGUFValueType.get_type(val[0])
|
853
|
+
if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
|
854
|
+
raise ValueError("All items in a GGUF array should be of the same type")
|
855
|
+
kv_data += self._pack("I", ltype)
|
856
|
+
kv_data += self._pack("Q", len(val))
|
857
|
+
for item in val:
|
858
|
+
kv_data += self._pack_val(item, ltype, add_vtype=False)
|
859
|
+
else:
|
860
|
+
raise ValueError("Invalid GGUF metadata value type or value")
|
861
|
+
|
862
|
+
return kv_data
|
863
|
+
|
864
|
+
@staticmethod
|
865
|
+
def format_n_bytes_to_str(num: int) -> str:
|
866
|
+
if num == 0:
|
867
|
+
return "negligible - metadata only"
|
868
|
+
fnum = float(num)
|
869
|
+
for unit in ("", "K", "M", "G"):
|
870
|
+
if abs(fnum) < 1000.0:
|
871
|
+
return f"{fnum:3.1f}{unit}"
|
872
|
+
fnum /= 1000.0
|
873
|
+
return f"{fnum:.1f}T - over 1TB, split recommended"
|