okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c7938c2d3
main
1"""Bounded, constant-memory read of the GGUF metadata needed for import preview. 2 3This reads tensor directory entries and checks their declared byte ranges, but it 4does not read tensor payloads or establish provenance. 5""" 6 7from __future__import annotations 8 9import os 10import stat 11import struct 12from pathlib import Path 13 14from strata_control .profiles import ProfileError 15from tools .gguf_reader import BLOCK_GEOMETRY ,GGML_TYPES 16 17 18MAX_HEADER_BYTES = 64 * 1024 * 1024 19MAX_METADATA_KEYS = 4096 20MAX_STRING_BYTES = 1024 * 1024 21MAX_ARRAY_ITEMS = 500_000 22MAX_TENSORS = 100_000 23SCALAR_BYTES = {0 :1 ,1 :1 ,2 :2 ,3 :2 ,4 :4 ,5 :4 ,6 :4 ,7 :1 , 2410 :8 ,11 :8 ,12 :8 } 25CAPTURE_STRINGS = {"general.architecture" ,"tokenizer.ggml.model" ,"clip.projector_type" } 26PRESENCE_KEYS = {"tokenizer.ggml.tokens" ,"tokenizer.ggml.merges" } 27 28 29class _Reader : 30def __init__ (self ,stream ,size :int ): 31self .stream ,self .size ,self .used = stream ,size ,0 32 33def take (self ,count :int )-> bytes : 34if count < 0 or self .used + count > min (self .size ,MAX_HEADER_BYTES ): 35raise ProfileError ("GGUF metadata exceeds the bounded inspection limit" ,5 ) 36data = self .stream .read (count ) 37if len (data )!= count : 38raise ProfileError ("GGUF metadata is truncated" ,5 ) 39self .used += count 40return data 41 42def skip (self ,count :int )-> None : 43if count < 0 or self .used + count > min (self .size ,MAX_HEADER_BYTES ): 44raise ProfileError ("GGUF metadata exceeds the bounded inspection limit" ,5 ) 45self .stream .seek (count ,os .SEEK_CUR ) 46self .used += count 47 48def u32 (self )-> int : 49return struct .unpack ("<I" ,self .take (4 ))[0 ] 50 51def u64 (self )-> int : 52return struct .unpack ("<Q" ,self .take (8 ))[0 ] 53 54def string (self ,* ,capture :bool = False )-> str | None : 55size = self .u64 () 56if size > MAX_STRING_BYTES : 57raise ProfileError ("GGUF metadata string is too large to inspect" ,5 ) 58if not capture : 59self .skip (size ) 60return None 61try : 62return self .take (size ).decode ("utf-8" ) 63except UnicodeError : 64raise ProfileError ("GGUF metadata has invalid UTF-8" ,5 )from None 65 66def value (self ,kind :int ,* ,capture :bool = False )-> object : 67if kind == 8 : 68return self .string (capture = capture ) 69if kind == 9 : 70element_type ,count = self .u32 (),self .u64 () 71if count > MAX_ARRAY_ITEMS : 72raise ProfileError ("GGUF metadata array exceeds the inspection limit" ,5 ) 73if element_type == 8 : 74for _ in range (count ): 75self .string () 76elif element_type in SCALAR_BYTES : 77self .skip (count * SCALAR_BYTES [element_type ]) 78else : 79raise ProfileError ("GGUF metadata has an unsupported array type" ,5 ) 80return element_type ,count 81if kind not in SCALAR_BYTES : 82raise ProfileError ("GGUF metadata has an unsupported value type" ,5 ) 83if capture and kind in (4 ,10 ): 84return struct .unpack ("<I" if kind == 4 else "<Q" ,self .take (SCALAR_BYTES [kind ]))[0 ] 85self .skip (SCALAR_BYTES [kind ]) 86return None 87 88 89def real_model_file (path :Path )-> Path : 90"""The regular file a model path stands for. A model file the person picked can be a link (a Hugging Face cache snapshot, an 91Ollama blob, a shortcut to a bigger drive): it is followed here, once, and the target is what gets opened. Strata's own state files 92(run configs, profiles, runtime records) keep the strict no-link rule in their readers.""" 93try : 94target = Path (os .path .realpath (path )) 95info = target .stat () 96except OSError : 97if os .path .islink (path ): 98raise ProfileError (f" { Path ( path ). name } is a link to a file that is not there" ,5 )from None 99raise ProfileError (f" { Path ( path ). name } is missing" ,5 )from None 100if not stat .S_ISREG (info .st_mode ): 101raise ProfileError ("GGUF shard must be a regular file" ,5 ) 102return target 103 104 105def inspect_metadata (path :Path )-> dict : 106"""Return only bounded compatibility signals from one regular GGUF v3 shard (a link to one is followed).""" 107try : 108path = real_model_file (Path (path )) 109descriptor = os .open (path ,os .O_RDONLY ) 110with os .fdopen (descriptor ,"rb" )as stream : 111details = os .fstat (stream .fileno ()) 112if not stat .S_ISREG (details .st_mode ): 113raise ProfileError ("GGUF shard must be a regular file" ,5 ) 114reader = _Reader (stream ,details .st_size ) 115if reader .take (4 )!= b"GGUF" : 116raise ProfileError ("file does not begin with a GGUF header" ,5 ) 117version ,tensors ,keys = reader .u32 (),reader .u64 (),reader .u64 () 118if version != 3 : 119raise ProfileError ("Strata metadata preflight requires GGUF v3" ,5 ) 120# tensors == 0 is a real file: a split set made with llama.cpp's gguf-split (Unsloth's) keeps only the metadata in its first shard 121if not 0 <= tensors <= MAX_TENSORS or keys > MAX_METADATA_KEYS : 122raise ProfileError ("GGUF tensor or metadata count exceeds the inspection limit" ,5 ) 123found :dict [str ,object ]= {} 124for _ in range (keys ): 125key = reader .string (capture = True ) 126if key is None or len (key )> 256 : 127raise ProfileError ("GGUF metadata key is invalid or too long" ,5 ) 128value_type = reader .u32 () 129if key in CAPTURE_STRINGS and value_type != 8 : 130raise ProfileError ("GGUF architecture or tokenizer model is not a string" ,5 ) 131value = reader .value (value_type ,capture = key in CAPTURE_STRINGS or 132key == "general.alignment" ) 133if key in CAPTURE_STRINGS : 134found [key ]= value 135elif key in PRESENCE_KEYS : 136found [key ]= value_type == 9 and isinstance (value ,tuple )and \ 137value [0 ]== 8 and value [1 ]> 0 138elif key == "general.alignment" : 139found [key ]= value 140alignment = found .get ("general.alignment" ,32 ) 141if type (alignment )is not int or not 1 <= alignment <= 4096 or \ 142alignment & (alignment - 1 ): 143raise ProfileError ("GGUF tensor alignment is invalid" ,5 ) 144tensor_types :dict [str ,int ]= {} 145expert_types :dict [str ,int ]= {} 146required_payload_bytes = 0 147extents :list [tuple [int ,int ]]= [] 148for _ in range (tensors ): 149name = reader .string (capture = True ) 150if not name or len (name )> 256 : 151raise ProfileError ("GGUF tensor name is invalid or too long" ,5 ) 152dimensions = reader .u32 () 153if not 1 <= dimensions <= 8 : 154raise ProfileError ("GGUF tensor dimension count is invalid" ,5 ) 155elements = 1 156for _ in range (dimensions ): 157size = reader .u64 () 158if size == 0 or size > 1_000_000_000 or elements > (1 << 63 )// size : 159raise ProfileError ("GGUF tensor shape is invalid" ,5 ) 160elements *= size 161type_id ,offset = reader .u32 (),reader .u64 () 162type_name = GGML_TYPES .get (type_id ) 163geometry = BLOCK_GEOMETRY .get (type_name )if type_name else None 164if geometry is None or elements % geometry [0 ]: 165raise ProfileError ("GGUF tensor has an unsupported encoding or shape" ,5 ) 166if offset % alignment : 167raise ProfileError ("GGUF tensor offset is not aligned" ,5 ) 168needed = offset + elements // geometry [0 ]* geometry [1 ] 169required_payload_bytes = max (required_payload_bytes ,needed ) 170extents .append ((offset ,needed )) 171tensor_types [type_name ]= tensor_types .get (type_name ,0 )+ 1 172if "_exps" in name or ".experts." in name : 173expert_types [type_name ]= expert_types .get (type_name ,0 )+ 1 174data_start = (reader .used + alignment - 1 )// alignment * alignment 175extents .sort () 176if any (next_start < end for (_ ,end ), (next_start ,_ )in zip (extents ,extents [1 :])): 177raise ProfileError ("GGUF tensor byte ranges overlap" ,5 ) 178if tensors and data_start + required_payload_bytes > details .st_size : 179raise ProfileError ("GGUF tensor payload is shorter than its directory requires" ,5 ) 180if tensors == 1 and details .st_size - (data_start + required_payload_bytes )>= 64 : 181raise ProfileError ("single-tensor GGUF shard has unexplained trailing bytes" ,5 ) 182return {"architecture" :found .get ("general.architecture" ), 183"projector_type" :found .get ("clip.projector_type" ), 184"tokenizer_model" :found .get ("tokenizer.ggml.model" ), 185"tokenizer_tokens_present" :found .get ("tokenizer.ggml.tokens" )is True , 186"tokenizer_merges_present" :found .get ("tokenizer.ggml.merges" )is True , 187"tensor_count_reported" :tensors ,"tensor_count_scanned" :tensors , 188"tensor_types" :dict (sorted (tensor_types .items ())), 189"expert_tensor_types" :dict (sorted (expert_types .items ())), 190"header_bytes_scanned" :reader .used , 191"payload_bytes_required" :required_payload_bytes , 192"payload_extent_valid" :True } 193except OSError : 194raise ProfileError ("GGUF metadata could not be read" ,5 )from None