okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
4.1 KiB96 linesraw
1#!/usr/bin/env python3
2"""Long-context recall check: hide one fact in a long prompt and ask for it back (the guide's "long-context retrieval" cell).
3
4    python research/tools/dgx-spark-2026-10/dgx_needle.py --config strata-iq3s-final.json --tokens 12000
5
6Starts the model's server, sends one request, and reports whether the answer contains the fact.  The fact is placed at a
7random position in the prompt and never appears in the question, so a correct answer means the context was read.
8"""
9from __future__ import annotations
10
11import argparse
12import json
13import random
14import subprocess
15import sys
16import time
17import urllib.error
18import urllib.request
19from pathlib import Path
20
21ROOT = Path(__file__).resolve().parents[3]
22WORDS = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember ledger quartz "
23         "meadow anchor violet thunder cedar marble piston ribbon cobalt falcon glacier hollow ivory juniper kernel "
24         "lattice mirror nectar oasis pepper quarry raven saddle tundra umber vessel willow xenon yellow zephyr").split()
25
26
27def build(tokens: int, needle: str, rng: random.Random) -> str:
28    words = max(8, int(tokens / 1.35))
29    body = [rng.choice(WORDS) for _ in range(words)]
30    at = rng.randrange(len(body) // 4, 3 * len(body) // 4)
31    body[at:at] = [needle]
32    return ("Read the following notes carefully, then answer the question at the end.\n\n" + " ".join(body) +
33            "\n\nQuestion: what is the access code for the harbor gate? Answer with the code only.")
34
35
36def post(port: int, prompt: str, max_tokens: int = 32) -> dict:
37    body = json.dumps({"messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens, "temperature": 0,
38                       "chat_template_kwargs": {"enable_thinking": False}}).encode()
39    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=body,
40                                 headers={"Content-Type": "application/json"})
41    try:
42        with urllib.request.urlopen(req, timeout=3600) as r:
43            return json.loads(r.read())
44    except urllib.error.HTTPError as e:
45        raise SystemExit(f"HTTP {e.code}: {e.read()[:400]!r}")
46
47
48def main() -> int:
49    ap = argparse.ArgumentParser()
50    ap.add_argument("--config", required=True)
51    ap.add_argument("--tokens", type=int, default=12000)
52    ap.add_argument("--port", type=int, default=8091)
53    ap.add_argument("--runs", type=int, default=3)
54    a = ap.parse_args()
55    cfg = json.loads(Path(a.config).read_text())
56    cfg["port"] = a.port
57    cfg["log"] = "/tmp/dgx-needle.log"
58    cpath = Path("/tmp/dgx-needle.json")
59    cpath.write_text(json.dumps(cfg, indent=1))
60    proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config",
61                             str(cpath), "--port", str(a.port)], cwd=str(ROOT),
62                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
63    ok = 0
64    try:
65        for _ in range(600):
66            try:
67                with urllib.request.urlopen(f"http://127.0.0.1:{a.port}/v1/models", timeout=5) as r:
68                    if r.status == 200:
69                        break
70            except Exception:
71                pass
72            time.sleep(2)
73        post(a.port, "Say hi.", 8)
74        for i in range(a.runs):
75            rng = random.Random(1000 + i)
76            code = f"{rng.randrange(100000, 999999)}"
77            needle = f"The access code for the harbor gate is {code}."
78            r = post(a.port, build(a.tokens, needle, rng))
79            answer = r["choices"][0]["message"].get("content", "")
80            t = r.get("timings") or {}
81            hit = code in answer
82            ok += hit
83            print(f"run {i}: prompt_n {t.get('prompt_n')} at {t.get('prompt_per_second')} tok/s, "
84                  f"answer {answer[:40]!r} -> {'HIT' if hit else 'MISS'} (code {code})")
85    finally:
86        proc.terminate()
87        try:
88            proc.wait(60)
89        except subprocess.TimeoutExpired:
90            proc.kill()
91    print(f"{ok} of {a.runs} recalled")
92    return 0 if ok == a.runs else 1
93
94
95if __name__ == "__main__":
96    sys.exit(main())