From f499b8cf37b90f5ef4395dda86bdbd033f31affc Mon Sep 17 00:00:00 2001 From: Robert Karl Date: Mon, 19 Oct 2026 00:00:49 -0700 Subject: [PATCH] correctness tooling for DeepSeek V4 Flash and GLM 5.3 Flash: @FILE id lists, per-model script roots, pi context note - src/poly/main.cpp: --tokens/--eos-ids/--follow take @FILE (a 31K-id list is over Linux's 128 KiB argument limit); tools/qwen35/q36_llama_dump.cpp: the same for --tokens/--force. Test-only; documented in UPSTREAM.md. - bench/unbiased/correctness/scripts: US2_CORR_ROOT / US2_DUMP / US2_POLY / US2_VOCAB overrides so the step-12 scripts run for another model, tokenizer and reference build; ids passed as @FILE; stderr decoded with errors='replace' (DeepSeek's vocabulary pieces are not all UTF-8); make-inputs-model.py (inputs through the fork front end's /apply-template + /tokenize); pull-record-2026-10-19.sh. - README: pi's compaction defaults need a window well above 32K (USTRAT-8). Runs on the 2x B200 pod in progress; record follows. Co-Authored-By: Claude Fable 5.1 --- README.md | 2 +- UPSTREAM.md | 5 ++ .../correctness/scripts/derive-top20.py | 4 +- .../correctness/scripts/make-inputs-model.py | 48 +++++++++++++++++++ .../unbiased/correctness/scripts/poly-run.py | 9 ++-- .../scripts/pull-record-2026-10-19.sh | 19 ++++++++ bench/unbiased/correctness/scripts/ref-run.py | 15 +++--- .../unbiased/correctness/scripts/score-all.py | 4 +- bench/unbiased/correctness/scripts/score.py | 4 +- src/poly/main.cpp | 11 ++++- tools/qwen35/q36_llama_dump.cpp | 13 ++++- 11 files changed, 115 insertions(+), 19 deletions(-) create mode 100755 bench/unbiased/correctness/scripts/make-inputs-model.py create mode 100755 bench/unbiased/correctness/scripts/pull-record-2026-10-19.sh diff --git a/README.md b/README.md index cd77a0e..e978bf8 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,7 @@ UD-Q3_K_M on an RTX 3090 and Qwen3.6 UD-IQ4_XS on the A6000 pass as is (the IQ4_ after the two fixes under "Known limits" (argument order; GLM's architecture name in the vocabulary load). The API-only checks (`frontend/tests/acceptance-real-engine.sh`) hold decode and prompt reading within 15 % of step 9 on the 3090 (Flash-Next with the installer's `--pool-workers 15`; 24 costs 14 %) and record the first B200 figures -(72 and 74 tok/s decode on one card). Record: `bench/unbiased/2026-10-19-step13-acceptance/`. +(72 and 74 tok/s decode on one card). Record: `bench/unbiased/2026-10-19-step13-acceptance/`. pi's compaction defaults (reserve 16K, keep the last 20K tokens) assume a window well above 64K: against a server at `--max-context 32768` a long pi session compacts to no effect and then sends `max_tokens: 1` ("Response was truncated before completion"); serve 128K or more to pi, or lower pi's `compaction` settings (USTRAT-8). ## Known limits diff --git a/UPSTREAM.md b/UPSTREAM.md index ee60a0a..7279ac1 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -113,6 +113,11 @@ and teacher-forced per-step distributions on 16 sequences per model (within llam and arm). Two upstream claims did not hold and are not repeated here: the draft block is not bitwise inert above 4-token windows, and `strata`'s output is not reproducible across starts unless the expert cache is pinned. Tickets USTRAT-1 to 5. +One test-only hunk since (2026-10-19, correctness checks of DeepSeek V4 Flash and GLM 5.3 Flash): `src/poly/main.cpp` +`--tokens`, `--eos-ids` and `--follow` accept `@FILE` (the comma-separated ids read from that file), because a 31K-id +list is over Linux's 128 KiB single-argument limit. `tools/qwen35/q36_llama_dump.cpp` (upstream's llama.cpp-side parity +program, not part of the build) takes the same `@FILE` for `--tokens` and `--force`. Nothing on the serve path changes. + ## Removed Each entry names the rule above that it satisfies. diff --git a/bench/unbiased/correctness/scripts/derive-top20.py b/bench/unbiased/correctness/scripts/derive-top20.py index bcc961a..6d0427b 100644 --- a/bench/unbiased/correctness/scripts/derive-top20.py +++ b/bench/unbiased/correctness/scripts/derive-top20.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 """reference//..full (f32 [steps][vocab], kept on the box) -> ..top20.tsv committed: per step the argmax, the top-2 gap in nats and the 20 likeliest ids with their log-probabilities (id:logp).""" -import pathlib, sys +import os, pathlib, sys import numpy as np -V = 248320 +V = int(os.environ.get('US2_VOCAB', 248320)) for f in sorted(pathlib.Path(sys.argv[1]).glob('*.full')): out = f.with_name(f.name[:-5] + '.top20.tsv') if out.exists(): continue diff --git a/bench/unbiased/correctness/scripts/make-inputs-model.py b/bench/unbiased/correctness/scripts/make-inputs-model.py new file mode 100755 index 0000000..8d16749 --- /dev/null +++ b/bench/unbiased/correctness/scripts/make-inputs-model.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Step-12 inputs for a model whose tokenizer is not Qwen's (CORRECTNESS-PLAN.md 3.2; the DeepSeek V4 Flash and GLM 5.3 +Flash runs of 2026-10-19). Same texts as make-inputs.py (inputs-src/), tokenized through the fork front end that serves +the model: /apply-template renders the model's own chat template, /tokenize gives the ids (special tokens parsed). +make-inputs-model.py +Writes /inputs//.prompt.ids, .json and realtext's .answer.ids. Raw text (long, realtext) is prefixed +with the model's sequence start: DeepSeek <|begin_of_sentence|>, GLM [gMASK], as the chat template does.""" +import json, pathlib, sys, urllib.request +root, url, fam = pathlib.Path(sys.argv[1]), sys.argv[2].rstrip('/'), sys.argv[3] +SRC = root / 'inputs-src'; OUT = root / 'inputs' + +def post(path, body): + req = urllib.request.Request(url + path, json.dumps(body).encode(), {'content-type': 'application/json'}) + return json.load(urllib.request.urlopen(req, timeout=600)) + +def tokenize(text): + return post('/tokenize', {'content': text, 'add_special': False})['tokens'] + +def chat(q, think): + """The model's own template, thinking on or off. DeepSeek: the template's `thinking` switch (off renders + `<|Assistant|>`). GLM: the template always opens ; off is an empty block, as Qwen's.""" + if fam == 'deepseek': + return post('/apply-template', {'messages': [{'role': 'user', 'content': q}], 'chat_template_kwargs': {'thinking': think}})['prompt'] + p = post('/apply-template', {'messages': [{'role': 'user', 'content': q}]})['prompt'] + assert p.endswith(''), p[-40:] + return p if think else p + '' + +PREFIX = {'deepseek': '<|begin▁of▁sentence|>', 'glm': '[gMASK]'}[fam] + +def write(setname, seq, prompt, answer=None, n_answer=None): + d = OUT / setname; d.mkdir(parents=True, exist_ok=True) + (d / f'{seq}.prompt.ids').write_text(','.join(map(str, prompt)) + '\n') + if answer is not None: + (d / f'{seq}.answer.ids').write_text(','.join(map(str, answer)) + '\n') + meta = {'prompt_tokens': len(prompt), 'n_answer': len(answer) if answer else n_answer} + (d / f'{seq}.json').write_text(json.dumps(meta) + '\n') + print(setname, seq, meta, flush=True) + +for i, q in enumerate(json.load(open(SRC / 'short.json'))): + write('short', f'p{i:02d}', tokenize(chat(q, False)), n_answer=128) +write('code', 'lru', tokenize(chat((SRC / 'code.txt').read_text().strip(), False)), n_answer=400) +write('code', 'puzzle', tokenize(chat((SRC / 'reasoning.txt').read_text().strip(), True)), n_answer=324) +doc = tokenize(PREFIX + (SRC / 'longdoc.txt').read_text()) +print('longdoc tokens', len(doc)); assert len(doc) >= 31744, len(doc) +for name, n in (('d4k', 4096), ('d16k', 16384), ('d31k', 31744)): + write('long', name, doc[:n], n_answer=256) +write('realtext', 'r16k', doc[:16384 - 510], answer=doc[16384 - 510:16384]) +(root / 'inputs' / 'README.txt').write_text(f'{fam}: tokenized through {url} (fork front end /apply-template + /tokenize), texts from inputs-src/\n') diff --git a/bench/unbiased/correctness/scripts/poly-run.py b/bench/unbiased/correctness/scripts/poly-run.py index 601580e..07b6132 100644 --- a/bench/unbiased/correctness/scripts/poly-run.py +++ b/bench/unbiased/correctness/scripts/poly-run.py @@ -7,8 +7,9 @@ arms: base = --tail-skip 0 --no-draft --lookup 0 --window 1 (arm 1) pb512 = base + --prompt-batch 512 (3.3 last paragraph, step 0 only) Writes poly///.top.txt, .ids.txt, .log, command.sh.""" import os, pathlib, subprocess, sys, time -ROOT = pathlib.Path.home() / 'us2-results/correctness' -EXE = pathlib.Path.home() / 'us2-build/build/bin/strata-poly' +# US2_CORR_ROOT / US2_POLY: another model's root and engine binary (DeepSeek, GLM: 2026-10-19) +ROOT = pathlib.Path(os.environ.get('US2_CORR_ROOT', pathlib.Path.home() / 'us2-results/correctness')) +EXE = pathlib.Path(os.environ.get('US2_POLY', pathlib.Path.home() / 'us2-build/build/bin/strata-poly')) tag, gguf, arm = sys.argv[1], sys.argv[2], sys.argv[3]; only = set(sys.argv[4:]) def answer_path(p, seq, tag): @@ -30,7 +31,7 @@ for p in sorted(ROOT.glob('inputs/*/*.prompt.ids')): prompt = p.read_text().strip(); ans = ans_path.read_text().strip() n = len(ans.split(',')) cmd = [str(EXE), '--model', gguf, '--max-context', '32768'] + ARMS[arm] + \ - ['--tokens', prompt, '--follow', ans, '--max-new', str(n), '--top-probs', '20'] + ['--tokens', f'@{p}', '--follow', f'@{ans_path}', '--max-new', str(n), '--top-probs', '20'] t0 = time.time() try: with open(OUT / f'{seq}.top.txt', 'w') as err, open(OUT / f'{seq}.ids.txt', 'w') as out: @@ -39,7 +40,7 @@ for p in sorted(ROOT.glob('inputs/*/*.prompt.ids')): print(f'{p.parent.name}/{seq} {arm}: cannot exec ({e}); the id list needs a file option', flush=True) (OUT / f'{seq}.log').write_text(f'not run: {e}\n'); continue with open(OUT / 'command.sh', 'a') as f: - f.write('STRATA_FREEZE_EXPERTS=1 ' + ' '.join(c if len(c) < 200 else f'$(cat {p if c == prompt else ans_path})' for c in cmd) + '\n') + f.write('STRATA_FREEZE_EXPERTS=1 ' + ' '.join(cmd) + '\n') # top lines go to stderr with the engine's log; keep the log lines apart from the top lines raw = (OUT / f'{seq}.top.txt').read_text().splitlines() (OUT / f'{seq}.log').write_text('\n'.join(l for l in raw if not l.startswith('top ')) + '\n') diff --git a/bench/unbiased/correctness/scripts/pull-record-2026-10-19.sh b/bench/unbiased/correctness/scripts/pull-record-2026-10-19.sh new file mode 100755 index 0000000..6a71f33 --- /dev/null +++ b/bench/unbiased/correctness/scripts/pull-record-2026-10-19.sh @@ -0,0 +1,19 @@ +#!/bin/bash +# Pull the DeepSeek V4 Flash / GLM 5.3 Flash correctness record from the 2x B200 pod (2026-10-19) into this directory: +# inputs per tokenizer, the references' top-20 extracts and checksums (the f32 logits stay on the pod), the engine +# arms' outputs, the scores, the chain scripts and logs. +set -u +SSH="ssh -p 30381 -i $HOME/.ssh/id_ed25519"; H=root@38.80.152.146; P=/opt/us2-correctness +cd "$(dirname "$0")/.." || exit 1 +for fam in deepseek glm; do + mkdir -p inputs-$fam reference/$fam poly/$fam scores/$fam + rsync -az -e "$SSH" $H:$P/$fam/inputs/ inputs-$fam/ + rsync -az -e "$SSH" --include='*/' --include='*.top20.tsv' --include='*.sha256' --include='*.gen.txt' --include='command.sh' --include='*.force.ids' --exclude='*' $H:$P/$fam/reference/$fam/ reference/$fam/ + rsync -az -e "$SSH" $H:$P/$fam/poly/$fam/ poly/$fam/ + rsync -az -e "$SSH" $H:$P/$fam/scores/$fam/ scores/$fam/ +done +mkdir -p probes/deepseek-master-cpu logs/2026-10-19 +rsync -az -e "$SSH" --include='*.log' --include='*.out' --include='*.sh' --exclude='*' $H:$P/deepseek/probes/ probes/deepseek-master-cpu/ +rsync -az -e "$SSH" $H:$P/bin/ logs/2026-10-19/bin/ +rsync -az -e "$SSH" --exclude='build-*.log' $H:$P/logs/ logs/2026-10-19/ +echo pulled diff --git a/bench/unbiased/correctness/scripts/ref-run.py b/bench/unbiased/correctness/scripts/ref-run.py index 0577d70..d3c610d 100644 --- a/bench/unbiased/correctness/scripts/ref-run.py +++ b/bench/unbiased/correctness/scripts/ref-run.py @@ -6,8 +6,9 @@ ref-run.py gpu|cpu [seq ...] cpu: --ngl 0, --force on the answer, writes .cpu.full. Full logits are f32 [steps][vocab]; every run also gets ..log (stderr) and command.sh.""" import hashlib, json, os, pathlib, subprocess, sys, time -ROOT = pathlib.Path.home() / 'us2-results/correctness' -DUMP = pathlib.Path.home() / 'llamacpp-ref/tools/q36_llama_dump' +# US2_CORR_ROOT / US2_DUMP: another model's root and reference build (DeepSeek, GLM: 2026-10-19) +ROOT = pathlib.Path(os.environ.get('US2_CORR_ROOT', pathlib.Path.home() / 'us2-results/correctness')) +DUMP = pathlib.Path(os.environ.get('US2_DUMP', pathlib.Path.home() / 'llamacpp-ref/tools/q36_llama_dump')) tag, gguf, mode = sys.argv[1], sys.argv[2], sys.argv[3] only = set(sys.argv[4:]) @@ -27,20 +28,22 @@ for p in seqs: n = meta['n_answer'] nctx = ((meta['prompt_tokens'] + n + 8 + 255) // 256) * 256 env = dict(os.environ, STRATA_DUMP_CTX=str(nctx)) - cmd = [str(DUMP), '--model', gguf, '--tokens', prompt, '--ngl', '99' if mode == 'gpu' else '0', + cmd = [str(DUMP), '--model', gguf, '--tokens', f'@{p}', '--ngl', '99' if mode == 'gpu' else '0', '--dump-full-logits', str(OUT / f'{seq}.{mode}.full')] if mode == 'cpu' or ans_path.exists(): ans = ans_path.read_text().strip().split(',') # --force N ids runs N+1 steps; the engines score N steps, so force all but the last and let step N be greedy - cmd += ['--force', ','.join(ans[:-1])] + forced = OUT / f'{seq}.force.ids'; forced.write_text(','.join(ans[:-1]) + '\n') + cmd += ['--force', f'@{forced}'] else: cmd += ['--n', str(n)] t0 = time.time() - r = subprocess.run(cmd, env=env, capture_output=True, text=True) + # errors='replace': the DeepSeek vocabulary's pieces are not all valid UTF-8 in llama.cpp's load log (2026-10-19) + r = subprocess.run(cmd, env=env, capture_output=True, text=True, errors='replace') dt = time.time() - t0 (OUT / f'{seq}.{mode}.log').write_text(r.stderr) with open(OUT / 'command.sh', 'a') as f: - f.write(f'STRATA_DUMP_CTX={nctx} ' + ' '.join(c if len(c) < 200 else f'$(cat {p})' for c in cmd) + '\n') + f.write(f'STRATA_DUMP_CTX={nctx} ' + ' '.join(cmd) + '\n') if r.returncode != 0: print(f'{setname}/{seq} {mode}: EXIT {r.returncode} after {dt:.0f} s; see {seq}.{mode}.log', flush=True); continue gen = [l for l in r.stdout.splitlines() if l.startswith('gen:')][0].split()[1:] diff --git a/bench/unbiased/correctness/scripts/score-all.py b/bench/unbiased/correctness/scripts/score-all.py index 16196c8..ac5028b 100644 --- a/bench/unbiased/correctness/scripts/score-all.py +++ b/bench/unbiased/correctness/scripts/score-all.py @@ -3,8 +3,8 @@ poly: score-all.py poly e.g. poly qwen36-q3km qwen36-q3km base strata: score-all.py strata (ref-tag is the Flash-Next reference directory) Writes scores///.tsv + .json and summary.md (per set: steps, top-1, KL, floor, ratio, T1, T2).""" -import json, pathlib, subprocess, sys -ROOT = pathlib.Path.home() / 'us2-results/correctness' +import json, os, pathlib, subprocess, sys +ROOT = pathlib.Path(os.environ.get('US2_CORR_ROOT', pathlib.Path.home() / 'us2-results/correctness')) kind = sys.argv[1] if kind == 'poly': tag, ref, arm = sys.argv[2:5]; runs = ROOT / 'poly' / tag / arm; glob = '*.top.txt'; strip = '.top.txt' diff --git a/bench/unbiased/correctness/scripts/score.py b/bench/unbiased/correctness/scripts/score.py index 1e7a24c..b0cd207 100644 --- a/bench/unbiased/correctness/scripts/score.py +++ b/bench/unbiased/correctness/scripts/score.py @@ -12,10 +12,10 @@ Q for an id in P's top 20 that the engine did not print: the engine's rest mass the rest bucket (an upper bound on each missing id's probability is the engine's 20th probability; the spread is used, and the number of such ids is reported as 'missing'). T1 gate: argmax equal at every position with gap >= 0.5. T2 gate: mean KL <= 1.5 x floor (full-vocab) on the positions.""" -import json, sys +import json, os, sys import numpy as np -V = 248320 +V = int(os.environ.get('US2_VOCAB', 248320)) # Qwen 248320; DeepSeek V4 Flash 129280; GLM 5.3 Flash 154880 def load_full(path): a = np.fromfile(path, dtype=np.float32) diff --git a/src/poly/main.cpp b/src/poly/main.cpp index ce03229..92935e9 100644 --- a/src/poly/main.cpp +++ b/src/poly/main.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -1179,7 +1180,15 @@ int main(int argc, char** argv) { else if (a == "--min-p") s.min_p = std::strtof(val(), nullptr); else if (a == "--seed") s.seed = std::strtoull(val(), nullptr, 10); else if (a == "--tokens" || a == "--eos-ids" || a == "--follow") { - if (!parse_ids(val(), a == "--tokens" ? ids : a == "--eos-ids" ? eos : follow)) { + // "@path": the id list read from that file (a 31K-id list is over Linux's 128 KiB argument limit; 2026-10-19) + std::string list = val(); + if (!list.empty() && list[0] == '@') { + std::ifstream in(list.substr(1), std::ios::binary); + if (!in) { std::fprintf(stderr, "cannot read %s\n", list.c_str() + 1); return 2; } + list.assign(std::istreambuf_iterator(in), std::istreambuf_iterator()); + while (!list.empty() && (list.back() == '\n' || list.back() == '\r' || list.back() == ' ')) list.pop_back(); + } + if (!parse_ids(list.c_str(), a == "--tokens" ? ids : a == "--eos-ids" ? eos : follow)) { std::fprintf(stderr, "strata-poly: %s takes token ids separated by commas\n", a.c_str()); return 2; } diff --git a/tools/qwen35/q36_llama_dump.cpp b/tools/qwen35/q36_llama_dump.cpp index e705993..e285fe8 100644 --- a/tools/qwen35/q36_llama_dump.cpp +++ b/tools/qwen35/q36_llama_dump.cpp @@ -8,6 +8,7 @@ // -lggml-base -Wl,-rpath,/build/bin -o q36_llama_dump // Usage: q36_llama_dump --model GGUF (--prompt TEXT | --tokens ID,ID,...) [--n 64] [--ngl 99] [--dump-layers F] // [--dump-logits F] [--force ID,ID,...] [--dump-full-logits F] +// --tokens and --force also take @FILE: the comma-separated ids read from that file. // --force feeds that continuation instead of the greedy ids (teacher forcing); --dump-full-logits writes every // step's logits (f32, [step][vocab]). // --prompt is tokenized with special tokens parsed and no BOS added (Qwen adds none). @@ -42,7 +43,17 @@ bool on_tensor(struct ggml_tensor* t, bool ask, void* user) { return true; } -std::vector parse_ids(const std::string& s) { +std::vector parse_ids(const std::string& arg) { + // "@path": the list is read from that file (a 31K-id list is over Linux's 128 KiB single-argument limit; 2026-10-19) + std::string s = arg; + if (!s.empty() && s[0] == '@') { + FILE* f = std::fopen(s.c_str() + 1, "rb"); + if (!f) { std::fprintf(stderr, "cannot read %s\n", s.c_str() + 1); std::exit(2); } + s.clear(); + char buf[65536]; size_t n; + while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) s.append(buf, n); + std::fclose(f); + } std::vector v; const char* p = s.c_str(); while (*p) {