okami.mom/strata

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

Niko1221Merge branch 'f-140' into f-140-j2e0f28e7d

main
21.7 KiB381 linesraw
1#!/usr/bin/env python3
2"""Serial fresh-prompt benchmark, adapted from the community MI50/RTX 5090 harness.
3
4Start a dedicated Strata server separately. This script never starts or stops it.
5Expert adaptation and the OS file cache stay warm between requests; prefix reuse
6is rejected. Engine file-tier counters describe decode, not physical disk reads.
7"""
8from __future__ import annotations
9
10import argparse
11import hashlib
12import json
13import platform
14import statistics
15import subprocess
16import sys
17import threading
18import time
19import urllib.error
20import urllib.request
21import uuid
22from pathlib import Path
23
24
25def write_json(path, value):
26    path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
27
28
29def get(url, timeout=30):
30    with urllib.request.urlopen(url, timeout=timeout) as response:
31        return json.load(response)
32
33
34def digest(value):
35    return hashlib.sha256(json.dumps(value, sort_keys=True).encode("utf-8")).hexdigest()
36
37
38def executable_record(config):
39    """Resolve the configured binary exactly as serve/server.py does, without executing it."""
40    executable = Path(config["exe"])
41    if not executable.is_absolute():
42        executable = Path(config.get("cwd") or ".") / executable
43    executable = executable.resolve()
44    checksum = hashlib.sha256()
45    with executable.open("rb") as source:
46        for block in iter(lambda: source.read(1024 * 1024), b""):
47            checksum.update(block)
48    return {"path": str(executable), "sha256": checksum.hexdigest(), "size_bytes": executable.stat().st_size}
49
50
51def engine_provenance_record(path, executable):
52    """Keep compact build provenance and verify its executable artifact, when recorded."""
53    path = path.resolve()
54    raw = path.read_bytes()
55    source = json.loads(raw.decode("utf-8-sig"))
56    artifacts = source.get("artifacts", {})
57    if isinstance(artifacts, list):
58        entries = [(entry["file"], entry) for entry in artifacts]
59    elif isinstance(artifacts, dict):
60        entries = list(artifacts.items())
61    else:
62        raise ValueError("Provenance artifacts must be a list or dictionary")
63    matches = [entry for name, entry in entries
64               if Path(name).name.casefold() == Path(executable["path"]).name.casefold()]
65    if len(matches) > 1:
66        raise ValueError("Provenance has multiple artifacts matching the configured executable")
67    expected = matches[0]["sha256"].lower() if matches else None
68    if expected is not None and expected != executable["sha256"]:
69        raise ValueError("Provenance executable SHA-256 does not match the configured executable")
70    toolchain_keys = ("cmake", "ninja", "msvc", "windows_sdk", "nvcc", "cuda", "cuda_architectures",
71                      "cxx_standard", "cuda_standard", "build_type", "portable_avx2", "msvc_runtime",
72                      "parallel_jobs", "tests_built")
73    toolchain = {key: value for key, value in source.get("toolchain", {}).items() if key in toolchain_keys}
74    # Release BUILD.json records CUDA and target architectures at the top level.
75    toolchain.update({key: source[key] for key in ("cuda", "archs", "ptx", "portable") if key in source})
76    return {"path": str(path), "sha256": hashlib.sha256(raw).hexdigest(),
77            "version": source.get("strata_version", source.get("version")), "commit": source.get("commit"),
78            "fingerprint": source.get("engine_source_fingerprint", source.get("source_fingerprint")),
79            "toolchain": toolchain, "repository": source.get("fork_repository"),
80            "llama_cpp_commit": source.get("llama_cpp_pinned_commit"),
81            "executable_hash_verified": expected is not None, "recorded_executable_sha256": expected}
82
83
84def validate_completion(before, after, chunks, expected, finish, done, text):
85    if not done:
86        raise RuntimeError("The stream ended without [DONE]")
87    if not text:
88        raise RuntimeError("The response contained no text")
89    if finish not in ("length", "stop"):
90        raise RuntimeError(f"Unsuccessful finish reason: {finish!r}")
91    if after["totals"]["requests"] != before["totals"]["requests"] + 1:
92        raise RuntimeError("Request counter mismatch; another client or engine restart invalidated this trial")
93    if after["live"]["state"] != "idle" or after["live"].get("queued", 0):
94        raise RuntimeError("The dedicated server was not idle after the request")
95    engine = after["requests"][0]
96    usage_chunk = next((chunk for chunk in reversed(chunks) if "usage" in chunk), None)
97    if not usage_chunk or not usage_chunk.get("timings"):
98        raise RuntimeError("The final stream chunk lacks usage or engine timings")
99    usage, timings = usage_chunk["usage"], usage_chunk["timings"]
100    if engine.get("reused") != 0 or usage["prompt_tokens_details"]["cached_tokens"] != 0:
101        raise RuntimeError("Fresh prompt reused cached tokens; restart this arm before resuming")
102    if engine["prompt_tokens"] != expected or usage["prompt_tokens"] != expected:
103        raise RuntimeError(f"Prompt token count mismatch; expected {expected}")
104    if engine.get("prompt_total") != expected or engine.get("prompt_read") != expected:
105        raise RuntimeError("The engine did not report reading the complete prompt")
106    if engine["finish"] != finish or engine["output_tokens"] != usage["completion_tokens"]:
107        raise RuntimeError("Stream usage or finish reason does not match /metrics")
108    if timings["prompt_n"] != expected or timings["predicted_n"] != usage["completion_tokens"]:
109        raise RuntimeError("Final stream timings do not match the completed request")
110    for name, timing_name in (("prompt_ms", "prompt_ms"), ("decode_ms", "predicted_ms")):
111        if engine[name] <= 0 or abs(engine[name] - timings[timing_name]) > 0.11:
112            raise RuntimeError(f"Invalid or mismatched engine timing: {name}")
113    if engine["engine_generated"] <= 0:
114        raise RuntimeError("The engine reported no generated tokens")
115    return engine, usage, timings
116
117
118def perform(url, out, session, label, attempt, req, expected, interval=1.0, timeout=1800):
119    stem = f"{label}-attempt-{attempt}"
120    body = json.dumps(req, ensure_ascii=False).encode("utf-8")
121    (out / f"{stem}-request.json").write_bytes(body + b"\n")
122    row = {"label": label, "attempt": attempt, "session": session, "status": "failed",
123           "expected_prompt_tokens": expected, "request_sha256": hashlib.sha256(body).hexdigest(),
124           "started_epoch_s": time.time(), "raw_stream": f"{stem}-sse.jsonl",
125           "telemetry": f"{stem}-telemetry.jsonl", "text": "", "reasoning": ""}
126    chunks, texts, reasoning, telemetry_errors = [], [], [], []
127    stop = threading.Event()
128    monitor = None
129    started = None
130
131    def sample(output):
132        metrics = get(url + "/metrics")
133        hardware = dict(metrics["hardware"])
134        if hardware.get("ram_total") is not None and hardware.get("ram_used") is not None:
135            hardware["ram_available"] = hardware["ram_total"] - hardware["ram_used"]
136        sample_row = {"epoch_s": time.time(), "metrics_time": metrics.get("time"),
137                      "live": metrics["live"], "hardware": hardware,
138                      "completed_requests": metrics["totals"]["requests"]}
139        output.write(json.dumps(sample_row) + "\n")
140        output.flush()
141
142    def monitor_loop(output):
143        while not stop.wait(interval):
144            try:
145                sample(output)
146            except Exception as error:
147                telemetry_errors.append(f"{type(error).__name__}: {error}")
148                output.write(json.dumps({"epoch_s": time.time(), "error": telemetry_errors[-1]}) + "\n")
149                output.flush()
150                break
151
152    try:
153        before = get(url + "/metrics")
154        row["metrics_before"] = before
155        if before["live"]["state"] != "idle" or before["live"].get("queued", 0):
156            raise RuntimeError("The dedicated server must already be loaded and idle")
157        if expected + req["max_tokens"] > before["engine"]["max_context"]:
158            raise RuntimeError("Prompt plus output cap exceeds the configured context")
159        with (out / row["telemetry"]).open("w", encoding="utf-8") as telemetry:
160            sample(telemetry)
161            monitor = threading.Thread(target=monitor_loop, args=(telemetry,), daemon=True)
162            monitor.start()
163            try:
164                with (out / row["raw_stream"]).open("w", encoding="utf-8") as raw:
165                    started = time.perf_counter()
166                    first, finish, done = None, None, False
167                    wire = urllib.request.Request(url + "/v1/chat/completions", data=body,
168                                                  headers={"Content-Type": "application/json"})
169                    with urllib.request.urlopen(wire, timeout=timeout) as response:
170                        for line in response:
171                            raw.write(json.dumps({"elapsed_s": time.perf_counter() - started,
172                                                  "line": line.decode("utf-8")}, ensure_ascii=False) + "\n")
173                            raw.flush()
174                            if not line.startswith(b"data:"):
175                                continue
176                            payload = line[5:].strip()
177                            if payload == b"[DONE]":
178                                done = True
179                                break
180                            chunk = json.loads(payload)
181                            chunks.append(chunk)
182                            if chunk.get("error"):
183                                raise RuntimeError(f"Stream error: {chunk['error']}")
184                            for choice in chunk.get("choices", []):
185                                delta = choice.get("delta", {})
186                                content = delta.get("content") or ""
187                                thought = delta.get("reasoning_content") or ""
188                                if (content or thought) and first is None:
189                                    first = time.perf_counter() - started
190                                texts.append(content)
191                                reasoning.append(thought)
192                                finish = choice.get("finish_reason") or finish
193                    row.update(client_ttft_s=first, client_elapsed_s=time.perf_counter() - started,
194                               finish_reason=finish, stream_done=done)
195                    after = get(url + "/metrics")
196                    row["metrics_after"] = after
197                    engine, usage, timings = validate_completion(before, after, chunks, expected,
198                                                                  finish, done, "".join(texts + reasoning))
199                    row.update(engine=engine, usage=usage, timings=timings,
200                               prefill_tok_s=expected / (engine["prompt_ms"] / 1000),
201                               decode_tok_s=engine["engine_generated"] / (engine["decode_ms"] / 1000))
202            finally:
203                stop.set()
204                monitor.join()
205                try:
206                    sample(telemetry)
207                except Exception as error:
208                    telemetry_errors.append(f"{type(error).__name__}: {error}")
209            if telemetry_errors:
210                raise RuntimeError("Telemetry failed: " + "; ".join(telemetry_errors))
211        row["status"] = "ok"
212    except urllib.error.HTTPError as error:
213        row["error"] = {"type": type(error).__name__, "message": str(error), "http_status": error.code,
214                        "body": error.read().decode("utf-8", errors="replace")}
215    except Exception as error:
216        row["error"] = {"type": type(error).__name__, "message": str(error)}
217    finally:
218        stop.set()
219        if monitor is not None and monitor.is_alive():
220            monitor.join()
221        row.update(text="".join(texts), reasoning="".join(reasoning), finished_epoch_s=time.time())
222        if started is not None and "client_elapsed_s" not in row:
223            row["client_elapsed_s"] = time.perf_counter() - started
224        write_json(out / f"{stem}-record.json", row)
225        write_json(out / f"{stem}-chunks.json", chunks)
226    return row
227
228
229def summary(rows, targets):
230    groups = {}
231    for target in targets:
232        selected = [r for r in rows if r["label"].startswith(f"tokens-{target}-")]
233        good = [r for r in selected if r["status"] == "ok"]
234        fields = ("client_ttft_s", "client_elapsed_s", "prefill_tok_s", "decode_tok_s")
235        groups[str(target)] = {"successful_runs": len(good), "failed_attempts": len(selected) - len(good),
236                               **{field: {"median": statistics.median(v), "min": min(v), "max": max(v)}
237                                  for field in fields if (v := [r[field] for r in good])}}
238    return groups
239
240
241def main():
242    parser = argparse.ArgumentParser(description=__doc__)
243    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[3])
244    parser.add_argument("--pack", type=Path, required=True)
245    parser.add_argument("--config", type=Path, help="Server configuration, saved with relevant fields only")
246    parser.add_argument("--engine-provenance", type=Path,
247                        help="Build provenance JSON or release BUILD.json; requires --config")
248    parser.add_argument("--url", default="http://127.0.0.1:18080")
249    parser.add_argument("--model", default="strata")
250    parser.add_argument("--label", required=True, help="Configuration label, such as iq2-xs-3090-resident")
251    parser.add_argument("--out", type=Path, required=True, help="A separate directory for each configuration")
252    parser.add_argument("--targets", default="1024,4096,16384")
253    parser.add_argument("--runs", type=int, default=3)
254    parser.add_argument("--max-tokens", type=int, default=256)
255    parser.add_argument("--timeout", type=float, default=1800)
256    parser.add_argument("--telemetry-interval", type=float, default=1.0)
257    parser.add_argument("--resume", action="store_true", help="Keep completed trials and preserve failed attempts")
258    args = parser.parse_args()
259    targets = [int(value) for value in args.targets.split(",")]
260    if not targets or min(targets) <= 0 or len(set(targets)) != len(targets):
261        parser.error("Targets must be unique positive token counts")
262    if args.runs < 1 or args.max_tokens < 1 or args.timeout <= 0 or args.telemetry_interval <= 0:
263        parser.error("Runs, output cap, timeout, and telemetry interval must be positive")
264    if args.engine_provenance and not args.config:
265        parser.error("--engine-provenance requires --config to identify the executable")
266    args.root, args.pack, args.out = args.root.resolve(), args.pack.resolve(), args.out.resolve()
267    url = args.url.rstrip("/")
268    sys.path[:0] = [str(args.root), str(args.root / "tools")]
269    from strata_tokenizer import Tokenizer
270    from serve.frontend import ChatTemplate, openai_to_messages
271
272    directory = args.pack / "tokenizer"
273    vocab = json.loads((directory / "vocab.json").read_text(encoding="utf-8"))
274    tokens = [None] * len(vocab)
275    for token, number in vocab.items():
276        tokens[number] = token
277    tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text(encoding="utf-8").splitlines(),
278                          json.loads((directory / "token_type.json").read_text(encoding="utf-8")))
279    template = ChatTemplate(directory / "chat_template.jinja")
280
281    def request(content, maximum=args.max_tokens):
282        return {"model": args.model, "messages": [{"role": "user", "content": content}],
283                "temperature": 0, "reasoning_effort": "none", "max_tokens": maximum,
284                "stream": True, "stream_options": {"include_usage": True}}
285
286    def count(req):
287        messages, tools, kwargs = openai_to_messages(req)
288        return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True))
289
290    initial = get(url + "/metrics")
291    if initial["live"]["state"] != "idle" or initial["live"].get("queued", 0):
292        raise RuntimeError("Start a dedicated, loaded and idle server before this benchmark")
293    config = {}
294    executable = None
295    if args.config:
296        source = json.loads(args.config.read_text(encoding="utf-8-sig"))
297        executable = executable_record(source)
298        keys = ("exe", "cwd", "args", "gpu", "layer_split", "split_skip_if_fits", "backend", "tokenizer", "log",
299                "model_name", "parallel", "expert_profile_save", "expert_profile_save_every")
300        config = {key: source[key] for key in keys if key in source}
301        compute_variables = {"CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER", "STRATA_STAGE_TRIM", "STRATA_SPLIT_OWN",
302                             "STRATA_ARENA_PIN_GIB", "STRATA_RESIDENT_PIN", "STRATA_RESIDENT_HEADROOM_GIB",
303                             "STRATA_ARENA_MMAP", "STRATA_PREFILL_HELP", "STRATA_FETCH_THREADS", "STRATA_LOOKAHEAD",
304                             "STRATA_DECODE_TIMING", "STRATA_SPLIT_TIMING", "STRATA_VERIFY_PROFILE",
305                             "STRATA_SPLIT_MISS_MS", "STRATA_PF_FUSED", "STRATA_FILE_RELEASE"}
306        config["env"] = {key: value for key, value in source.get("env", {}).items()
307                         if key in compute_variables}
308    revision = subprocess.run(["git", "-c", f"safe.directory={args.root.as_posix()}", "rev-parse", "HEAD"],
309                              cwd=args.root, capture_output=True, text=True, check=True).stdout.strip()
310    provenance = engine_provenance_record(args.engine_provenance, executable) if args.engine_provenance else None
311    manifest = {"label": args.label, "frontend_source_commit": revision, "pack": str(args.pack),
312                "config": config, "engine_executable": executable,
313                "engine_provenance": provenance, "engine_reported_version": initial["engine"].get("version"),
314                "targets": targets, "runs": args.runs, "max_tokens": args.max_tokens,
315                "model": args.model, "server_model": initial["engine"]["model"],
316                "max_context": initial["engine"]["max_context"],
317                "hardware_static": initial.get("hardware_static"),
318                "tokenizer_sha256": {name: hashlib.sha256((directory / name).read_bytes()).hexdigest()
319                                     for name in ("vocab.json", "merges.txt", "token_type.json", "chat_template.jinja")},
320                "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
321                "method": "Serial warm-engine trials; default adaptive expert state retained; zero prompt reuse required",
322                "disk_counter_note": "file_mb is the decode file tier, possibly OS-cached; disk_read_mb is system-wide physical I/O"}
323    manifest_path = args.out / "manifest.json"
324    if manifest_path.exists():
325        if not args.resume:
326            raise RuntimeError("Output already has a manifest; use a new output directory or --resume")
327        if digest(json.loads(manifest_path.read_text(encoding="utf-8"))) != digest(manifest):
328            raise RuntimeError("Resume manifest differs; use a new output directory")
329    elif args.resume:
330        raise RuntimeError("Cannot resume: output has no manifest")
331    args.out.mkdir(parents=True, exist_ok=True)
332    write_json(manifest_path, manifest)
333    rows_path = args.out / "results.json"
334    rows = json.loads(rows_path.read_text(encoding="utf-8")) if args.resume and rows_path.exists() else []
335    session = uuid.uuid4().hex[:12]
336    write_json(args.out / f"session-{session}.json", {"session": session, "epoch_s": time.time(),
337               "python": sys.version, "platform": platform.platform(), "initial_metrics": initial,
338               "initial_status": get(url + "/v1/status"), "resumed": args.resume})
339
340    def run(label, req):
341        if any(row["label"] == label and row["status"] == "ok" for row in rows):
342            print("skip completed", label, flush=True)
343            return
344        attempt = sum(row["label"] == label for row in rows) + 1
345        print("start", args.label, label, "tokens", count(req), flush=True)
346        row = perform(url, args.out, session, label, attempt, req, count(req),
347                      args.telemetry_interval, args.timeout)
348        rows.append(row)
349        write_json(rows_path, rows)
350        write_json(args.out / "summary.json", summary(rows, targets))
351        print(row["status"], label, json.dumps({key: row.get(key) for key in
352              ("client_ttft_s", "prefill_tok_s", "decode_tok_s", "error")}), flush=True)
353        if row["status"] != "ok":
354            raise RuntimeError(f"Benchmark stopped after failed trial {label}; evidence was retained")
355
356    run(f"warmup-{session}", request(f"Warmup {session}. Reply with exactly the word READY.", 16))
357    filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003"
358                       for i in range(12000))
359    ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, "
360              "modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.")
361    for target in targets:
362        for trial in range(1, args.runs + 1):
363            # Checkpoints cover a complete turn or >=16K prompt tokens by default;
364            # this early differing nonce prevents a whole checkpoint from matching.
365            prefix = f"Benchmark nonce: series-{target}-trial-{trial}.\nReview this synthetic Python module:\n"
366            low, high = 0, len(filler)
367            while low < high:
368                middle = (low + high + 1) // 2
369                if count(request(prefix + filler[:middle] + ending)) <= target:
370                    low = middle
371                else:
372                    high = middle - 1
373            req = request(prefix + filler[:low] + ending)
374            if not target - 20 <= count(req) <= target:
375                raise RuntimeError(f"Could not construct target {target}: {count(req)}")
376            run(f"tokens-{target}-run-{trial}", req)
377    print("Complete:", args.out / "summary.json", flush=True)
378
379
380if __name__ == "__main__":
381    main()