#!/usr/bin/env python3 """Offline paired probe for expert-cache pressure from a planned GPU resident record. Writes raw model output only to a private output directory. This reserves a memory *budget* with Strata's own planner; it does not run KAR CUDA decoding. """ import argparse import hashlib import json import os from pathlib import Path import re import subprocess import time def private_write(path: Path, data: bytes) -> None: fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) with os.fdopen(fd, "wb") as file: file.write(data) def measure(engine: Path, config: dict, prompt: Path, out: Path, reserve: int, max_new: int, tag: str) -> dict: args = list(config["args"]) if "--serve" in args or "--ple-kar" in args or "--control-vector-scaled" in args: raise ValueError("requires the plain offline native engine profile") if args[args.index("--expert-cache") + 1] != "auto": raise ValueError("requires automatic expert-cache sizing") args[args.index("--vram-reserve-mib") + 1] = str(reserve) cmd = [str(engine), *args, "--tokens-file", str(prompt), "--max-new", str(max_new)] start = time.monotonic() result = subprocess.run(cmd, cwd=config["cwd"], capture_output=True, timeout=900, check=False) wall = time.monotonic() - start private_write(out / f"{tag}.stdout", result.stdout) private_write(out / f"{tag}.stderr", result.stderr) stdout = result.stdout.decode("utf-8", errors="replace") stderr = result.stderr.decode("utf-8", errors="replace") token_line = re.search(r"^output\s*:\s*(.*)$", stdout, re.MULTILINE) cache = re.search(r"expert cache (\d+) slots, ([\d.]+) GiB", stderr) decode = re.search(r"^decode\s+(\d+) tokens in ([\d.]+) ms\s+->\s+([\d.]+) tok/s", stdout, re.MULTILINE) prefill = re.search(r"^prefill\s+(\d+) tokens in ([\d.]+) ms\s+->\s+([\d.]+) tok/s", stdout, re.MULTILINE) cpu_experts = re.search(r"CPU experts ([\d.]+) distinct / ([\d.]+) routed per layer", stdout) pcie_experts = re.search(r"pcie experts\s+([\d.]+) distinct experts per layer", stdout) if result.returncode or not token_line or not cache or not decode or not prefill: raise RuntimeError(f"reserve={reserve}: engine failed or did not emit expected metrics; " f"see private logs, exit={result.returncode}") tokens = token_line.group(1).split() return { "reserve_mib": reserve, "exit_code": result.returncode, "full_process_wall_s": round(wall, 3), "expert_slots": int(cache.group(1)), "expert_cache_gib": float(cache.group(2)), "prefill_tokens": int(prefill.group(1)), "prefill_ms": float(prefill.group(2)), "prefill_tok_s": float(prefill.group(3)), "decode_tokens": int(decode.group(1)), "decode_ms": float(decode.group(2)), "decode_tok_s": float(decode.group(3)), "cpu_experts_distinct_per_layer": float(cpu_experts.group(1)) if cpu_experts else None, "cpu_experts_routed_per_layer": float(cpu_experts.group(2)) if cpu_experts else None, "pcie_experts_distinct_per_layer": float(pcie_experts.group(1)) if pcie_experts else None, "output_ids": tokens, } def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", type=Path, required=True) parser.add_argument("--engine", type=Path, required=True) parser.add_argument("--prompt", type=Path, required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--max-new", type=int, default=160) parser.add_argument("--rounds", type=int, default=1) parser.add_argument("--base-reserve-mib", type=int, default=700) parser.add_argument("--extra-reserve-mib", type=int, default=10240) options = parser.parse_args() if (options.max_new < 1 or options.max_new > 512 or options.extra_reserve_mib < 1 or options.rounds < 1 or options.rounds > 10): parser.error("max-new must be 1..512, extra reserve positive, rounds 1..10") config = json.loads(options.config.read_text()) args = config["args"] if int(args[args.index("--vram-reserve-mib") + 1]) != options.base_reserve_mib: parser.error("source profile's VRAM reserve changed") options.out.mkdir(mode=0o700, parents=True, exist_ok=False) results = [] comparisons = [] base, pressured = options.base_reserve_mib, options.base_reserve_mib + options.extra_reserve_mib for round_id in range(options.rounds): order = (base, pressured) if round_id % 2 == 0 else (pressured, base) pair = {} for reserve in order: result = measure(options.engine, config, options.prompt, options.out, reserve, options.max_new, f"round-{round_id}-reserve-{reserve}") result["round"] = round_id results.append(result) pair[reserve] = result a, b = pair[base], pair[pressured] first_difference = next((i for i, tokens in enumerate(zip(a["output_ids"], b["output_ids"])) if tokens[0] != tokens[1]), None) if first_difference is None and len(a["output_ids"]) != len(b["output_ids"]): first_difference = min(len(a["output_ids"]), len(b["output_ids"])) comparisons.append({"round": round_id, "same_output_ids": first_difference is None, "first_different_output_index": first_difference}) for item in results: ids = item.pop("output_ids") item["output_count"] = len(ids) item["output_ids_sha256"] = hashlib.sha256(" ".join(ids).encode()).hexdigest() with options.engine.open("rb") as engine_file, options.prompt.open("rb") as prompt_file: engine_digest = hashlib.file_digest(engine_file, "sha256").hexdigest() prompt_digest = hashlib.file_digest(prompt_file, "sha256").hexdigest() report = { "engine_sha256": engine_digest, "prompt_sha256": prompt_digest, "max_new": options.max_new, "comparisons": comparisons, "arms": results, } private_write(options.out / "summary.json", json.dumps(report, indent=2).encode() + b"\n") print(json.dumps(report, indent=2)) if __name__ == "__main__": main()