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
14.6 KiB318 linesraw
1#!/usr/bin/env python3
2"""ista_intake.py - one command per IST-DAS commit (DEEPSEEK-ISTA-PLAN Phase 0).
3
4For a pinned HF commit and one or more of its sets it:
5  1. lists the repo tree at that commit (path + size) and writes it to the report folder;
6  2. downloads only files that are absent or have the wrong size, into <root>/<set>/;
7  3. hashes everything into <root>/SHA256SUMS-<commit>-<set>.txt and hard-links duplicates (the Engram file is the same
8     110.6 GB blob in all three sets, so it is stored once);
9  4. reads the GGUF headers and reports every tensor type with its count and bytes, flagging types the device kernels do
10     not take (the same set --pack-info prints as "no GPU kernel");
11  5. builds a pointer pack with pack_gguf.py - no requant, the file as published;
12  6. runs --pack-info, the scripted eval (session16.sh, 4995 positions) and a speed smoke (code + agent, DSpark off/on);
13  7. writes one report per commit and set: <report-dir>/<commit>/<set>.md, every number tagged with the commit.
14
15Nothing here requantises or rewrites a GGUF. Exit codes: 0 ok, 1 a stage failed (the report says which), 2 bad usage.
16
17usage:
18  ista_intake.py --commit 9e2528f --sets 2.00bpw,2.25bpw
19  ista_intake.py --commit 9e2528f --sets 2.00bpw --no-eval      # download + pack only
20  ista_intake.py --commit 9e2528f --sets 2.00bpw --no-download   # headers + pack + eval on what is on disk
21"""
22from __future__ import annotations
23
24import argparse
25import hashlib
26import json
27import os
28import pathlib
29import re
30import shutil
31import subprocess
32import sys
33import time
34
35REPO = "helcig/tmp-oct26"
36ROOT = pathlib.Path("/data/helcig")
37REPORTS = pathlib.Path("/data/dsv41-port/runs/intake")
38PORT = pathlib.Path("/data/dsv41-port")
39PY = "/data/dsv41/hfvenv/bin/python"
40HF = "/data/dsv41/hfvenv/bin/hf"
41TOOLS = PORT / "src/tools/dsv41"
42# the substitutions the published sets need today (HANDOVER.md §6; Phase 1 removes them)
43# the Engram every live pack uses: the reference MXFP8 tables (shards 8/9 of the UD set, 203 GB).  The IST-DAS IQ4_NL
44# Engram (110.6 GB) is a separate Phase 1.3 experiment, so the intake does not depend on it.
45ENGRAM_DIR = pathlib.Path("/home/niko/dsv41-c0/t2/Engram")
46DSPARK = pathlib.Path("/data/dsv41/source/dspark-DeepSeek-V4.1-Flash-1017-Q8_0.gguf")
47DENSE_WOA = pathlib.Path("/home/niko/dsv41-dense/woaQ5_K")
48DENSE_HEAD = pathlib.Path("/home/niko/dsv41-dense/headQ6_K")
49# the UD set's first shard carries the Engram hash parameters as ple.* metadata and the vision tower carries the mmproj
50ENGRAM_META = pathlib.Path("/data/dsv41/source/UD-Q8_K_XL/DeepSeek-V4.1-Flash-1017-UD-Q8_K_XL-00001-of-00009.gguf")
51MMPROJ = pathlib.Path("/data/dsv41/source/mmproj-BF16.gguf")
52DSPARK_NOISE = "128799"     # dspark_noise_token_id for this model (see the h225 pack)
53DSPARK_RANK = "256"         # dspark_markov_rank
54# ggml type ids the device kernels take (src/dsv41/ds4_iq.cu's supported() plus MXFP4); kept in sync with --pack-info
55DEVICE_TYPES = {0, 1, 2, 3, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 29, 39}
56TYPE_NAMES = {0: "F32", 1: "F16", 2: "Q4_0", 3: "Q4_1", 6: "Q5_0", 7: "Q5_1", 8: "Q8_0", 9: "Q8_1",
57              10: "Q2_K", 11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", 15: "Q8_K",
58              16: "IQ2_XXS", 17: "IQ2_XS", 18: "IQ3_XXS", 19: "IQ1_S", 20: "IQ4_NL", 21: "IQ3_S",
59              22: "IQ2_S", 23: "IQ4_XS", 24: "I8", 25: "I16", 26: "I32", 27: "I64", 28: "F64",
60              29: "IQ1_M", 30: "BF16", 39: "MXFP4"}
61
62
63def log(msg: str) -> None:
64    print("%s %s" % (time.strftime("%H:%M:%S"), msg), flush=True)
65
66
67def run(cmd: list[str], **kw) -> subprocess.CompletedProcess:
68    return subprocess.run(cmd, capture_output=True, text=True, **kw)
69
70
71def sha256_file(p: pathlib.Path, chunk: int = 1 << 24) -> str:
72    h = hashlib.sha256()
73    with open(p, "rb") as f:
74        while True:
75            b = f.read(chunk)
76            if not b:
77                break
78            h.update(b)
79    return h.hexdigest()
80
81
82def repo_tree(commit: str) -> list[tuple[str, int]]:
83    from huggingface_hub import HfApi
84    rows = []
85    for f in HfApi().list_repo_tree(REPO, revision=commit, recursive=True):
86        size = getattr(f, "size", None)
87        if size:
88            rows.append((f.path, int(size)))
89    return sorted(rows)
90
91
92def local_path(root: pathlib.Path, repo_path: str) -> pathlib.Path:
93    return root / repo_path
94
95
96def download(commit: str, repo_path: str, dest_root: pathlib.Path) -> int:
97    dest_root.mkdir(parents=True, exist_ok=True)
98    r = run([HF, "download", REPO, "--revision", commit, "--include", repo_path, "--local-dir", str(dest_root)])
99    if r.returncode != 0:
100        log("  download failed: %s" % (r.stderr or r.stdout)[-300:])
101    return r.returncode
102
103
104def tensor_types(shards: list[pathlib.Path]) -> dict[int, tuple[int, int]]:
105    """type id -> (tensor count, bytes) over the shards, using pack_gguf's Gguf reader and its block table."""
106    sys.path.insert(0, str(TOOLS))
107    import pack_gguf  # noqa: E402
108    types = dict(pack_gguf.TYPES)
109    # pack_gguf's table covers the quant types; the intake also meets these (ggml ids, values/block, bytes/block)
110    types.update({2: ("Q4_0", 32, 18), 3: ("Q4_1", 32, 20), 6: ("Q5_0", 32, 22), 7: ("Q5_1", 32, 24),
111                  9: ("Q8_1", 32, 36), 15: ("Q8_K", 256, 292), 19: ("IQ1_S", 256, 50), 29: ("IQ1_M", 256, 56),
112                  24: ("I8", 1, 1), 25: ("I16", 1, 2), 26: ("I32", 1, 4), 27: ("I64", 1, 8), 28: ("F64", 1, 8)})
113    out: dict[int, tuple[int, int]] = {}
114    for s in shards:
115        g = pack_gguf.Gguf(s)
116        for name, typ, dims, off in g.tensors:          # (name, type, dims, offset); the file handle is closed already
117            t = types.get(typ)
118            if t is None:
119                out[typ] = (out.get(typ, (0, 0))[0] + 1, out.get(typ, (0, 0))[1])
120                continue
121            nvals = 1
122            for d in dims:
123                nvals *= int(d)
124            nbytes = (nvals // t[1]) * t[2] if t[1] > 1 else nvals * t[2]
125            c, b = out.get(typ, (0, 0))
126            out[typ] = (c + 1, b + nbytes)
127    return out
128
129
130def pack_set(commit: str, set_name: str, root: pathlib.Path, report: list[str]) -> pathlib.Path | None:
131    setdir = root / set_name
132    pack = PORT / "packs" / ("ista_%s_%s" % (set_name, commit[:7]))
133    if pack.exists():
134        report.append("- pack already exists: %s" % pack)
135        return pack
136    # the exact recipe the hand-built h225 pack used (HANDOVER.md §6 and h4_225.sh): no requant, our MXFP8 Engram, and the
137    # three workarounds Phase 1 removes - the interleaved 3-D attn_output_a, the engram_(k|q|wkv) tensors, and the Engram
138    # hash parameters that live in the UD set's metadata (--engram-meta), without which pack_gguf sees no Engram layers.
139    cmd = [PY, str(TOOLS / "pack_gguf.py"), "--model", str(setdir), "--out", str(pack)]
140    if ENGRAM_DIR.exists():
141        cmd += ["--engram", str(ENGRAM_DIR)]
142    if ENGRAM_META.exists():
143        cmd += ["--engram-meta", str(ENGRAM_META)]
144    if MMPROJ.exists():
145        cmd += ["--mmproj", str(MMPROJ)]
146    if DENSE_WOA.exists():
147        cmd += ["--dense-override", str(DENSE_WOA)]
148    if DENSE_HEAD.exists():
149        cmd += ["--dense-override", str(DENSE_HEAD)]
150    cmd += ["--skip-tensors", r"attn_output_a|engram_(k|q|wkv)\."]
151    if DSPARK.exists():
152        # pack_gguf fills the block/MTP geometry from the drafter but not the noise token or the markov rank: without them
153        # the pack reports dspark_noise_token_id 0 and DSpark drafts one token a round (the 2026-10-22 bug).
154        cmd += ["--dspark-gguf", str(DSPARK), "--dspark-noise-token", DSPARK_NOISE, "--dspark-markov-rank", DSPARK_RANK]
155    log("  pack: %s" % " ".join(cmd[2:]))
156    r = run(cmd, cwd=str(PORT))
157    (PORT / "runs").mkdir(exist_ok=True)
158    (PORT / "runs" / ("pack_%s_%s.log" % (set_name, commit[:7]))).write_text((r.stdout or "") + (r.stderr or ""))
159    if r.returncode != 0:
160        report.append("- pack FAILED (rc %d), see runs/pack_%s_%s.log" % (r.returncode, set_name, commit[:7]))
161        return None
162    report.append("- pack: %s" % pack)
163    return pack
164
165
166def tensor_names(setdir: pathlib.Path) -> list[str]:
167    sys.path.insert(0, str(TOOLS))
168    try:
169        import pack_gguf
170    except Exception:
171        return []
172    names = []
173    for s in sorted(setdir.glob("*.gguf")):
174        try:
175            g = pack_gguf.Gguf(s)
176            names += [t[0] for t in g.tensors]
177            g.close()
178        except Exception:
179            continue
180    return names
181
182
183def pack_info(pack: pathlib.Path) -> str:
184    r = run(["bash", "-lc", ". /data/dsv41-port/env.sh; cd /data/dsv41-port && ./build/strata-dsv41 --pack-info --pack %s"
185             % pack])
186    return (r.stdout or "") + (r.stderr or "")
187
188
189def eval_pack(pack: pathlib.Path, tag: str) -> list[str]:
190    # session16.sh takes the pack directory NAME (it prefixes packs/ itself), never a path
191    r = run(["bash", "-lc", "cd /data/dsv41-port && bash session16.sh %s" % pack.name])
192    (PORT / "runs" / ("eval_%s.log" % tag)).write_text((r.stdout or "") + (r.stderr or ""))
193    rows = [l for l in (r.stdout or "").splitlines() if l.startswith("s16_") or l.startswith("rc=")]
194    return rows
195
196
197def speed_smoke(pack: pathlib.Path, tag: str) -> list[str]:
198    out = []
199    ids = (PORT / "prompts/sa_code.ids").read_text()[:300]
200    for prompt, name in ((ids, "code"),):
201        for dspark in ("off", "on"):
202            cmd = ("cd /data/dsv41-port && . ./env.sh && ./build/strata-dsv41 --pack %s --tp 1 --threads off --gpus 0 "
203                   "--max-context 2048 --vision off --dspark %s --expert-profile none --ids '%s' --n 32"
204                   % (pack, dspark, prompt))
205            t0 = time.time()
206            r = run(["bash", "-lc", cmd])
207            dt = time.time() - t0
208            m = re.search(r"decode:.*?([\d.]+) tok/s", (r.stderr or ""))
209            out.append("| %s | %s | %s | %s | %.1f |" % (name, dspark, "ok" if r.returncode == 0 else "FAILED",
210                                                         m.group(1) if m else "-", dt))
211    return out
212
213
214def main() -> int:
215    ap = argparse.ArgumentParser()
216    ap.add_argument("--commit", required=True)
217    ap.add_argument("--sets", default="2.00bpw")
218    ap.add_argument("--root", default=str(ROOT))
219    ap.add_argument("--no-download", action="store_true")
220    ap.add_argument("--no-pack", action="store_true")
221    ap.add_argument("--no-eval", action="store_true")
222    ap.add_argument("--no-speed", action="store_true")
223    a = ap.parse_args()
224    commit = a.commit
225    root = pathlib.Path(a.root)
226    rep_dir = REPORTS / commit[:7]
227    rep_dir.mkdir(parents=True, exist_ok=True)
228    report: list[str] = ["# IST-DAS intake, commit %s" % commit, "", "run %s" % time.strftime("%Y-%m-%dT%H:%M:%S%z"), ""]
229
230    log("listing %s at %s" % (REPO, commit[:7]))
231    try:
232        tree = repo_tree(commit)
233    except Exception as e:      # noqa: BLE001  (HF's API rate-limits unauthenticated boxes; the files are already local)
234        if not a.no_download:
235            raise
236        log("  the Hub API is not answering (%r); building the file list from disk" % (e,))
237        tree = []
238        for set_name in [s.strip() for s in a.sets.split(",") if s.strip()]:
239            for p in sorted((root / set_name).glob("*.gguf")):
240                tree.append(("%s/%s" % (set_name, p.name), p.stat().st_size))
241        tree.sort()
242    (rep_dir / "tree.txt").write_text("\n".join("%s %d" % (p, s) for p, s in tree))
243    report += ["## Files at this commit", "", "| path | GB |", "|---|---|"]
244    report += ["| %s | %.2f |" % (p, s / 1e9) for p, s in tree]
245    report.append("")
246
247    rc = 0
248    for set_name in [s.strip() for s in a.sets.split(",") if s.strip()]:
249        report += ["## Set %s" % set_name, ""]
250        files = [(p, s) for p, s in tree if p.startswith(set_name + "/") and p.endswith(".gguf")]
251        # 1. download what is missing or the wrong size
252        if not a.no_download:
253            for p, size in files:
254                dest = local_path(root, p)
255                if dest.exists() and dest.stat().st_size == size:
256                    report.append("- present: %s (%.2f GB)" % (p, size / 1e9))
257                    continue
258                log("downloading %s (%.2f GB)" % (p, size / 1e9))
259                d = download(commit, p, root)
260                if d != 0:
261                    report.append("- DOWNLOAD FAILED: %s" % p)
262                    rc = 1
263                else:
264                    report.append("- downloaded: %s (%.2f GB)" % (p, size / 1e9))
265        # 2. hash + dedupe
266        sums = root / ("SHA256SUMS-%s-%s.txt" % (commit[:7], set_name))
267        lines = []
268        for p, size in files:
269            dest = local_path(root, p)
270            if not dest.exists():
271                continue
272            lines.append("%s  %s" % (sha256_file(dest), p))
273        sums.write_text("\n".join(lines) + "\n")
274        report.append("- sha256: %s" % sums)
275        # 3. headers
276        shards = [local_path(root, p) for p, _ in files if local_path(root, p).exists()]
277        if shards:
278            try:
279                types = tensor_types(shards)
280                report += ["", "| type | tensors | GB | device kernel |", "|---|---|---|---|"]
281                for t, (c, b) in sorted(types.items()):
282                    report.append("| %s (%d) | %d | %.2f | %s |" % (
283                        TYPE_NAMES.get(t, "?"), t, c, b / 1e9, "yes" if t in DEVICE_TYPES else "**NO - CPU lane**"))
284                report.append("")
285            except Exception as e:      # noqa: BLE001
286                report.append("- header scan failed: %r" % (e,))
287        # 4. pack
288        if not a.no_pack:
289            pack = pack_set(commit, set_name, root, report)
290        else:
291            pack = None
292        # 5. pack-info + eval + speed
293        if pack is not None:
294            pi = pack_info(pack)
295            report += ["### --pack-info", "", "```", pi.strip()[-3000:], "```", ""]
296            if "MISSING" in pi:
297                report.append("- **pack-info reports MISSING files: this pack cannot load**")
298                rc = 1
299            if not a.no_eval:
300                log("eval %s" % pack)
301                rows = eval_pack(pack, "%s_%s" % (set_name, commit[:7]))
302                report += ["### quality (4995 positions, code/agent/english)", "", "```", "\n".join(rows) or "(no output)", "```", ""]
303            if not a.no_speed:
304                log("speed smoke %s" % pack)
305                rows = speed_smoke(pack, "%s_%s" % (set_name, commit[:7]))
306                report += ["### speed smoke (32 tokens, one card)", "", "| prompt | dspark | rc | decode tok/s | wall s |",
307                           "|---|---|---|---|---|"] + rows + [""]
308        report.append("")
309
310    out = rep_dir / ("%s.md" % ",".join(s.strip() for s in a.sets.split(",")))
311    out.write_text("\n".join(report) + "\n")
312    log("report: %s" % out)
313    print("REPORT %s" % out)
314    return rc
315
316
317if __name__ == "__main__":
318    sys.exit(main())