#!/usr/bin/env python3 """Warm same-process CPU KAR / CUDA PLE comparison through Strata's native protocol. Offline evaluation only. The engine serves the same pretokenized prompt several times with prompt and conversation reuse disabled. Raw engine logs stay in a private output directory; stdout contains aggregate data only. """ import argparse import hashlib import json import os from pathlib import Path import queue import statistics import subprocess import threading def replace_arg(args, flag, value): args[args.index(flag) + 1] = value def drain_stdout(stream, lines): for line in stream: lines.put(line.rstrip("\n")) lines.put(None) def until(lines, label, timeout): while True: line = lines.get(timeout=timeout) if line is None: raise RuntimeError(f"{label}: engine ended before the expected response") if line.startswith("ERR "): raise RuntimeError(f"{label}: {line}") yield line def request(proc, lines, tokens, max_new, label): proc.stdin.write(f"GEN {max_new} {','.join(map(str, tokens))}\n") proc.stdin.flush() ids = [] for line in until(lines, label, 300): if line.startswith("T "): ids.append(int(line[2:])) if line.startswith("DONE "): fields = line.split() if len(fields) < 9: raise RuntimeError(f"{label}: short DONE line") done = {"generated": int(fields[1]), "prompt": int(fields[2]), "prompt_ms": float(fields[3]), "decode_ms": float(fields[4]), "finish": fields[5], "drafts_accepted": int(fields[6]), "drafts_offered": int(fields[7]), "reused": int(fields[8])} if done["generated"] != len(ids) or done["reused"] != 0: raise RuntimeError(f"{label}: output count or zero-reuse contract failed") done["output_ids_sha256"] = hashlib.sha256(" ".join(map(str, ids)).encode()).hexdigest() # The report lives only in the caller's private output directory. # Keep IDs so a long-form quality check can detokenize exact output. done["output_ids"] = ids done["prefill_tokens_per_second"] = 1000 * done["prompt"] / done["prompt_ms"] done["decode_tokens_per_second"] = 1000 * done["generated"] / done["decode_ms"] return done def arm(engine, common, extra, out, name, prompts, warmups, repeats, max_new): lines = queue.Queue() with (out / f"{name}.stderr").open("wb") as log: proc = subprocess.Popen([str(engine), *common, *extra], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, text=True, bufsize=1, start_new_session=True) reader = threading.Thread(target=drain_stdout, args=(proc.stdout, lines), daemon=True) reader.start() try: for line in until(lines, f"{name} startup", 900): if line.startswith("READY "): break result = {} for prompt_name, tokens in prompts.items(): samples = [] for index in range(warmups + repeats): item = request(proc, lines, tokens, max_new, f"{name}/{prompt_name}/{index}") if index >= warmups: samples.append(item) result[prompt_name] = samples proc.stdin.write("QUIT\n") proc.stdin.flush() if proc.wait(timeout=30) != 0: raise RuntimeError(f"{name}: engine exited with {proc.returncode}") return result finally: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=10) except subprocess.TimeoutExpired: proc.kill() proc.wait(timeout=10) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--engine", required=True, type=Path) parser.add_argument("--config", required=True, type=Path) parser.add_argument("--archive", required=True, type=Path) parser.add_argument("--out", required=True, type=Path) parser.add_argument("--cache-mib", type=int, default=64) parser.add_argument("--expert-slots", type=int, default=9000) parser.add_argument("--tokens-file", type=Path, help="comma-separated pretokenized private prompt; replaces synthetic prompts") parser.add_argument("--arms", default="cpu,gpu", help="ordered subset of native,cpu,gpu (default cpu,gpu)") parser.add_argument("--warmups", type=int, default=1) parser.add_argument("--repeats", type=int, default=5) parser.add_argument("--max-new", type=int, default=16) parser.add_argument("--static-experts", action="store_true", help="disable adaptive expert swaps for a stable residency policy") parser.add_argument("--ignore-eos", action="store_true", help="run to max-new with an unreachable EOS ID for decode timing") parser.add_argument("--gpu-first", action="store_true", help="reverse startup order to expose warm file-cache effects") options = parser.parse_args() selected = options.arms.split(",") if len(selected) < 2 or len(set(selected)) != len(selected) or \ any(name not in ("native", "cpu", "gpu") for name in selected): parser.error("--arms needs two or three distinct arms from native,cpu,gpu") if options.out.exists() or not 1 <= options.cache_mib <= 1024 or \ options.expert_slots < 1 or options.warmups < 1 or not 1 <= options.repeats <= 30: parser.error("invalid output path or measurement parameters") options.out.mkdir(mode=0o700, parents=True) os.chmod(options.out, 0o700) source = json.loads(options.config.read_text()) common = list(source["args"]) if "--ple-kar" in common or "--ple-kar-gpu-cache-mib" in common or "--serve" in common: parser.error("source config already selects an experiment") replace_arg(common, "--expert-cache", str(options.expert_slots)) common += ["--serve", "--prompt-cache", "0", "--conversation-cache-mib", "0", "--stats"] if options.static_experts: common += ["--adapt-swaps", "0"] if options.ignore_eos: common += ["--eos-ids", "2147483647"] if options.tokens_file: raw = options.tokens_file.read_text().strip() try: ids = [int(token) for token in raw.split(",")] except ValueError: parser.error("--tokens-file must contain comma-separated integer IDs") if not ids or any(token < 0 or token > 2147483647 for token in ids): parser.error("--tokens-file contains invalid token IDs") prompts = {"long": ids} else: prompts = {"unique": list(range(1, 2049)), "repeated": list(range(1, 129)) * 16} report = {} kar = ["--ple-kar", str(options.archive), "--ple-kar-level", "2"] arms = [(name, {"native": [], "cpu": kar, "gpu": kar + ["--ple-kar-gpu-cache-mib", str(options.cache_mib)]}[name]) for name in selected] if options.gpu_first: arms.reverse() report["arm_order"] = [name for name, _ in arms] for name, extra in arms: report[name] = arm(options.engine, common, extra, options.out, name, prompts, options.warmups, options.repeats, options.max_new) (options.out / "summary.json").write_text(json.dumps(report, indent=2) + "\n") report["output_ids_exact"] = all( len({report[name][kind][i]["output_ids_sha256"] for name, _ in arms}) == 1 for kind in prompts for i in range(options.repeats)) medians = {} for kind in prompts: medians[kind] = { arm_name: {field: statistics.median(item[field] for item in report[arm_name][kind]) for field in ("prompt_ms", "decode_ms", "prefill_tokens_per_second", "decode_tokens_per_second")} for arm_name, _ in arms} report["medians"] = medians (options.out / "summary.json").write_text(json.dumps(report, indent=2) + "\n") print(json.dumps({"output_ids_exact": report["output_ids_exact"], "medians": medians}, indent=2)) if __name__ == "__main__": main()