okami.mom/strata

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

Niko1221The DGX Spark benchmark family and guide (from the owner's handover, 2026-10-26)694e71170

main
12.5 KiB254 linesraw
1#!/usr/bin/env python3
2"""dgx_bench - the DGX Spark benchmark family for Strata (Qwen3.8-Flash-Next first).
3
4    python tools/dgx_bench.py --config strata-iq3_s.json --tag base
5    python tools/dgx_bench.py --config strata-iq3_s.json --tag gu-swiglu --env STRATA_GU_SWIGLU=1
6    python tools/dgx_bench.py --config strata-iq3_s.json --tag base --cells 4096:0:256,4096:0.7:256 --rounds 3
7
8It starts the server on the model's own config (serve/server.py, the path setup writes), waits for it, sends the cells
9through the real HTTP API, restarts the server between arms, and writes every request plus a summary.
10
11A cell is PROMPT_TOKENS:TEMPERATURE:MAX_NEW.  The default family is the one the DGX Spark guide's contract names:
12512 / 4096 / 16384 / 32768 fresh prompt tokens at temperature 0 and 0.7, with a 256-token generation cap, plus one
131024-token decode cell.  Every request carries a unique nonce as its first token sequence, so the conversation cache
14cannot serve the prompt (verified: timings.cache_n must be 0, or the row is marked reused and excluded from the summary).
15
16Per request it records the client's own time to first content token (TTFT), the wall time, and the server's timings
17(prompt_n, prompt_ms, prompt_per_second, predicted_n, predicted_ms, predicted_per_second, draft counts) read from
18GET /v1/status right after the streamed answer.  Medians over rounds; nothing is retried or filtered except requests
19that failed (they are kept and reported as failures).
20
21Standard library only, like tools/strata_bench.py and tools/ab_engine.py.
22"""
23from __future__ import annotations
24
25import argparse
26import json
27import os
28import random
29import statistics
30import subprocess
31import sys
32import time
33import urllib.error
34import urllib.request
35from pathlib import Path
36
37ROOT = Path(__file__).resolve().parents[1]
38DEFAULT_CELLS = "512:0:256,4096:0:256,4096:0.7:256,16384:0:256,16384:0.7:256,32768:0:256,32768:0.7:256,4096:0:1024"
39WORDS = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember ledger quartz "
40         "meadow anchor violet thunder cedar marble piston ribbon cobalt falcon glacier hollow ivory juniper kernel "
41         "lattice mirror nectar oasis pepper quarry raven saddle tundra umber vessel willow xenon yellow zephyr "
42         "basalt cinder dune elm fjord granite heather inlet jetty kiln lagoon mesa niche opal prairie quill").split()
43
44
45def build_prompt(target_tokens: int, nonce: str) -> str:
46    """A prompt of about target_tokens tokens: a unique nonce line, a word list, and a task that keeps the answer going."""
47    rng = random.Random(hash((target_tokens, nonce)) & 0xFFFFFFFF)
48    # ~1.35 tokens per word for this vocabulary in Qwen's tokenizer
49    words = max(8, int(target_tokens / 1.35))
50    body = " ".join(rng.choice(WORDS) for _ in range(words))
51    return (f"Request nonce {nonce}. Read the word list below carefully.\n\n{body}\n\n"
52            f"Write a long, detailed analysis of the word list above: its sounds, its themes and its structure. "
53            f"Keep writing for at least 400 words; do not stop early and do not ask questions.")
54
55
56def post_stream(port: int, prompt: str, max_tokens: int, temperature: float, timeout: float = 3600) -> dict:
57    """One streamed chat completion; returns the client's times and the token count."""
58    body = json.dumps({"messages": [{"role": "user", "content": prompt}], "max_tokens": max_tokens,
59                       "temperature": temperature, "stream": True,
60                       "chat_template_kwargs": {"enable_thinking": False}}).encode()
61    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", data=body,
62                                 headers={"Content-Type": "application/json"})
63    t0 = time.time()
64    ttft = None
65    n = 0
66    text_len = 0
67    finish = None
68    with urllib.request.urlopen(req, timeout=timeout) as r:
69        for raw in r:
70            line = raw.decode("utf-8", "replace").strip()
71            if not line.startswith("data:"):
72                continue
73            data = line[5:].strip()
74            if data == "[DONE]":
75                break
76            try:
77                obj = json.loads(data)
78            except ValueError:
79                continue
80            for ch in obj.get("choices") or []:
81                d = ch.get("delta") or {}
82                piece = d.get("content") or d.get("reasoning_content") or ""
83                if piece:
84                    if ttft is None:
85                        ttft = time.time() - t0
86                    text_len += len(piece)
87                if ch.get("finish_reason"):
88                    finish = ch["finish_reason"]
89            if obj.get("usage"):
90                n = int(obj["usage"].get("completion_tokens") or n)
91    wall = time.time() - t0
92    return {"ttft_s": ttft, "wall_s": round(wall, 3), "stream_tokens": n, "chars": text_len, "finish": finish}
93
94
95def last_timings(port: int) -> dict:
96    try:
97        with urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/status", timeout=10) as r:
98            st = json.loads(r.read())
99        return st.get("last_timings") or {}
100    except Exception:
101        return {}
102
103
104def wait_ready(port: int, proc: subprocess.Popen, timeout: float = 3600) -> float:
105    t0 = time.time()
106    while time.time() - t0 < timeout:
107        if proc.poll() is not None:
108            raise RuntimeError(f"server exited with {proc.returncode}")
109        try:
110            with urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/models", timeout=5) as r:
111                if r.status == 200:
112                    return time.time() - t0
113        except Exception:
114            pass
115        time.sleep(3)
116    raise TimeoutError("server not ready")
117
118
119def calibrate(port: int, target: int, max_tokens: int, temperature: float, log) -> str:
120    """Build a prompt whose prompt_n is within ~2% of target (two probes at most)."""
121    nonce = f"{random.getrandbits(48):012x}"
122    prompt = build_prompt(target, nonce)
123    for attempt in range(3):
124        r = post_stream(port, prompt, 8, 0.0)
125        t = last_timings(port)
126        got = int(t.get("prompt_n") or 0)
127        log(f"    calibrate {target}: prompt_n {got}")
128        if got and abs(got - target) <= max(16, target // 50):
129            return prompt
130        if not got:
131            break
132        words = len(prompt.split()) * target / got
133        rng = random.Random(target + attempt)
134        body = " ".join(rng.choice(WORDS) for _ in range(max(8, int(words))))
135        prompt = (f"Request nonce {nonce}. Read the word list below carefully.\n\n{body}\n\n"
136                  f"Write a long, detailed analysis of the word list above: its sounds, its themes and its structure. "
137                  f"Keep writing for at least 400 words; do not stop early and do not ask questions.")
138    return prompt
139
140
141def run_arm(cfg_path: Path, tag: str, cells, rounds: int, port: int, env: dict, out: Path, warm: int,
142            exe: str | None = None, xargs: list[str] | None = None) -> list[dict]:
143    base = json.loads(cfg_path.read_text())
144    cfg = dict(base)
145    if exe:
146        cfg["exe"] = exe
147    if xargs:
148        cfg["args"] = list(cfg.get("args") or []) + list(xargs)
149    cfg["port"] = port
150    cfg["log"] = str(out / f"{tag}.engine.log")
151    cpath = out / f"{tag}.config.json"
152    cpath.write_text(json.dumps(cfg, indent=1))
153    rows: list[dict] = []
154    meta = {"tag": tag, "config": str(cfg_path), "cells": cells, "rounds": rounds, "env": env,
155            "engine": cfg.get("exe"), "args": cfg.get("args"), "started": time.strftime("%Y-%m-%dT%H:%M:%S")}
156    (out / f"{tag}.meta.json").write_text(json.dumps(meta, indent=1))
157    logf = open(out / f"{tag}.jsonl", "a", encoding="utf-8")
158    penv = dict(os.environ, **env)
159    for rnd in range(rounds):
160        srvlog = open(out / f"{tag}.server.log", "a", encoding="utf-8")
161        proc = subprocess.Popen([sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config",
162                                 str(cpath), "--port", str(port)], cwd=str(ROOT), env=penv,
163                                stdout=srvlog, stderr=srvlog)
164        try:
165            ready = wait_ready(port, proc)
166            print(f"round {rnd} {tag}: ready in {ready:.0f} s", flush=True)
167            nonce = f"{random.getrandbits(48):012x}"
168            post_stream(port, f"Request nonce {nonce}. Say hello in one short sentence, then list five colors.", warm, 0.0)
169            # a 4K prompt first: with --mmap-experts the first request pages the experts in (a one-time cold cost of
170            # tens of seconds); every measured cell then runs on the same warm state the fork's baselines had
171            nonce = f"{random.getrandbits(48):012x}"
172            post_stream(port, build_prompt(4096, nonce), 8, 0.0)
173            prompts = {}
174            for (length, temp, maxnew) in cells:
175                key = (length, maxnew)
176                if key not in prompts:
177                    prompts[key] = calibrate(port, length, maxnew, 0.0, print)
178                nonce = f"{random.getrandbits(48):012x}"
179                prompt = prompts[key]
180                prompt = prompt.replace("Request nonce ", "Request nonce ", 1)
181                # a fresh nonce: rewrite the first line so no prefix can be reused
182                prompt = prompt.split("\n", 1)
183                prompt = f"Request nonce {nonce}. Read the word list below carefully.\n" + prompt[1]
184                r = post_stream(port, prompt, maxnew, temp)
185                t = last_timings(port)
186                row = {"round": rnd, "arm": tag, "len": length, "temp": temp, "max_new": maxnew, **r, **t}
187                rows.append(row)
188                logf.write(json.dumps(row) + "\n")
189                logf.flush()
190                print(f"  {length:6d} T={temp} n={maxnew:4d}: prompt_n {t.get('prompt_n')} "
191                      f"prompt {t.get('prompt_per_second')} tok/s decode {t.get('predicted_per_second')} tok/s "
192                      f"n {t.get('predicted_n')} ttft {r['ttft_s'] and round(r['ttft_s'], 2)} wall {r['wall_s']}",
193                      flush=True)
194        finally:
195            proc.terminate()
196            try:
197                proc.wait(60)
198            except subprocess.TimeoutExpired:
199                proc.kill()
200            time.sleep(5)
201    logf.close()
202    return rows
203
204
205def summarize(rows: list[dict], cells) -> str:
206    lines = ["| cell | n | prompt tok/s | decode tok/s | ttft s | wall s |", "|---|---|---|---|---|---|"]
207    for (length, temp, maxnew) in cells:
208        sel = [r for r in rows if r["len"] == length and r["temp"] == temp and r["max_new"] == maxnew
209               and not r.get("cache_n")]
210        if not sel:
211            lines.append(f"| {length} T={temp} n={maxnew} | 0 | - | - | - | - |")
212            continue
213        med = lambda k: statistics.median([r[k] for r in sel if r.get(k)]) if any(r.get(k) for r in sel) else None
214        p, d, ttft, wall = med("prompt_per_second"), med("predicted_per_second"), med("ttft_s"), med("wall_s")
215        fmt = lambda v, f="{:.1f}": "-" if v is None else f.format(v)
216        lines.append(f"| {length} T={temp} n={maxnew} | {len(sel)} | {fmt(p)} | {fmt(d)} | {fmt(ttft, '{:.2f}')} | "
217                     f"{fmt(wall, '{:.1f}')} |")
218    return "\n".join(lines)
219
220
221def main() -> int:
222    ap = argparse.ArgumentParser()
223    ap.add_argument("--config", required=True)
224    ap.add_argument("--tag", default="base")
225    ap.add_argument("--cells", default=DEFAULT_CELLS)
226    ap.add_argument("--rounds", type=int, default=3)
227    ap.add_argument("--port", type=int, default=8091)
228    ap.add_argument("--env", action="append", default=[], help="NAME=VALUE for the server process (repeatable)")
229    ap.add_argument("--exe", default="", help="engine binary to run instead of the config's")
230    ap.add_argument("--xargs", default="", help="extra engine arguments, ';'-separated")
231    ap.add_argument("--warm", type=int, default=64)
232    ap.add_argument("--out", default="")
233    a = ap.parse_args()
234    cells = []
235    for s in a.cells.split(","):
236        l, t, n = s.split(":")
237        cells.append((int(l), float(t), int(n)))
238    out = Path(a.out) if a.out else ROOT / "bench" / "results" / time.strftime("dgx-%Y-%m-%d-%H%M") 
239    out.mkdir(parents=True, exist_ok=True)
240    env = {}
241    for e in a.env:
242        k, v = e.split("=", 1)
243        env[k] = v
244    print(f"out {out}; cells {cells}; rounds {a.rounds}", flush=True)
245    rows = run_arm(Path(a.config), a.tag, cells, a.rounds, a.port, env, out, a.warm,
246                   exe=(a.exe or None), xargs=(a.xargs.split(";") if a.xargs else None))
247    summary = summarize(rows, cells)
248    (out / f"{a.tag}.summary.md").write_text(f"# {a.tag}\n\n{summary}\n")
249    print("\n" + summary)
250    return 0
251
252
253if __name__ == "__main__":
254    sys.exit(main())