okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
10.1 KiB210 linesraw
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
9    python 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):
43    pass
44
45
46def manifest_entry(path: pathlib.Path = MANIFEST) -> dict:
47    v = json.loads(path.read_text(encoding="utf-8")).get("vision") or {}
48    if not v.get("files") or not v.get("marks"):
49        raise SystemExit(f"{path}: no \"vision\" entry")
50    return 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
55    else is cut off unread: RangeError), or a local file / file:// URL read at the offset."""
56    if not url.startswith(("http://", "https://")):
57        p = pathlib.Path(url[7:] if url.startswith("file://") else url)
58        with p.open("rb") as f:
59            f.seek(start)
60            b = f.read(n)
61        if len(b) != n:
62            raise RangeError(f"{p}: {len(b)} of {n} bytes at {start}")
63        return b
64    end = start + n - 1
65    req = urllib.request.Request(url, headers={"User-Agent": "maya-setup", "Range": f"bytes={start}-{end}",
66                                               "Accept-Encoding": "identity"})
67    try:
68        with urllib.request.urlopen(req, timeout=timeout) as r:
69            cr = r.headers.get("Content-Range", "")
70            want = f"bytes {start}-{end}/"
71            if 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)
73                raise RangeError(f"the server answered status {r.status} ({cr or 'no Content-Range'}) to a request for "
74                                 f"bytes {start}-{end}, not just those bytes")
75            b = r.read(n + 1)
76    except OSError as e:
77        raise RangeError(str(e)) from e
78    if len(b) != n:
79        raise RangeError(f"{len(b)} bytes arrived for a range of {n}")
80    return 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
85    sha256 checked.  Each step is tried `tries` times; then SystemExit with the reason."""
86    rows = marks["rows"]
87    total = marks.get("bytes")
88    why = ""
89    for attempt in range(tries):
90        try:
91            n = struct.unpack("<Q", read_range(url, 0, 8, total))[0]
92            if not 0 < n < 1 << 24:
93                raise RangeError(f"a safetensors header of {n} bytes")
94            head = json.loads(read_range(url, 8, n, total))
95            base = 8 + n
96            at = {}
97            for name, (off, nb, _sha) in rows.items():
98                e = head.get(name) or {}
99                a, b = e.get("data_offsets") or (None, None)
100                if e.get("dtype") != "BF16" or a is None or base + a != off or b - a != nb:
101                    raise RangeError(f"{name} is not where the manifest says ({e or 'not in the header'})")
102                at[name] = (off, nb)
103            lo = min(o for o, _ in at.values())
104            hi = max(o + nb for o, nb in at.values())
105            if hi - lo > 1 << 20:
106                raise RangeError(f"the marker rows span {hi - lo} bytes: not read in one piece")
107            blob = read_range(url, lo, hi - lo, total)
108            out = {}
109            for name, (off, nb) in at.items():
110                out[name] = blob[off - lo:off - lo + nb]
111                if hashlib.sha256(out[name]).hexdigest() != rows[name][2]:
112                    raise RangeError(f"{name}: the sha256 does not match the manifest's")
113            return out
114        except (RangeError, ValueError) as e:
115            why = str(e)
116            if attempt + 1 < tries:
117                print(f"vision: the marker rows: {why}; trying once more ...", file=sys.stderr)
118                time.sleep(2)
119    raise 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):
124    raw = np.memmap(path, np.uint8, mode="r")
125    n = struct.unpack("<Q", bytes(raw[:8]))[0]
126    head = json.loads(bytes(raw[8:8 + n]))
127    head.pop("__metadata__", None)
128    return 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."""
133    out = {}
134    for k, v in (cfg.get("vision_config") or {}).items():
135        if isinstance(v, (int, float)) and not isinstance(v, bool):
136            out["vision.%s" % k] = v
137    if isinstance(cfg.get("image_token_id"), int):
138        out["image_token_id"] = cfg["image_token_id"]
139    if not out.get("vision.num_hidden_layers") or "image_token_id" not in out:
140        raise SystemExit("config.json: no vision_config / image_token_id")
141    return out
142
143
144def pack(d: pathlib.Path, man: dict, marks_url: str | None = None) -> dict:
145    names = [n for n in man["files"] if n.endswith(".safetensors")]
146    if len(names) != 1:
147        raise SystemExit("the manifest's vision entry: one safetensors shard expected")
148    src = d / names[0]
149    if not src.is_file() or src.stat().st_size != man["files"][names[0]][0]:
150        raise SystemExit(f"{src}: missing or not whole")
151    geo = geometry(json.loads((d / "config.json").read_text(encoding="utf-8")))
152    mk = man["marks"]
153    url = marks_url or HF.format(repo=man["repo"], revision=man["revision"], path=mk["file"])
154    rows = fetch_marks(url, mk)
155    raw, head, base = shard(src)
156    order = sorted(head, key=lambda t: head[t]["data_offsets"][0])
157    for t in order:
158        if not t.startswith(("vision.", "aligner.")):
159            raise SystemExit(f"{src.name}: {t} is not the vision tower's")
160    entries, off = [], 0
161    part = d / "vision.bin.part"
162    with part.open("wb") as f:
163        def put(name, dtype, shape, b):
164            nonlocal off
165            f.write(b)
166            entries.append([name, dtype, off, len(b), list(shape)])
167            off += len(b)
168            pad = (-off) % ALIGN
169            f.write(b"\0" * pad)
170            off += pad
171        for t in order:
172            e = head[t]
173            a, b = e["data_offsets"]
174            put(t, e["dtype"], e["shape"], raw[base + a:base + b].tobytes())
175        for name in MARKS:
176            put(name, "BF16", [len(rows[name]) // 2], rows[name])
177    # read back: every tensor as the checkpoint has it, bit for bit
178    back = np.memmap(part, np.uint8, mode="r")
179    for name, _dt, o, nb, _shape in entries:
180        if name in rows:
181            ok = back[o:o + nb].tobytes() == rows[name]
182        else:
183            a, b = head[name]["data_offsets"]
184            ok = np.array_equal(back[o:o + nb], raw[base + a:base + b])
185        if not ok:
186            raise SystemExit(f"vision.bin: {name} differs from the checkpoint after the copy")
187    del back, raw
188    part.replace(d / "vision.bin")
189    info = {"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))
192    return info
193
194
195def main() -> int:
196    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
197    ap.add_argument("--dir", required=True, help="the folder with shard 1 and config.json")
198    ap.add_argument("--manifest", default=str(MANIFEST))
199    ap.add_argument("--marks-url", help="shard 2 elsewhere (a URL or a local file; default: Hugging Face, pinned)")
200    a = ap.parse_args()
201    d = pathlib.Path(a.dir)
202    info = pack(d, manifest_entry(pathlib.Path(a.manifest)), a.marks_url)
203    nb = sum(e[3] for e in info["tensors"])
204    print(f"vision.bin: {len(info['tensors'])} tensors ({nb / 1e9:.2f} GB), every one equal to the checkpoint's; "
205          f"{info['config']['vision.num_hidden_layers']} blocks, image token {info['config']['image_token_id']}")
206    return 0
207
208
209if __name__ == "__main__":
210    sys.exit(main())