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/vision_pack.py - DeepSeek-V4.1's vision tower (the part of the model that reads pictures, which the GGUFs 4leave out) for a GGUF install: shard 1 of DeepSeek's own checkpoint (model-00001-of-00048, the tower's vision.* and the 5aligner's aligner.* tensors, BF16, nothing else) and config.json (their geometry) from download_gguf.json's "vision" 6entry, plus the picture span's three marker rows (image_start, image_newline, image_end: BF16 [5120]), which sit beside 7the embedding in shard 2 - only their 30 KB are read from it, with an HTTP range request, never the 1.3 GB file. 8 9python tools/ds4/vision_pack.py --dir <folder with shard 1 and config.json> -> vision.bin + vision.json there 10 11vision.bin holds every tensor exactly as the checkpoint has it (copied, 256-byte aligned) and then the three marker 12rows; it is read back and compared with the shard bit for bit before it is kept. vision.json lists every tensor (name, 13dtype, offset, bytes, shape) as tensors.txt does, and the geometry the engine reads (vision.<key> from config.json's 14vision_config, image_token_id); pack_gguf.py adds both to the pack. 15 16The marker rows: the shard's header (a range request), then the rows (one range request), each row's sha256 checked 17against the manifest's. A server that answers a range request with the whole file (status 200, not 206) is cut off at 18once, the request is tried once more, then this stops with the reason - nothing large is ever downloaded here. 19--marks-url takes another URL, or a local file (a mirror, the tests). 20""" 21from __future__import annotations 22 23import argparse 24import hashlib 25import json 26import pathlib 27import struct 28import sys 29import time 30import urllib .request 31 32import numpy as np 33 34HERE = pathlib .Path (__file__ ).resolve ().parent 35MANIFEST = HERE / "download_gguf.json" 36HF = "https://huggingface.co/{repo}/resolve/{revision}/{path}" 37ALIGN = 256 38MARKS = ("image_start" ,"image_newline" ,"image_end" )# (the order in vision.bin) 39TRIES = 2 # a range request and one retry 40 41 42class RangeError (Exception ): 43pass 44 45 46def manifest_entry (path :pathlib .Path = MANIFEST )-> dict : 47v = json .loads (path .read_text (encoding = "utf-8" )).get ("vision" )or {} 48if not v .get ("files" )or not v .get ("marks" ): 49raise SystemExit (f" { path } : no \"vision\" entry" ) 50return v 51 52 53def read_range (url :str ,start :int ,n :int ,total :int | None = None ,timeout :int = 60 )-> bytes : 54"""Bytes start .. start + n - 1 of a file: a URL with a range request (exactly those bytes, status 206 - anything 55else is cut off unread: RangeError), or a local file / file:// URL read at the offset.""" 56if not url .startswith (("http://" ,"https://" )): 57p = pathlib .Path (url [7 :]if url .startswith ("file://" )else url ) 58with p .open ("rb" )as f : 59f .seek (start ) 60b = f .read (n ) 61if len (b )!= n : 62raise RangeError (f" { p } : { len ( b ) } of { n } bytes at { start } " ) 63return b 64end = start + n - 1 65req = urllib .request .Request (url ,headers = {"User-Agent" :"maya-setup" ,"Range" :f"bytes= { start } - { end } " , 66"Accept-Encoding" :"identity" }) 67try : 68with urllib .request .urlopen (req ,timeout = timeout )as r : 69cr = r .headers .get ("Content-Range" ,"" ) 70want = f"bytes { start } - { end } /" 71if r .status != 206 or not cr .startswith (want )or (total and cr != f" { want } { total } " ): 72# (the whole file, or other bytes: the connection is closed here without reading the body) 73raise RangeError (f"the server answered status { r . status } ( { cr or 'no Content-Range' } ) to a request for " 74f"bytes { start } - { end } , not just those bytes" ) 75b = r .read (n + 1 ) 76except OSError as e : 77raise RangeError (str (e ))from e 78if len (b )!= n : 79raise RangeError (f" { len ( b ) } bytes arrived for a range of { n } " ) 80return b 81 82 83def fetch_marks (url :str ,marks :dict ,tries :int = TRIES )-> dict : 84"""The marker rows {name: bytes} from shard 2 at `url`: its header (where they are), then the rows, every row's 85sha256 checked. Each step is tried `tries` times; then SystemExit with the reason.""" 86rows = marks ["rows" ] 87total = marks .get ("bytes" ) 88why = "" 89for attempt in range (tries ): 90try : 91n = struct .unpack ("<Q" ,read_range (url ,0 ,8 ,total ))[0 ] 92if not 0 < n < 1 << 24 : 93raise RangeError (f"a safetensors header of { n } bytes" ) 94head = json .loads (read_range (url ,8 ,n ,total )) 95base = 8 + n 96at = {} 97for name , (off ,nb ,_sha )in rows .items (): 98e = head .get (name )or {} 99a ,b = e .get ("data_offsets" )or (None ,None ) 100if e .get ("dtype" )!= "BF16" or a is None or base + a != off or b - a != nb : 101raise RangeError (f" { name } is not where the manifest says ( { e or 'not in the header' } )" ) 102at [name ]= (off ,nb ) 103lo = min (o for o ,_ in at .values ()) 104hi = max (o + nb for o ,nb in at .values ()) 105if hi - lo > 1 << 20 : 106raise RangeError (f"the marker rows span { hi - lo } bytes: not read in one piece" ) 107blob = read_range (url ,lo ,hi - lo ,total ) 108out = {} 109for name , (off ,nb )in at .items (): 110out [name ]= blob [off - lo :off - lo + nb ] 111if hashlib .sha256 (out [name ]).hexdigest ()!= rows [name ][2 ]: 112raise RangeError (f" { name } : the sha256 does not match the manifest's" ) 113return out 114except (RangeError ,ValueError )as e : 115why = str (e ) 116if attempt + 1 < tries : 117f"vision: the marker rows: { why } ; trying once more ..." ,file = sys .stderr ) 118time .sleep (2 ) 119raise SystemExit (f"vision: the picture markers (30 KB of { marks [ 'file' ] } ) could not be read: { why } . Nothing large " 120"was downloaded. Check the connection and run the setup again (or --no-vision: text only)." ) 121 122 123def shard (path :pathlib .Path ): 124raw = np .memmap (path ,np .uint8 ,mode = "r" ) 125n = struct .unpack ("<Q" ,bytes (raw [:8 ]))[0 ] 126head = json .loads (bytes (raw [8 :8 + n ])) 127head .pop ("__metadata__" ,None ) 128return raw ,head ,8 + n 129 130 131def geometry (cfg :dict )-> dict : 132"""pack.py's vision keys: vision.<key> for config.json's numeric vision_config entries, and image_token_id.""" 133out = {} 134for k ,v in (cfg .get ("vision_config" )or {}).items (): 135if isinstance (v , (int ,float ))and not isinstance (v ,bool ): 136out ["vision.%s" % k ]= v 137if isinstance (cfg .get ("image_token_id" ),int ): 138out ["image_token_id" ]= cfg ["image_token_id" ] 139if not out .get ("vision.num_hidden_layers" )or "image_token_id" not in out : 140raise SystemExit ("config.json: no vision_config / image_token_id" ) 141return out 142 143 144def pack (d :pathlib .Path ,man :dict ,marks_url :str | None = None )-> dict : 145names = [n for n in man ["files" ]if n .endswith (".safetensors" )] 146if len (names )!= 1 : 147raise SystemExit ("the manifest's vision entry: one safetensors shard expected" ) 148src = d / names [0 ] 149if not src .is_file ()or src .stat ().st_size != man ["files" ][names [0 ]][0 ]: 150raise SystemExit (f" { src } : missing or not whole" ) 151geo = geometry (json .loads ((d / "config.json" ).read_text (encoding = "utf-8" ))) 152mk = man ["marks" ] 153url = marks_url or HF .format (repo = man ["repo" ],revision = man ["revision" ],path = mk ["file" ]) 154rows = fetch_marks (url ,mk ) 155raw ,head ,base = shard (src ) 156order = sorted (head ,key = lambda t :head [t ]["data_offsets" ][0 ]) 157for t in order : 158if not t .startswith (("vision." ,"aligner." )): 159raise SystemExit (f" { src . name } : { t } is not the vision tower's" ) 160entries ,off = [],0 161part = d / "vision.bin.part" 162with part .open ("wb" )as f : 163def put (name ,dtype ,shape ,b ): 164nonlocal off 165f .write (b ) 166entries .append ([name ,dtype ,off ,len (b ),list (shape )]) 167off += len (b ) 168pad = (- off )% ALIGN 169f .write (b"\0" * pad ) 170off += pad 171for t in order : 172e = head [t ] 173a ,b = e ["data_offsets" ] 174put (t ,e ["dtype" ],e ["shape" ],raw [base + a :base + b ].tobytes ()) 175for name in MARKS : 176put (name ,"BF16" , [len (rows [name ])// 2 ],rows [name ]) 177# read back: every tensor as the checkpoint has it, bit for bit 178back = np .memmap (part ,np .uint8 ,mode = "r" ) 179for name ,_dt ,o ,nb ,_shape in entries : 180if name in rows : 181ok = back [o :o + nb ].tobytes ()== rows [name ] 182else : 183a ,b = head [name ]["data_offsets" ] 184ok = np .array_equal (back [o :o + nb ],raw [base + a :base + b ]) 185if not ok : 186raise SystemExit (f"vision.bin: { name } differs from the checkpoint after the copy" ) 187del back ,raw 188part .replace (d / "vision.bin" ) 189info = {"from" : {"repo" :man ["repo" ],"revision" :man ["revision" ],"files" :sorted (man ["files" ]), 190"marks" :mk ["file" ]},"config" :geo ,"tensors" :entries } 191 (d / "vision.json" ).write_text (json .dumps (info )) 192return info 193 194 195def main ()-> int : 196ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 197ap .add_argument ("--dir" ,required = True ,help = "the folder with shard 1 and config.json" ) 198ap .add_argument ("--manifest" ,default = str (MANIFEST )) 199ap .add_argument ("--marks-url" ,help = "shard 2 elsewhere (a URL or a local file; default: Hugging Face, pinned)" ) 200a = ap .parse_args () 201d = pathlib .Path (a .dir ) 202info = pack (d ,manifest_entry (pathlib .Path (a .manifest )),a .marks_url ) 203nb = sum (e [3 ]for e in info ["tensors" ]) 204f"vision.bin: { len ( info [ 'tensors' ]) } tensors ( { nb / 1e9 :.2f } GB), every one equal to the checkpoint's; " 205f" { info [ 'config' ][ 'vision.num_hidden_layers' ] } blocks, image token { info [ 'config' ][ 'image_token_id' ] } " ) 206return 0 207 208 209if __name__ == "__main__" : 210sys .exit (main ())