okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
22.8 KiB536 linesraw
1"""tools/strata_gguf.py - Strata's own GGUF reader and writer for the preparation tools (replaces llama.cpp's gguf-py in them).
2
3It covers what the tools use, with gguf-py's names so a tool runs on either (see tools/_paths.py gguf_lib(); STRATA_GGUF_PY still selects
4the vendored gguf-py for two releases):
5
6    GGMLQuantizationType, GGML_QUANT_SIZES, GGUFValueType, GGUF_MAGIC, GGUF_VERSION, GGUF_DEFAULT_ALIGNMENT
7    quant_shape_to_byte_shape / quant_shape_from_byte_shape
8    GGUFReader(path)    .data (memmap of the file) .data_offset .alignment .fields[key] (.types .contents()) .tensors
9                        each tensor: .name .tensor_type .shape (dims, ggml order) .n_elements .n_bytes .data_offset .data .field
10    GGUFWriter(path, arch)   add_* / add_key_value / add_tensor(name, array, raw_shape=, raw_dtype=) / write_header_to_file /
11                        write_kv_data_to_file / write_tensors_to_file / close; one file, little-endian, no splitting, no lazy tensors
12    quants              strata_quants: dequantize / quantize
13
14A file written here is byte-identical to gguf-py's for the same calls (tools/test_strata_gguf.py compares them). Reading handles GGUF v2 and v3,
15little-endian only. The tools' lightweight header parser is tools/gguf_reader.py (GGUFFile); this module is the one that gives tensor data.
16"""
17from __future__ import annotations
18
19import os
20import struct
21import sys
22from collections import OrderedDict
23from enum import IntEnum
24from typing import Any, NamedTuple, Sequence
25
26import numpy as np
27
28import strata_quants as quants
29
30GGUF_MAGIC = 0x46554747          # "GGUF"
31GGUF_VERSION = 3
32GGUF_DEFAULT_ALIGNMENT = 32
33GGML_MAX_DIMS = 4
34GGUF_MAX_STRING_LENGTH = 1024 * 1024 * 1024
35GGUF_MAX_ARRAY_ELEMENTS = 1024 * 1024 * 1024
36READER_SUPPORTED_VERSIONS = (2, GGUF_VERSION)
37
38
39class GGMLQuantizationType(IntEnum):
40    F32 = 0
41    F16 = 1
42    Q4_0 = 2
43    Q4_1 = 3
44    Q5_0 = 6
45    Q5_1 = 7
46    Q8_0 = 8
47    Q8_1 = 9
48    Q2_K = 10
49    Q3_K = 11
50    Q4_K = 12
51    Q5_K = 13
52    Q6_K = 14
53    Q8_K = 15
54    IQ2_XXS = 16
55    IQ2_XS = 17
56    IQ3_XXS = 18
57    IQ1_S = 19
58    IQ4_NL = 20
59    IQ3_S = 21
60    IQ2_S = 22
61    IQ4_XS = 23
62    I8 = 24
63    I16 = 25
64    I32 = 26
65    I64 = 27
66    F64 = 28
67    IQ1_M = 29
68    BF16 = 30
69    TQ1_0 = 34
70    TQ2_0 = 35
71    MXFP4 = 39
72    NVFP4 = 40
73    Q1_0 = 41
74    Q2_0 = 42
75    # Agention's llama.cpp fork (the APR trellis expert types; see tools/gguf_reader.py): gguf-py cannot open these, we can
76    PTQ1_0 = 143
77    TQ2_T = 144
78    TQK6 = 145
79    TQK7 = 146
80    TQP5 = 147
81    TQP6 = 148
82    TQP7 = 149
83
84
85_Q = GGMLQuantizationType
86#: (elements per block, bytes per block): ggml's block structs (third_party/strata-ggml/strata-quant-common.h)
87GGML_QUANT_SIZES: dict[GGMLQuantizationType, tuple[int, int]] = {
88    _Q.F32: (1, 4), _Q.F16: (1, 2), _Q.Q4_0: (32, 18), _Q.Q4_1: (32, 20), _Q.Q5_0: (32, 22), _Q.Q5_1: (32, 24),
89    _Q.Q8_0: (32, 34), _Q.Q8_1: (32, 36), _Q.Q2_K: (256, 84), _Q.Q3_K: (256, 110), _Q.Q4_K: (256, 144),
90    _Q.Q5_K: (256, 176), _Q.Q6_K: (256, 210), _Q.Q8_K: (256, 292), _Q.IQ2_XXS: (256, 66), _Q.IQ2_XS: (256, 74),
91    _Q.IQ3_XXS: (256, 98), _Q.IQ1_S: (256, 50), _Q.IQ4_NL: (32, 18), _Q.IQ3_S: (256, 110), _Q.IQ2_S: (256, 82),
92    _Q.IQ4_XS: (256, 136), _Q.I8: (1, 1), _Q.I16: (1, 2), _Q.I32: (1, 4), _Q.I64: (1, 8), _Q.F64: (1, 8),
93    _Q.IQ1_M: (256, 56), _Q.BF16: (1, 2), _Q.TQ1_0: (256, 54), _Q.TQ2_0: (256, 66), _Q.MXFP4: (32, 17),
94    _Q.NVFP4: (64, 36), _Q.Q1_0: (128, 18), _Q.Q2_0: (64, 18),
95    _Q.PTQ1_0: (128, 28), _Q.TQ2_T: (128, 34), _Q.TQK6: (128, 26), _Q.TQK7: (128, 30),
96    _Q.TQP5: (128, 42), _Q.TQP6: (128, 50), _Q.TQP7: (128, 58),
97}
98
99
100class GGUFValueType(IntEnum):
101    UINT8 = 0
102    INT8 = 1
103    UINT16 = 2
104    INT16 = 3
105    UINT32 = 4
106    INT32 = 5
107    FLOAT32 = 6
108    BOOL = 7
109    STRING = 8
110    ARRAY = 9
111    UINT64 = 10
112    INT64 = 11
113    FLOAT64 = 12
114
115    @staticmethod
116    def get_type(val: Any) -> "GGUFValueType":
117        if isinstance(val, (str, bytes, bytearray)):
118            return GGUFValueType.STRING
119        if isinstance(val, list):
120            return GGUFValueType.ARRAY
121        if isinstance(val, float):
122            return GGUFValueType.FLOAT32
123        if isinstance(val, bool):
124            return GGUFValueType.BOOL
125        if isinstance(val, int):
126            return GGUFValueType.INT32
127        raise ValueError(f"Unknown type: {type(val)}")
128
129
130_V = GGUFValueType
131_SCALAR = {_V.UINT8: ("B", np.uint8), _V.INT8: ("b", np.int8), _V.UINT16: ("H", np.uint16), _V.INT16: ("h", np.int16),
132           _V.UINT32: ("I", np.uint32), _V.INT32: ("i", np.int32), _V.FLOAT32: ("f", np.float32), _V.UINT64: ("Q", np.uint64),
133           _V.INT64: ("q", np.int64), _V.FLOAT64: ("d", np.float64), _V.BOOL: ("?", np.bool_)}
134
135
136def quant_shape_to_byte_shape(shape: Sequence[int], quant_type: GGMLQuantizationType) -> tuple[int, ...]:
137    block_size, type_size = GGML_QUANT_SIZES[quant_type]
138    if shape[-1] % block_size != 0:
139        raise ValueError(f"Quantized tensor row size ({shape[-1]}) is not a multiple of {quant_type.name} block size ({block_size})")
140    return (*shape[:-1], shape[-1] // block_size * type_size)
141
142
143def quant_shape_from_byte_shape(shape: Sequence[int], quant_type: GGMLQuantizationType) -> tuple[int, ...]:
144    block_size, type_size = GGML_QUANT_SIZES[quant_type]
145    if shape[-1] % type_size != 0:
146        raise ValueError(f"Quantized tensor bytes per row ({shape[-1]}) is not a multiple of {quant_type.name} type size ({type_size})")
147    return (*shape[:-1], shape[-1] // type_size * block_size)
148
149
150# --------------------------------------------------------------------------------------------------------------------- reader
151class ReaderField(NamedTuple):
152    offset: int
153    name: str
154    types: list
155    value: Any = None          # the parsed value (a str, a number, a bool, or a list)
156
157    def contents(self, index_or_slice: int | slice = slice(None)) -> Any:
158        if not self.types:
159            return None
160        if self.types[0] == GGUFValueType.ARRAY:
161            return self.value[index_or_slice]
162        return self.value
163
164
165class ReaderTensor(NamedTuple):
166    name: str
167    tensor_type: GGMLQuantizationType
168    shape: np.ndarray
169    n_elements: int
170    n_bytes: int
171    data_offset: int
172    data: np.ndarray
173    field: Any
174
175
176_NP_DATA = {_Q.F16: np.float16, _Q.F32: np.float32, _Q.F64: np.float64, _Q.I8: np.int8, _Q.I16: np.int16, _Q.I32: np.int32, _Q.I64: np.int64}
177
178
179class GGUFReader:
180    alignment: int = GGUF_DEFAULT_ALIGNMENT
181    data_offset: int
182
183    def __init__(self, path, mode: str = "r"):
184        self.data = np.memmap(path, mode=mode)
185        self._size = int(self.data.nbytes)
186        self._buf = memoryview(self.data)            # byte offsets index this; struct reads from it
187        self._pos = 0
188        if self._size < 24:
189            raise ValueError("not a GGUF file (too short)")
190        if self._u("<I") != GGUF_MAGIC:
191            raise ValueError("GGUF magic invalid")
192        version = self._u("<I")
193        if version & 65535 == 0:
194            raise ValueError("this GGUF is big-endian, which is not supported")
195        if version not in READER_SUPPORTED_VERSIONS:
196            raise ValueError(f"Sorry, file appears to be version {version} which we cannot handle")
197        self.fields: OrderedDict[str, ReaderField] = OrderedDict()
198        self.tensors: list[ReaderTensor] = []
199        tensor_count, kv_count = self._u("<Q"), self._u("<Q")
200        if tensor_count > GGUF_MAX_ARRAY_ELEMENTS:
201            raise ValueError(f"Tensor count {tensor_count} exceeds maximum {GGUF_MAX_ARRAY_ELEMENTS}")
202        if kv_count > GGUF_MAX_ARRAY_ELEMENTS:
203            raise ValueError(f"KV count {kv_count} exceeds maximum {GGUF_MAX_ARRAY_ELEMENTS}")
204        self.fields["GGUF.version"] = ReaderField(4, "GGUF.version", [_V.UINT32], version)
205        self.fields["GGUF.tensor_count"] = ReaderField(8, "GGUF.tensor_count", [_V.UINT64], tensor_count)
206        self.fields["GGUF.kv_count"] = ReaderField(16, "GGUF.kv_count", [_V.UINT64], kv_count)
207        for _ in range(kv_count):
208            start = self._pos
209            key = self._str()
210            vt = self._u("<I")
211            types, value = self._value(vt)
212            if key in self.fields:
213                raise KeyError(f"Duplicate {key} already in list at offset {start}")
214            self.fields[key] = ReaderField(start, key, types, value)
215        infos = [self._tensor_info() for _ in range(tensor_count)]
216        align = self.fields.get("general.alignment")
217        if align is not None:
218            if align.types != [_V.UINT32]:
219                raise ValueError("Bad type for general.alignment field")
220            self.alignment = int(align.value)
221            if self.alignment == 0 or (self.alignment & (self.alignment - 1)) != 0:
222                raise ValueError("Invalid alignment: must be a non-zero power of two")
223        pad = self._pos % self.alignment
224        self.data_offset = self._pos + (self.alignment - pad if pad else 0)
225        self._build_tensors(infos)
226
227    # -- parsing
228    def _need(self, n: int) -> None:
229        if n < 0 or self._pos + n > self._size:
230            raise ValueError(f"header ends early: {n} bytes needed at offset {self._pos}, {self._size - self._pos} left")
231
232    def _u(self, fmt: str):
233        n = struct.calcsize(fmt)
234        self._need(n)
235        (v,) = struct.unpack_from(fmt, self._buf, self._pos)
236        self._pos += n
237        return v
238
239    def _str(self) -> str:
240        n = self._u("<Q")
241        if n > GGUF_MAX_STRING_LENGTH:
242            raise ValueError(f"String length {n} exceeds maximum {GGUF_MAX_STRING_LENGTH}")
243        self._need(n)
244        s = bytes(self._buf[self._pos:self._pos + n]).decode("utf-8")
245        self._pos += n
246        return s
247
248    def _value(self, raw_type: int):
249        try:
250            vt = GGUFValueType(raw_type)
251        except ValueError:
252            raise ValueError(f"Unknown/unhandled field type {raw_type}") from None
253        if vt == _V.STRING:
254            return [vt], self._str()
255        if vt in _SCALAR:
256            return [vt], self._u("<" + _SCALAR[vt][0])
257        # an array: element type, count, then the elements
258        et = GGUFValueType(self._u("<I"))
259        count = self._u("<Q")
260        if count > GGUF_MAX_ARRAY_ELEMENTS:
261            raise ValueError(f"Array length {count} exceeds maximum {GGUF_MAX_ARRAY_ELEMENTS}")
262        if et == _V.ARRAY:
263            raise ValueError("nested metadata arrays are not supported")
264        if et == _V.STRING:
265            self._need(count * 8)
266            return [vt, et], [self._str() for _ in range(count)]
267        fmt, npt = _SCALAR[et]
268        size = np.dtype(npt).itemsize
269        self._need(count * size)
270        arr = np.frombuffer(self._buf, dtype=np.dtype(npt).newbyteorder("<"), count=count, offset=self._pos)
271        self._pos += count * size
272        return [vt, et], arr.tolist()
273
274    def _tensor_info(self):
275        start = self._pos
276        name = self._str()
277        n_dims = self._u("<I")
278        if n_dims > GGML_MAX_DIMS:
279            raise ValueError(f"Tensor dimensions count {n_dims} exceeds GGML_MAX_DIMS ({GGML_MAX_DIMS})")
280        dims = [self._u("<Q") for _ in range(n_dims)]
281        raw_type = self._u("<I")
282        offset = self._u("<Q")
283        return name, dims, raw_type, offset, start
284
285    def _build_tensors(self, infos) -> None:
286        seen = set()
287        for name, dims, raw_type, offset, info_at in infos:
288            if name in seen:
289                raise ValueError(f"Found duplicated tensor with name {name}")
290            seen.add(name)
291            try:
292                ggml_type = GGMLQuantizationType(raw_type)
293            except ValueError:
294                raise ValueError(f"{raw_type} is not a valid GGMLQuantizationType") from None
295            n_elems = 1
296            for d in dims:
297                n_elems *= int(d)
298            np_dims = tuple(reversed(dims))
299            block_size, type_size = GGML_QUANT_SIZES[ggml_type]
300            n_bytes = n_elems * type_size // block_size
301            start = self.data_offset + offset
302            if ggml_type in _NP_DATA:
303                item_count, item_type = n_elems, _NP_DATA[ggml_type]
304            else:
305                item_count, item_type = n_bytes, np.uint8
306                np_dims = quant_shape_to_byte_shape(np_dims, ggml_type)
307            nbytes = item_count * np.dtype(item_type).itemsize
308            if start + nbytes > self._size:
309                raise ValueError(f"tensor {name} ends at byte {start + nbytes}, past the end of the file ({self._size})")
310            data = self.data[start:start + nbytes].view(dtype=item_type)[:item_count].reshape(np_dims)
311            self.tensors.append(ReaderTensor(name, ggml_type, np.array(dims, dtype=np.uint64), n_elems, n_bytes, start, data,
312                                             ReaderField(info_at, name, [], None)))   # .offset: where this tensor's info entry starts
313
314    def get_field(self, key: str):
315        return self.fields.get(key)
316
317    def get_tensor(self, idx: int) -> ReaderTensor:
318        return self.tensors[idx]
319
320
321# --------------------------------------------------------------------------------------------------------------------- writer
322class _TI:
323    __slots__ = ("shape", "dtype", "nbytes", "tensor")
324
325    def __init__(self, shape, dtype, nbytes, tensor=None):
326        self.shape, self.dtype, self.nbytes, self.tensor = shape, dtype, nbytes, tensor
327
328
329class _KV:
330    __slots__ = ("value", "type", "sub_type")
331
332    def __init__(self, value, type, sub_type=None):
333        self.value, self.type, self.sub_type = value, type, sub_type
334
335
336class GGUFWriter:
337    """One output file, little-endian. The sequence is gguf-py's: add the KVs and tensors, then write_header_to_file(),
338    write_kv_data_to_file(), write_tensors_to_file(), close(). The tensor data is held (not copied) until it is written."""
339
340    def __init__(self, path, arch: str, use_temp_file: bool = False, endianess=None, split_max_tensors: int = 0, split_max_size: int = 0,
341                 dry_run: bool = False, small_first_shard: bool = False):
342        if split_max_tensors or split_max_size or small_first_shard:
343            raise NotImplementedError("strata_gguf writes one file; splitting is not supported")
344        if endianess not in (None, "little") and getattr(endianess, "name", "LITTLE") != "LITTLE":
345            raise NotImplementedError("strata_gguf writes little-endian files only")
346        self.path = os.fspath(path) if path else None
347        self.arch = arch
348        self.data_alignment = GGUF_DEFAULT_ALIGNMENT
349        self.tensors: dict[str, _TI] = {}
350        self.kv_data: dict[str, _KV] = {}
351        self.fout = None
352        self.state = "no_file"
353        self.add_string("general.architecture", arch)
354
355    # -- key/values
356    def add_key_value(self, key: str, val: Any, vtype: GGUFValueType, sub_type: GGUFValueType | None = None) -> None:
357        self.kv_data[key] = _KV(val, GGUFValueType(vtype), None if sub_type is None else GGUFValueType(sub_type))
358
359    def remove_key(self, key: str) -> None:
360        self.kv_data.pop(key, None)
361
362    def add_uint8(self, key, val): self.add_key_value(key, val, _V.UINT8)
363    def add_int8(self, key, val): self.add_key_value(key, val, _V.INT8)
364    def add_uint16(self, key, val): self.add_key_value(key, val, _V.UINT16)
365    def add_int16(self, key, val): self.add_key_value(key, val, _V.INT16)
366    def add_uint32(self, key, val): self.add_key_value(key, val, _V.UINT32)
367    def add_int32(self, key, val): self.add_key_value(key, val, _V.INT32)
368    def add_float32(self, key, val): self.add_key_value(key, val, _V.FLOAT32)
369    def add_uint64(self, key, val): self.add_key_value(key, val, _V.UINT64)
370    def add_int64(self, key, val): self.add_key_value(key, val, _V.INT64)
371    def add_float64(self, key, val): self.add_key_value(key, val, _V.FLOAT64)
372    def add_bool(self, key, val): self.add_key_value(key, val, _V.BOOL)
373
374    def add_string(self, key: str, val: str) -> None:
375        if not val:
376            return
377        self.add_key_value(key, val, _V.STRING)
378
379    def add_array(self, key: str, val: Sequence[Any]) -> None:
380        if len(val) == 0:
381            return
382        self.add_key_value(key, val, _V.ARRAY)
383
384    def add_custom_alignment(self, alignment: int) -> None:
385        if alignment <= 0 or (alignment & (alignment - 1)) != 0:
386            raise ValueError("Invalid alignment: must be a non-zero power of two")
387        self.data_alignment = alignment
388        self.add_uint32("general.alignment", alignment)
389
390    def add_quantization_version(self, quantization_version: int) -> None:
391        self.add_uint32("general.quantization_version", quantization_version)
392
393    # -- tensors
394    @staticmethod
395    def ggml_pad(x: int, n: int) -> int:
396        return ((x + n - 1) // n) * n
397
398    def add_tensor_info(self, name: str, tensor_shape: Sequence[int], tensor_dtype, tensor_nbytes: int, raw_dtype=None) -> None:
399        if self.state != "no_file":
400            raise ValueError(f"Expected output file to be not yet opened, got {self.state}")
401        if name in self.tensors:
402            raise ValueError(f"Duplicated tensor name {name!r}")
403        if raw_dtype is None:
404            dt = np.dtype(tensor_dtype)
405            known = {np.dtype(np.float16): _Q.F16, np.dtype(np.float32): _Q.F32, np.dtype(np.float64): _Q.F64, np.dtype(np.int8): _Q.I8,
406                     np.dtype(np.int16): _Q.I16, np.dtype(np.int32): _Q.I32, np.dtype(np.int64): _Q.I64}
407            if dt not in known:
408                raise ValueError("Only F16, F32, F64, I8, I16, I32, I64 tensors are supported for now")
409            dtype = known[dt]
410        else:
411            dtype = GGMLQuantizationType(raw_dtype)
412            if np.dtype(tensor_dtype) == np.uint8:
413                tensor_shape = quant_shape_from_byte_shape(tensor_shape, dtype)
414        self.tensors[name] = _TI(tuple(tensor_shape), dtype, tensor_nbytes)
415
416    def add_tensor(self, name: str, tensor: np.ndarray, raw_shape: Sequence[int] | None = None, raw_dtype=None, tensor_endianess=None) -> None:
417        shape = raw_shape if raw_shape is not None else tensor.shape
418        self.add_tensor_info(name, shape, tensor.dtype, tensor.nbytes, raw_dtype=raw_dtype)
419        self.tensors[name].tensor = tensor
420
421    # -- serialisation
422    def _pack_val(self, val: Any, vtype: GGUFValueType, add_vtype: bool, sub_type=None) -> bytes:
423        out = bytearray()
424        if add_vtype:
425            out += struct.pack("<I", vtype)
426        sc = _SCALAR.get(vtype)
427        if sc is not None:
428            out += struct.pack(("" if vtype == _V.BOOL else "<") + sc[0], val)
429        elif vtype == _V.STRING:
430            enc = val.encode("utf-8") if isinstance(val, str) else val
431            out += struct.pack("<Q", len(enc)) + enc
432        elif vtype == _V.ARRAY:
433            if not isinstance(val, Sequence):
434                raise ValueError("Invalid GGUF metadata array, expecting sequence")
435            if len(val) == 0:
436                raise ValueError("Invalid GGUF metadata array. Empty array")
437            if sub_type is not None:
438                ltype = sub_type
439            elif isinstance(val, bytes):
440                ltype = _V.UINT8
441            else:
442                ltype = GGUFValueType.get_type(val[0])
443                if not all(GGUFValueType.get_type(i) is ltype for i in val[1:]):
444                    raise ValueError("All items in a GGUF array should be of the same type")
445            out += struct.pack("<I", ltype) + struct.pack("<Q", len(val))
446            if ltype in _SCALAR and ltype != _V.BOOL:        # a long numeric array in one call (same bytes as one pack per item)
447                out += struct.pack("<%d%s" % (len(val), _SCALAR[ltype][0]), *val)
448            else:
449                for item in val:
450                    out += self._pack_val(item, ltype, add_vtype=False)
451        else:
452            raise ValueError("Invalid GGUF metadata value type or value")
453        return bytes(out)
454
455    def open_output_file(self, path=None) -> None:
456        if self.state == "empty" and self.fout is not None and (path is None or os.fspath(path) == self.path):
457            return
458        if self.state != "no_file":
459            raise ValueError(f"Expected output file to be not yet opened, got {self.state}")
460        if path is not None:
461            self.path = os.fspath(path)
462        if self.path is not None:
463            self.fout = open(self.path, "wb")
464            self.state = "empty"
465
466    def write_header_to_file(self, path=None) -> None:
467        self.open_output_file(path)
468        if self.state != "empty":
469            raise ValueError(f"Expected output file to be empty, got {self.state}")
470        self.fout.write(struct.pack("<I", GGUF_MAGIC))
471        self.fout.write(struct.pack("<I", GGUF_VERSION))
472        self.fout.write(struct.pack("<Q", len(self.tensors)))
473        self.fout.write(struct.pack("<Q", len(self.kv_data)))
474        self.fout.flush()
475        self.state = "header"
476
477    def write_kv_data_to_file(self) -> None:
478        if self.state != "header":
479            raise ValueError(f"Expected output file to contain the header, got {self.state}")
480        kv = bytearray()
481        for key, val in self.kv_data.items():
482            kv += self._pack_val(key, _V.STRING, add_vtype=False)
483            kv += self._pack_val(val.value, val.type, add_vtype=True, sub_type=val.sub_type)
484        self.fout.write(kv)
485        self.fout.flush()
486        self.state = "kv"
487
488    def write_ti_data_to_file(self) -> None:
489        if self.state != "kv":
490            raise ValueError(f"Expected output file to contain KV data, got {self.state}")
491        ti = bytearray()
492        offset = 0
493        for name, t in self.tensors.items():
494            ti += self._pack_val(name, _V.STRING, add_vtype=False)
495            n = len(t.shape)
496            ti += struct.pack("<I", n)
497            for j in range(n):
498                ti += struct.pack("<Q", t.shape[n - 1 - j])
499            ti += struct.pack("<I", int(t.dtype))
500            ti += struct.pack("<Q", offset)
501            offset += self.ggml_pad(t.nbytes, self.data_alignment)
502        self.fout.write(ti)
503        self.fout.flush()
504        self.state = "ti"
505
506    def _pad(self, n: int) -> None:
507        pad = self.ggml_pad(n, self.data_alignment) - n
508        if pad:
509            self.fout.write(bytes(pad))
510
511    def write_tensors_to_file(self, *, progress: bool = False) -> None:
512        self.write_ti_data_to_file()
513        self._pad(self.fout.tell())
514        for name, t in self.tensors.items():
515            if t.tensor is None or t.tensor.nbytes != t.nbytes:
516                raise ValueError(f"tensor {name!r} has no data or the wrong size")
517            start = self.fout.tell()
518            np.ascontiguousarray(t.tensor).tofile(self.fout)
519            if self.fout.tell() - start != t.nbytes:      # a short write would only show as a corrupt file at load time
520                raise ValueError(f"tensor {name!r} wrote {self.fout.tell() - start} bytes, expected {t.nbytes}")
521            self._pad(t.nbytes)
522            t.tensor = None
523        self.state = "weights"
524
525    def flush(self) -> None:
526        if self.fout is not None:
527            self.fout.flush()
528
529    def close(self) -> None:
530        if self.fout is not None:
531            self.fout.close()
532            self.fout = None
533
534
535if __name__ == "__main__":
536    sys.exit("strata_gguf is a library: see tools/test_strata_gguf.py")