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