okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""hf_slice.py - read single tensors (or slices of them) out of a remote safetensors repo with HTTP range requests, so a 2quality test needs megabytes of a model, not the model. No token is read or printed (public repos only; set HF_TOKEN in 3the environment for gated ones - it is sent as a header and never printed). 4 5from hf_slice import Repo 6r = Repo("Qwen/Qwen3.8-Flash-Next") 7w = r.tensor("model.language_model.layers.0.mlp.experts.gate_up_proj", rows=slice(0, 1)) # expert 0 only 8""" 9from __future__import annotations 10 11import concurrent .futures as cf 12import json 13import os 14import struct 15import urllib .request 16 17import numpy as np 18 19_DT = {"BF16" : (2 ,None ),"F16" : (2 ,np .float16 ),"F32" : (4 ,np .float32 ),"F8_E4M3" : (1 ,None ),"I8" : (1 ,np .int8 ), 20"U8" : (1 ,np .uint8 ),"I32" : (4 ,np .int32 ),"I64" : (8 ,np .int64 )} 21 22 23def _get (url :str ,start :int | None = None ,end :int | None = None )-> bytes : 24req = urllib .request .Request (url ) 25tok = os .environ .get ("HF_TOKEN" ) 26if tok : 27req .add_header ("Authorization" ,"Bearer " + tok ) 28if start is not None : 29req .add_header ("Range" ,"bytes=%d-%d" % (start ,end )) 30with urllib .request .urlopen (req ,timeout = 120 )as r : 31return r .read () 32 33 34def get_parallel (url :str ,start :int ,end :int ,workers :int = 16 ,piece :int = 8 << 20 )-> bytes : 35"""bytes start..end (inclusive) of url, in `piece`-byte range requests on `workers` threads (one stream of a CDN 36object is slow, a dozen are not).""" 37spans = [(a ,min (end ,a + piece - 1 ))for a in range (start ,end + 1 ,piece )] 38if len (spans )== 1 : 39return _get (url ,start ,end ) 40 41def one (sp ): 42for attempt in range (6 ): 43try : 44return _get (url ,sp [0 ],sp [1 ]) 45except Exception : 46if attempt == 5 : 47raise 48return b"" 49with cf .ThreadPoolExecutor (workers )as ex : 50return b"" .join (ex .map (one ,spans )) 51 52 53def bf16_to_f32 (raw :bytes | np .ndarray )-> np .ndarray : 54u = np .frombuffer (raw ,dtype = np .uint16 ).astype (np .uint32 )<< 16 55return u .view (np .float32 ) 56 57 58class Repo : 59def __init__ (self ,repo :str ,rev :str = "main" ): 60self .repo ,self .rev = repo ,rev 61self .base = "https://huggingface.co/%s/resolve/%s/" % (repo ,rev ) 62self .map = json .loads (_get (self .base + "model.safetensors.index.json" ))["weight_map" ] 63self ._hdr :dict [str ,tuple [dict ,int ]]= {} 64 65def header (self ,shard :str ): 66if shard not in self ._hdr : 67n = struct .unpack ("<Q" ,_get (self .base + shard ,0 ,7 ))[0 ] 68h = json .loads (_get (self .base + shard ,8 ,8 + n - 1 )) 69self ._hdr [shard ]= (h ,8 + n ) 70return self ._hdr [shard ] 71 72def info (self ,name :str ): 73shard = self .map [name ] 74h ,base = self .header (shard ) 75return shard ,h [name ],base 76 77def tensor (self ,name :str ,lead :slice | int | None = None ,workers :int = 16 )-> np .ndarray : 78"""The tensor `name` as float32. lead: an index or slice on the first axis (e.g. an expert), fetched alone.""" 79shard ,t ,base = self .info (name ) 80shape = t ["shape" ] 81item = _DT [t ["dtype" ]][0 ] 82s ,e = t ["data_offsets" ] 83inner = int (np .prod (shape [1 :]))* item if len (shape )> 1 else item 84if lead is None : 85i0 ,i1 = 0 ,shape [0 ] 86elif isinstance (lead ,int ): 87i0 ,i1 = lead ,lead + 1 88else : 89i0 ,i1 = lead .start or 0 ,lead .stop 90raw = get_parallel (self .base + shard ,base + s + i0 * inner ,base + s + i1 * inner - 1 ,workers ) 91out_shape = [i1 - i0 ]+ shape [1 :] 92if t ["dtype" ]== "BF16" : 93return bf16_to_f32 (raw ).reshape (out_shape ) 94return np .frombuffer (raw ,dtype = _DT [t ["dtype" ]][1 ]).astype (np .float32 ).reshape (out_shape )