okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd0e3766a
main
1#!/usr/bin/env python3 2# SPDX-License-Identifier: MIT OR Apache-2.0 3# From https://github.com/1872183316/quantscope (commit bfdf205), used by tools/strata_inspect.py and setup's --inspect. 4"""quantscope: find the real quantization of a model without downloading it. 5 6Reads only file headers (a few MB per file, via HTTP range requests) of GGUF or safetensors 7models on ModelScope, Hugging Face, any URL, or local disk, and reports the actual storage 8type and bits per weight of every tensor group (routed experts, attention, embeddings, ...). 9File names such as "IQ4_XS" or "Q4_K_XL" are recipe labels; the header is the ground truth. 10 11Examples: 12python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF # list variants 13python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF UD-Q4_K_XL # one variant 14python quantscope.py ms:unsloth/Qwen3.8-Flash-Next-GGUF --all # compare all variants 15python quantscope.py hf:Qwen/Qwen3-30B-A3B-GPTQ-Int4 16python quantscope.py models/model-00001-of-00003.gguf 17""" 18 19from __future__import annotations 20 21import argparse 22import fnmatch 23import glob 24import json 25import os 26import re 27import struct 28import sys 29import urllib .request 30from collections import defaultdict 31 32# ---------------------------------------------------------------- sources -------------------- 33 34HUBS = { 35"ms" : ("https://modelscope.cn/api/v1/models/{repo}/repo/files?Recursive=true" , 36"https://modelscope.cn/models/{repo}/resolve/master/{path}" ), 37"hf" : ("https://huggingface.co/api/models/{repo}/tree/main?recursive=true" , 38"https://huggingface.co/{repo}/resolve/main/{path}" ), 39} 40if os .environ .get ("HF_ENDPOINT" ): 41base = os .environ ["HF_ENDPOINT" ].rstrip ("/" ) 42HUBS ["hf" ]= (base + "/api/models/{repo}/tree/main?recursive=true" , 43base + "/{repo}/resolve/main/{path}" ) 44 45 46def http (url :str ,start :int | None = None ,end :int | None = None )-> bytes : 47headers = {"User-Agent" :"quantscope" } 48if start is not None : 49headers ["Range" ]= f"bytes= { start } - { end } " 50for attempt in range (5 ): 51try : 52with urllib .request .urlopen (urllib .request .Request (url ,headers = headers ), 53timeout = 60 )as r : 54return r .read () 55except Exception as error :# noqa: BLE001 - network retries 56if attempt == 4 : 57raise RuntimeError (f" { url } : { error } " )from error 58raise AssertionError 59 60 61class Source : 62"""A file readable by byte ranges (remote or local) with a known size.""" 63 64def __init__ (self ,name :str ,size :int ,url :str | None = None ,path :str | None = None ): 65self .name ,self .size ,self .url ,self .path = name ,size ,url ,path 66 67def read (self ,start :int ,length :int )-> bytes : 68length = max (0 ,min (length ,self .size - start )) 69if length == 0 : 70return b"" 71if self .path : 72with open (self .path ,"rb" )as f : 73f .seek (start ) 74return f .read (length ) 75return http (self .url ,start ,start + length - 1 ) 76 77 78def list_hub (kind :str ,repo :str )-> list [Source ]: 79list_url ,file_url = HUBS [kind ] 80data = json .loads (http (list_url .format (repo = repo ))) 81out = [] 82if kind == "ms" : 83for f in data ["Data" ]["Files" ]: 84if f .get ("Type" )== "blob" : 85out .append (Source (f ["Path" ],int (f .get ("Size" )or 0 ), 86url = file_url .format (repo = repo ,path = f ["Path" ]))) 87else : 88for f in data : 89if f .get ("type" )== "file" : 90size = int ((f .get ("lfs" )or {}).get ("size" )or f .get ("size" )or 0 ) 91out .append (Source (f ["path" ],size ,url = file_url .format (repo = repo ,path = f ["path" ]))) 92return out 93 94 95def resolve (spec :str )-> list [Source ]: 96m = re .match (r"^(ms|hf):([^/]+/[^/:]+)$" ,spec ) 97if m : 98return list_hub (m .group (1 ),m .group (2 )) 99if spec .startswith (("http://" ,"https://" )): 100head = urllib .request .Request (spec ,method = "HEAD" ,headers = {"User-Agent" :"quantscope" }) 101with urllib .request .urlopen (head ,timeout = 60 )as r : 102size = int (r .headers .get ("Content-Length" )or 0 ) 103return [Source (spec .rsplit ("/" ,1 )[- 1 ],size ,url = spec )] 104paths = [spec ]if os .path .isfile (spec )else sorted ( 105glob .glob (os .path .join (spec ,"**" ,"*" ),recursive = True )) 106return [Source (os .path .relpath (p ,spec )if os .path .isdir (spec )else os .path .basename (p ), 107os .path .getsize (p ),path = p )for p in paths if os .path .isfile (p )] 108 109 110def variant_of (name :str )-> str : 111"""Groups the shards of one model file: strips -00001-of-00004 and the extension.""" 112return re .sub (r"(-\d{5}-of-\d{5})?\.(gguf|safetensors|ninfer)$" ,"" ,name ) 113 114 115# ---------------------------------------------------------------- GGUF ----------------------- 116 117GGML_TYPES = { 1180 :"F32" ,1 :"F16" ,2 :"Q4_0" ,3 :"Q4_1" ,6 :"Q5_0" ,7 :"Q5_1" ,8 :"Q8_0" ,9 :"Q8_1" , 11910 :"Q2_K" ,11 :"Q3_K" ,12 :"Q4_K" ,13 :"Q5_K" ,14 :"Q6_K" ,15 :"Q8_K" ,16 :"IQ2_XXS" , 12017 :"IQ2_XS" ,18 :"IQ3_XXS" ,19 :"IQ1_S" ,20 :"IQ4_NL" ,21 :"IQ3_S" ,22 :"IQ2_S" , 12123 :"IQ4_XS" ,24 :"I8" ,25 :"I16" ,26 :"I32" ,27 :"I64" ,28 :"F64" ,29 :"IQ1_M" , 12230 :"BF16" ,34 :"TQ1_0" ,35 :"TQ2_0" ,39 :"MXFP4" , 12342 :"Q2_0" ,# ISTA-DASLab GSQ-RCO 2-bit (Strata, llama.cpp fork type) 124143 :"PTQ1_0" ,144 :"TQ2_T" ,145 :"TQK6" ,146 :"TQK7" ,# agentionai Gyro (tools/gguf_reader.py has the block sizes) 125} 126 127 128class Buffered : 129"""Sequential reader over a remote header that fetches more bytes on demand.""" 130 131def __init__ (self ,src :Source ,first :int = 4 << 20 ): 132self .src ,self .buf ,self .pos = src ,src .read (0 ,first ),0 133 134def take (self ,n :int )-> bytes : 135while self .pos + n > len (self .buf ): 136if len (self .buf )>= self .src .size : 137raise EOFError (f" { self . src . name } : truncated header" ) 138self .buf += self .src .read (len (self .buf ),max (len (self .buf ),4 << 20 )) 139out = self .buf [self .pos :self .pos + n ] 140self .pos += n 141return out 142 143def u32 (self )-> int :return struct .unpack ("<I" ,self .take (4 ))[0 ] 144def u64 (self )-> int :return struct .unpack ("<Q" ,self .take (8 ))[0 ] 145def string (self )-> str :return self .take (self .u64 ()).decode ("utf-8" ,"replace" ) 146 147 148SCALAR = {0 :1 ,1 :1 ,2 :2 ,3 :2 ,4 :4 ,5 :4 ,6 :4 ,7 :1 ,10 :8 ,11 :8 ,12 :8 } 149 150 151def gguf_value (r :Buffered ,vtype :int ): 152if vtype == 8 : 153return r .string () 154if vtype == 9 : 155itype ,n = r .u32 (),r .u64 () 156if itype == 8 : 157items = [r .string ()for _ in range (n )]# must be consumed either way 158return items if n <= 64 else None 159if itype == 9 : 160raise ValueError ("nested GGUF arrays are not supported" ) 161size = SCALAR [itype ] 162r .take (size * n ) 163return None 164raw = r .take (SCALAR [vtype ]) 165fmt = {0 :"<B" ,1 :"<b" ,2 :"<H" ,3 :"<h" ,4 :"<I" ,5 :"<i" ,6 :"<f" ,7 :"<?" , 16610 :"<Q" ,11 :"<q" ,12 :"<d" }[vtype ] 167return struct .unpack (fmt ,raw )[0 ] 168 169 170def read_gguf (src :Source )-> tuple [dict ,list [dict ]]: 171r = Buffered (src ) 172if r .take (4 )!= b"GGUF" : 173raise ValueError (f" { src . name } : not a GGUF file" ) 174r .u32 ()# version 175n_tensors ,n_kv = r .u64 (),r .u64 () 176meta = {} 177for _ in range (n_kv ): 178key = r .string () 179meta [key ]= gguf_value (r ,r .u32 ()) 180tensors = [] 181for _ in range (n_tensors ): 182name = r .string () 183dims = [r .u64 ()for _ in range (r .u32 ())] 184ttype ,offset = r .u32 (),r .u64 () 185count = 1 186for d in dims : 187count *= d 188tensors .append ({"name" :name ,"type" :GGML_TYPES .get (ttype ,f"type# { ttype } " ), 189"elements" :count ,"offset" :offset }) 190align = int (meta .get ("general.alignment" )or 32 ) 191data_start = (r .pos + align - 1 )// align * align 192# Actual stored bytes from the offsets: exact for every type, including unknown ones. 193order = sorted (tensors ,key = lambda t :t ["offset" ]) 194for a ,b in zip (order ,order [1 :]+ [None ]): 195end = b ["offset" ]if b else src .size - data_start 196a ["bytes" ]= end - a ["offset" ] 197return meta ,tensors 198 199 200# ---------------------------------------------------------------- safetensors ---------------- 201 202ST_BYTES = {"F64" :8 ,"F32" :4 ,"F16" :2 ,"BF16" :2 ,"F8_E4M3" :1 ,"F8_E5M2" :1 ,"I64" :8 , 203"I32" :4 ,"I16" :2 ,"I8" :1 ,"U8" :1 ,"BOOL" :1 ,"F8_E8M0" :1 ,"U32" :4 } 204PACKED = re .compile (r"(qweight|weight_packed|\.blocks$|_blocks$)" ) 205 206 207def read_safetensors (src :Source ,bits :int | None )-> list [dict ]: 208n = struct .unpack ("<Q" ,src .read (0 ,8 ))[0 ] 209header = json .loads (src .read (8 ,n )) 210out = [] 211for name ,t in header .items (): 212if name == "__metadata__" : 213continue 214count = 1 215for d in t ["shape" ]: 216count *= d 217nbytes = count * ST_BYTES .get (t ["dtype" ],1 ) 218elements = count 219if PACKED .search (name ): 220# Packed integer codes: logical weights = stored bits / code bits. 221elements = nbytes * 8 // (bits or 4 ) 222elif re .search (r"(scales|zeros|qzeros|g_idx|scale$|_scale|zero_point)" ,name ): 223elements = 0 # metadata of a quantized weight: counts as bytes only 224out .append ({"name" :name ,"type" :t ["dtype" ],"elements" :elements ,"bytes" :nbytes }) 225return out 226 227 228# ---------------------------------------------------------------- NInfer v3 ------------------ 229 230NINFER_MAGIC = b"NINFER" + bytes ([0 ,3 ]) 231 232 233def read_ninfer (src :Source )-> list [dict ]: 234"""Logical parameters of a NInfer v3 .ninfer entry, from its directory JSON only. 235 236A stored object may hold several logical parameters (for example an expert bank); each 237binding's share of the object's stored bytes is proportional to its element range. 238""" 239head = src .read (0 ,32 ) 240magic ,json_bytes ,_artifact_id = struct .unpack ("<8sQ16s" ,head ) 241if magic != NINFER_MAGIC : 242raise ValueError (f" { src . name } : not a NInfer v3 entry" ) 243directory = json .loads (src .read (32 ,json_bytes )) 244objects = {o ["id" ]:o for o in directory ["objects" ]if o .get ("kind" ,"tensor" )== "tensor" } 245elements = {} 246for oid ,o in objects .items (): 247count = 1 248for d in o ["shape" ]: 249count *= d 250elements [oid ]= count 251out = [] 252for name ,binding in directory ["bindings" ].items (): 253parts = ([{"object" :binding ["object" ],"range" : [0 ,elements .get (binding ["object" ],0 )]}] 254if "object" in binding else binding .get ("parts" , [])) 255count = nbytes = 0 256fmt = None 257for part in parts : 258o = objects .get (part ["object" ]) 259if o is None : 260continue 261n = part ["range" ][1 ]- part ["range" ][0 ] 262count += n 263nbytes += o ["bytes" ]* n / max (elements [part ["object" ]],1 ) 264fmt = o ["format" ] 265if count : 266out .append ({"name" :name ,"type" : (fmt or "?" ).upper (),"elements" :count , 267"bytes" :nbytes }) 268return out 269 270 271# ---------------------------------------------------------------- summary -------------------- 272 273CATEGORIES = [ 274 ("norms" ,r"(norm)" ), 275 ("hyper-connections" ,r"(hc_|_hc\.|hyper_connection)" ), 276 ("routed experts" ,r"(_exps\b|\.experts\.|experts\.\d+|block_sparse_moe\.experts)" ), 277 ("shared experts" ,r"(_shexp|shared_expert|moe\.shared\.)" ), 278 ("router" ,r"(ffn_gate_inp|\.gate\.weight$|\.router\b|shared_score)" ), 279 ("n-gram/per-layer embeddings" ,r"(ngram|per_layer|ple_|\.ple\.)" ), 280 ("linear attn/SSM" ,r"(ssm_|linear_attn|mamba|conv1d|\.gdn\.)" ), 281# GGUF also names GatedDeltaNet input projections attn_qkv/attn_gate. 282 ("attention (incl. GDN qkv/gate)" ,r"(attn|attention|self_attn|indexer|\.q_proj|\.k_proj|" 283r"\.v_proj|\.o_proj)" ), 284 ("dense FFN" ,r"(ffn_|\.mlp\.)" ), 285 ("token embedding" ,r"(token_embd|embed_tokens|token_embedding|wte)" ), 286 ("output head" ,r"(^output\.|lm_head|output_head)" ), 287 ("MTP / nextn" ,r"(nextn|mtp)" ), 288] 289 290 291def category (name :str )-> str : 292n = name .lower ().replace ("/" ,"." )# NInfer logical names use slashes 293for label ,pattern in CATEGORIES : 294if re .search (pattern ,n ): 295return label 296return "other" 297 298 299def q_class (bpw :float )-> str : 300for limit ,label in [(1.9 ,"Q1 class" ), (2.8 ,"Q2 class" ), (3.7 ,"Q3 class" ), 301 (4.9 ,"Q4 class" ), (5.9 ,"Q5 class" ), (7.5 ,"Q6 class" ), 302 (10.0 ,"Q8 class" ), (17.0 ,"16-bit" )]: 303if bpw < limit : 304return label 305return "32-bit" 306 307 308def summarize (title :str ,tensors :list [dict ])-> dict : 309groups :dict [str ,dict ]= defaultdict (lambda : {"elements" :0 ,"bytes" :0 , 310"types" :defaultdict (int )}) 311for t in tensors : 312g = groups [category (t ["name" ])] 313g ["elements" ]+= t ["elements" ] 314g ["bytes" ]+= t ["bytes" ] 315g ["types" ][t ["type" ]]+= t ["bytes" ] 316total_e = sum (g ["elements" ]for g in groups .values ()) 317total_b = sum (g ["bytes" ]for g in groups .values ()) 318f"\n=== { title } ===" ) 319f"total { total_b / 1e9 :.2f } GB, { total_e / 1e9 :.2f } B weights, " 320f" { 8 * total_b / max ( total_e , 1 ):.2f } bits/weight overall" ) 321f" { 'group' :30s } { 'weights' :>9s } { 'GB' :>8s } { 'bits/w' :>7s } types (share of bytes)" ) 322for label ,g in sorted (groups .items (),key = lambda kv :- kv [1 ]["bytes" ]): 323bpw = 8 * g ["bytes" ]/ g ["elements" ]if g ["elements" ]else float ("nan" ) 324types = ", " .join (f" { k } { 100 * v / g [ 'bytes' ]:.0f } %" 325for k ,v in sorted (g ["types" ].items (),key = lambda kv :- kv [1 ])) 326f" { label :30s } { g [ 'elements' ] / 1e9 :8.2f } B { g [ 'bytes' ] / 1e9 :8.2f } { bpw :7.2f } { types } " ) 327experts = groups .get ("routed experts" ) 328verdict = None 329if experts and experts ["elements" ]: 330verdict = 8 * experts ["bytes" ]/ experts ["elements" ] 331f"-> routed experts are { verdict :.2f } bits/weight ( { q_class ( verdict ) } )" ) 332return {"title" :title ,"gb" :total_b / 1e9 ,"bpw" :8 * total_b / max (total_e ,1 ), 333"experts_bpw" :verdict } 334 335 336def scan (label :str ,files :list [Source ],meta_config :dict | None )-> dict : 337tensors :list [dict ]= [] 338for src in files : 339if src .name .endswith (".gguf" ): 340_meta ,ts = read_gguf (src ) 341elif src .name .endswith (".ninfer" ): 342ts = read_ninfer (src ) 343else : 344bits = None 345if meta_config : 346q = meta_config .get ("quantization_config" )or {} 347bits = q .get ("bits" )or q .get ("w_bit" ) 348ts = read_safetensors (src ,bits ) 349tensors += ts 350f" read header of { src . name } : { len ( ts ) } tensors" ,file = sys .stderr ) 351return summarize (label ,tensors ) 352 353 354def main ()-> None : 355parser = argparse .ArgumentParser (description = __doc__ , 356formatter_class = argparse .RawDescriptionHelpFormatter ) 357parser .add_argument ("source" ,help = "ms:owner/repo, hf:owner/repo, URL, file or directory" ) 358parser .add_argument ("variant" ,nargs = "?" ,help = "variant name or glob (e.g. UD-Q4_K_XL)" ) 359parser .add_argument ("--all" ,action = "store_true" ,help = "scan and compare every variant" ) 360args = parser .parse_args () 361 362files = [f for f in resolve (args .source ) 363if f .name .endswith ((".gguf" ,".safetensors" ,".ninfer" ))] 364config = None 365for f in resolve (args .source )if args .source .startswith (("ms:" ,"hf:" ))else []: 366if f .name == "config.json" : 367config = json .loads (http (f .url )) 368if config .get ("quantization_config" ): 369"config.json quantization_config:" , 370json .dumps (config ["quantization_config" ])[:400 ]) 371variants :dict [str ,list [Source ]]= defaultdict (list ) 372for f in files : 373variants [variant_of (f .name )].append (f ) 374if not variants : 375sys .exit ("no .gguf, .safetensors or .ninfer files found" ) 376if len (variants )> 1 and not args .variant and not args .all : 377"variants (pass one as the second argument, or --all):" ) 378for name ,fs in sorted (variants .items ()): 379f" { name :70s } { sum ( f . size for f in fs ) / 1e9 :8.2f } GB { len ( fs ) } file(s)" ) 380return 381chosen = {k :v for k ,v in variants .items () 382if args .all or not args .variant or args .variant in k 383or fnmatch .fnmatch (k ,args .variant )} 384results = [scan (name ,sorted (fs ,key = lambda f :f .name ),config ) 385for name ,fs in sorted (chosen .items ())] 386if len (results )> 1 : 387"\n=== comparison ===" ) 388f" { 'variant' :60s } { 'GB' :>8s } { 'bits/w' :>7s } { 'experts bits/w' :>15s } " ) 389for r in results : 390e = f" { r [ 'experts_bpw' ]:.2f } ( { q_class ( r [ 'experts_bpw' ]) } )" if r ["experts_bpw" ]else "-" 391f" { r [ 'title' ]:60s } { r [ 'gb' ]:8.2f } { r [ 'bpw' ]:7.2f } { e :>15s } " ) 392 393 394if __name__ == "__main__" : 395main ()