okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3"""tools/ds4/st.py - every tensor of a DeepSeek-V4.1 model directory, read in place. 4 5st = SafeTensors(Path("~/models/DSV4").expanduser()) 6st.t["layers.0.attn.wq_a.trellis"] -> (file, dtype, shape, absolute offset, bytes) 7st.raw(name), st.f32(name) -> numpy views / float32 copies 8 9The index's own files come first; any other .safetensors in the directory (the Engram shards 47 / 48 of the base 10repo, model-0004[78]-of-00048.safetensors) only adds names the index does not have. 11""" 12from __future__import annotations 13 14import json 15import pathlib 16import struct 17 18import numpy as np 19 20DTYPE_BYTES = {"F32" :4 ,"F16" :2 ,"BF16" :2 ,"I32" :4 ,"I16" :2 ,"F8_E4M3" :1 ,"F8_E8M0" :1 ,"U8" :1 ,"I8" :1 , 21"I64" :8 } 22 23 24class SafeTensors : 25def __init__ (self ,d :pathlib .Path ): 26self .dir = pathlib .Path (d ) 27ix = json .loads ((self .dir / "model.safetensors.index.json" ).read_text ())["weight_map" ] 28primary = sorted (set (ix .values ())) 29others = sorted (p .name for p in self .dir .glob ("*.safetensors" )if p .name not in primary ) 30self .files :list [str ]= [] 31self .t :dict [str ,tuple ]= {} 32self .mm :dict [str ,np .memmap ]= {} 33for fn in primary + others : 34p = self .dir / fn 35with p .open ("rb" )as f : 36n = struct .unpack ("<Q" ,f .read (8 ))[0 ] 37h = json .loads (f .read (n )) 38base = 8 + n 39self .files .append (fn ) 40for k ,v in h .items (): 41if k == "__metadata__" or k in self .t : 42continue 43a ,b = v ["data_offsets" ] 44self .t [k ]= (fn ,v ["dtype" ],tuple (v ["shape" ]),base + a ,b - a ) 45self .mm [fn ]= np .memmap (p ,dtype = np .uint8 ,mode = "r" ) 46 47def has (self ,name :str )-> bool : 48return name in self .t 49 50def raw (self ,name :str )-> np .ndarray : 51fn ,_ ,_ ,off ,nb = self .t [name ] 52return self .mm [fn ][off :off + nb ] 53 54def f32 (self ,name :str )-> np .ndarray : 55"""The tensor as float32 (exact for F32/F16/BF16), shaped as stored.""" 56_ ,dt ,shape ,_ ,_ = self .t [name ] 57r = self .raw (name ) 58if dt == "F32" : 59a = r .view ("<f4" ) 60elif dt == "F16" : 61a = r .view ("<f2" ).astype (np .float32 ) 62elif dt == "BF16" : 63a = (r .view ("<u2" ).astype (np .uint32 )<< 16 ).view (np .float32 ) 64else : 65raise ValueError ("%s is %s, not a float tensor" % (name ,dt )) 66return a .reshape (shape )