#!/usr/bin/env python3 """Bench 3 cell runner (docs/PLAN-bench3.ja.md): one engine x one b3 scenario, R1-R6 on one server start. python runner3.py --engine engines/b3-fork-27b.json --scenario scenarios/b3-agent-32k.json --out rows.jsonl \ --round 1 --order-pos 1 --attempt 1 Rows (JSON lines, same base fields as runner.py): phase warmup / canary / request (R1..R6d) / canary2 / cell. Generated text is kept under / (not for commit); rows carry metrics and checks only. """ from __future__ import annotations import argparse import ast import ctypes import json import os import random import re import subprocess import sys import threading import time import unicodedata from pathlib import Path import runner as R ROOT = R.ROOT SAMPLING = {"on": {"temperature": 0.6, "top_p": 0.95, "top_k": 20}, "off": {"temperature": 0.7, "top_p": 0.8, "top_k": 20}} SEEDS = {"R1": 7, "R2": 8, "R3": 9, "R4": 7, "R5": 8} # --------------------------------------------------------------- memory / swap / thermal _libc = ctypes.CDLL("/usr/lib/libproc.dylib") def phys_footprint(pid: int) -> int: buf = ctypes.create_string_buffer(512) if _libc.proc_pid_rusage(pid, 2, buf) != 0: # RUSAGE_INFO_V2 return 0 return int.from_bytes(buf.raw[72:80], "little") # ri_phys_footprint def tree_pids(root: int) -> list[int]: out = subprocess.run(["ps", "-axo", "pid=,ppid="], capture_output=True, text=True).stdout.split() kids: dict[int, list[int]] = {} for pid, ppid in zip(out[0::2], out[1::2]): kids.setdefault(int(ppid), []).append(int(pid)) res, stack = [], [root] while stack: p = stack.pop() res.append(p) stack.extend(kids.get(p, [])) return res class Footprint(threading.Thread): """200 ms samples of phys_footprint: the largest process and the sum over the tree; windows per request.""" def __init__(self, root_pid: int, path: Path): super().__init__(daemon=True) self.root, self.path = root_pid, path self.stop_event = threading.Event() self.window = {"max_proc": 0, "sum": 0, "wired": 0} self.cell = {"max_proc": 0, "sum": 0, "wired": 0} def reset_window(self) -> dict: w, self.window = self.window, {"max_proc": 0, "sum": 0, "wired": 0} return w def run(self) -> None: tick = 0 with self.path.open("a") as fh: while not self.stop_event.is_set(): try: vals = [phys_footprint(p) for p in tree_pids(self.root)] s = {"max_proc": max(vals or [0]), "sum": sum(vals)} if tick % 5 == 0: s["wired"] = R.vm_bytes().get("wired", 0) for d in (self.window, self.cell): for k, v in s.items(): d[k] = max(d[k], v) if tick % 5 == 0: fh.write(json.dumps({"t": time.time(), **s}) + "\n") fh.flush() tick += 1 except Exception: pass self.stop_event.wait(0.2) def swap_state() -> dict: out = subprocess.run(["sysctl", "-n", "vm.swapusage"], capture_output=True, text=True).stdout m = re.search(r"used = ([0-9.]+)M", out) vm = subprocess.run(["vm_stat"], capture_output=True, text=True).stdout g = lambda name: int((re.search(name + r":\s+(\d+)", vm) or [0, 0])[1]) return {"swap_used_mb": float(m.group(1)) if m else None, "swapins": g("Swapins"), "swapouts": g("Swapouts"), "compressor": g("Pages occupied by compressor")} def thermal() -> str: return subprocess.run(["pmset", "-g", "therm"], capture_output=True, text=True).stdout.strip().replace("\n", " | ")[:300] # --------------------------------------------------------------- corpus slice with embedded facts LABELS = ["Aster", "Birch", "Cedar"] FACT = { "code": "# NOTE: the {label} key is {val}.", "en": "The housekeeper's ledger recorded the {label} key as {val}.", "ja": "帳面には、{label}の合言葉は「{val}」と記してあった。", "agent": "[tool output] {label} key: {val}", } START_MARK = {"code": "# ===== file:", "agent": "===== session", "en": "\n\nCHAPTER", "ja": "\n\n"} def corpus_slice(tok, scen: dict, target_tokens: int, max_tokens_budget: int) -> dict: """target_tokens of the corpus from the ~10% start, three facts at 10/50/90%. Returns text, facts, token count.""" text = (ROOT / "corpora" / scen["corpus"]).read_text(encoding="utf-8") a = int(len(text) * 0.10) j = text.find(START_MARK[scen["genre"]], a) start = j if j >= 0 else a rng = random.Random(f"{scen['id']}") facts = [{"label": l, "val": f"{rng.randint(1000, 9999)}-{rng.choice(['ALPHA', 'BETA', 'GAMMA', 'DELTA'])}"} for l in LABELS] sentences = [FACT[scen["genre"]].format(**f) + "\n" for f in facts] extra = sum(len(tok.encode(s).ids) for s in sentences) + 8 want = max(64, target_tokens - extra) window = text[start:start + want * 9] ids = tok.encode(window).ids if len(ids) < want: return {"short": True, "have": len(ids), "want": want} body = tok.decode(ids[:want]) lines = body.split("\n") out, total = [], len(body) marks = [0.10, 0.50, 0.90] pos, nxt = 0, 0 for line in lines: out.append(line) pos += len(line) + 1 if nxt < 3 and pos >= marks[nxt] * total: out.append(sentences[nxt].rstrip("\n")) nxt += 1 while nxt < 3: out.append(sentences[nxt].rstrip("\n")) nxt += 1 ctx = "\n".join(out) return {"short": False, "text": scen.get("context_prefix", "") + ctx, "facts": facts, "start_char": start, "tokens": len(tok.encode(scen.get("context_prefix", "") + ctx).ids)} # --------------------------------------------------------------- streaming with answer timing def stream3(base: str, payload: dict, timeout: float) -> dict: import urllib.request req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(payload).encode(), headers={"content-type": "application/json"}, method="POST") t0 = time.perf_counter() first = last = ans_first = ans_last = None reasoning, content = [], [] usage = finish = error = None parser = "reasoning_content" try: with urllib.request.urlopen(req, timeout=timeout) as resp: for raw in resp: line = raw.decode("utf-8", "replace").strip() if not line.startswith("data:"): continue data = line[5:].strip() if data == "[DONE]": break try: obj = json.loads(data) except json.JSONDecodeError: continue error = obj.get("error") or error usage = obj.get("usage") or usage for ch in obj.get("choices") or []: d = ch.get("delta") or {} r = d.get("reasoning_content") or d.get("reasoning") or "" c = d.get("content") or "" now = time.perf_counter() - t0 if r or c: first = now if first is None else first last = now if r: reasoning.append(r) if c: content.append(c) # a ... block inside content (engines without reasoning_content) joined = "".join(content) if "" in joined: parser = "think_tag" tail = joined.split("", 1)[1].strip() if tail: ans_first = now if ans_first is None else ans_first ans_last = now elif "" not in joined or reasoning: ans_first = now if ans_first is None else ans_first ans_last = now finish = ch.get("finish_reason") or finish except Exception as exc: error = repr(exc) content_s = "".join(content) reasoning_s = "".join(reasoning) if "" in content_s: reasoning_s = reasoning_s + content_s.split("", 1)[0].replace("", "") content_s = content_s.split("", 1)[1].strip() return {"e2e_s": time.perf_counter() - t0, "ttft_any": first, "last_s": last, "ttft_answer": ans_first, "ans_last_s": ans_last, "content": content_s, "reasoning": reasoning_s, "usage": usage, "finish_reason": finish, "error": error, "parser": parser} def norm(s: str) -> str: s = unicodedata.normalize("NFKC", s).lower() return re.sub(r"[\s‐-―−\-_]+", "", s) def repetition(text: str) -> dict: toks = text.split() grams = [" ".join(toks[i:i + 20]) for i in range(max(0, len(toks) - 19))] dup = 1 - len(set(grams)) / len(grams) if grams else 0.0 lines = [l.strip() for l in text.split("\n") if len(l.strip()) >= 20] worst = max((lines.count(l) for l in set(lines)), default=0) return {"dup20": round(dup, 4), "max_line_repeat": worst, "looped": dup > 0.10 or worst >= 3} def format_check(genre: str, answer: str) -> dict: if genre == "code": blocks = re.findall(r"```(?:python|py)?\n(.*?)```", answer, re.S) or [answer] for b in blocks: try: ast.parse(b) return {"format_ok": True} except SyntaxError: continue return {"format_ok": False} m = re.search(r"\{.*\}|\[.*\]", answer, re.S) try: json.loads(m.group(0) if m else answer) return {"format_ok": True} except Exception: return {"format_ok": False} # --------------------------------------------------------------- main def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--engine", required=True) ap.add_argument("--scenario", required=True) ap.add_argument("--out", required=True) ap.add_argument("--round", type=int, default=1) ap.add_argument("--order-pos", type=int, default=0) ap.add_argument("--attempt", type=int, default=1) ap.add_argument("--kv", default=None) a = ap.parse_args() from tokenizers import Tokenizer spec = json.loads(Path(a.engine).read_text()) scen = json.loads(Path(a.scenario).read_text()) kv = a.kv or spec.get("default_kv", "q8") variant = spec["kv_variants"][kv] spec = {**spec, **{k: v for k, v in variant.items() if k != "cmd_extra"}, "cmd": spec["cmd"] + variant.get("cmd_extra", [])} model_dir = R.expand(spec["tokenizer_dir"], {**os.environ, **R.local_vars()}) tok = Tokenizer.from_file(str(Path(model_dir) / "tokenizer.json")) out = Path(a.out) out.parent.mkdir(parents=True, exist_ok=True) stamp = time.strftime("%Y%m%d-%H%M%S") cell_dir = out.parent / "cells" / f"{stamp}-{spec['id']}-{scen['id']}-r{a.round}a{a.attempt}" cell_dir.mkdir(parents=True) base = {"run_stamp": stamp, "engine": spec["id"], "engine_label": spec["label"], "kv": kv, "scenario": scen["id"], "genre": scen["genre"], "context_target": scen["context_tokens"], "round": a.round, "order_pos": a.order_pos, "attempt": a.attempt, "bench": 3} def emit(row: dict) -> None: with out.open("a") as fh: fh.write(json.dumps({**base, **row}, ensure_ascii=False) + "\n") print(json.dumps({k: row.get(k) for k in ("phase", "request", "prompt_tokens", "ttft_any", "ttft_answer", "decode_tok_s", "e2e_s", "error", "failure")}), flush=True) # the length budget (plan 3.2): the window minus the biggest generation, the question, the template and a margin qtok = max(len(tok.encode(q).ids) for q in scen["questions"].values()) limit = 262144 - scen["requests"][0]["max_tokens"] - qtok - 64 - 256 target = min(scen["context_tokens"], limit) sl = corpus_slice(tok, scen, target, scen["requests"][0]["max_tokens"]) if sl["short"]: emit({"phase": "cell", "failure": "corpus", "detail": sl}) return base.update(context_tokens_raw=sl["tokens"], context_start_char=sl["start_char"], context_limit=limit) engine = R.Engine(spec, cell_dir, R.local_vars()) cell_t0 = time.time() fp = None deadline = cell_t0 + float(scen.get("cell_deadline_s", 3 * 3600 if scen["context_tokens"] >= 131072 else 5400)) try: base["swap_before"], base["thermal_before"] = swap_state(), thermal() load_s = engine.start() base.update(engine_version=engine.version(), load_s=load_s) root = R.port_pids(engine.port)[0] fp = Footprint(root, cell_dir / "memory.jsonl") fp.start() tmo = lambda: max(60.0, min(7200.0, deadline - time.time())) def req(messages, think, max_tokens, seed): payload = {"model": spec["model_id"], "messages": messages, "max_tokens": max_tokens, "stream": True, "stream_options": {"include_usage": True}, **SAMPLING["on" if think else "off"], "seed": seed, "chat_template_kwargs": {"enable_thinking": think}} if think: payload["reasoning_effort"] = "medium" payload["chat_template_kwargs"]["reasoning_effort"] = "medium" payload.update(spec.get("request_extra", {})) fp.reset_window() engine.pre_request() off = engine.log_size() r = stream3(engine.base, payload, tmo()) r["mem"] = fp.reset_window() r["engine_stats"] = engine.stats(off) return r def metrics(r, think): u = r["usage"] or {} det = u.get("prompt_tokens_details") or {} comp = u.get("completion_tokens") or len(tok.encode(r["reasoning"] + r["content"]).ids) think_tok = len(tok.encode(r["reasoning"]).ids) if r["reasoning"] else 0 span = (r["last_s"] - r["ttft_any"]) if r["ttft_any"] is not None and r["last_s"] else None aspan = (r["ans_last_s"] - r["ttft_answer"]) if r["ttft_answer"] is not None and r["ans_last_s"] else None ans_tok = max(0, comp - think_tok) return {"prompt_tokens": u.get("prompt_tokens"), "cached_tokens": det.get("cached_tokens"), "completion_tokens": comp, "thinking_tokens": think_tok, "answer_tokens": ans_tok, "ttft_any": r["ttft_any"], "ttft_answer": r["ttft_answer"], "e2e_s": r["e2e_s"], "decode_tok_s": (comp - 1) / span if span and comp > 1 else None, "decode_answer_tok_s": (ans_tok - 1) / aspan if aspan and ans_tok >= 64 else None, "finish_reason": r["finish_reason"], "error": r["error"], "parser": r["parser"], "footprint_max_proc": r["mem"]["max_proc"], "footprint_sum": r["mem"]["sum"], "wired": r["mem"]["wired"], "engine_stats": r["engine_stats"]} w = req([{"role": "user", "content": "Say hello in five words."}], False, 16, 1) emit({"phase": "warmup", **metrics(w, False)}) canary_text = (ROOT / "corpora" / "prose-en-trollope.txt").read_text()[200000:204000] cmsg = [{"role": "user", "content": canary_text + "\n\nSummarize the passage above in two sentences."}] c = req(cmsg, False, 128, 1) emit({"phase": "canary", **metrics(c, False)}) prefix = sl["text"] + "\n\n" t_requests = time.time() for rq in scen["requests"]: rid = rq["id"] if (spec.get("skip_long") and scen["context_tokens"] >= 131072 and rid in spec["skip_long"]) or time.time() > deadline: continue qs = rq["question"] if rq.get("fact") is not None: f = sl["facts"][rq["fact"]] if rq["fact"] >= 0 else {"label": "Zephyr", "val": ""} qs = scen["fact_question"].format(label=f["label"]) content = prefix + (qs if rq.get("fact") is not None else scen["questions"][qs]) before = swap_state() if rid == "R1" else None r = req([{"role": "user", "content": content}], rq["think"], rq["max_tokens"], rq.get("seed") or SEEDS.get(rid, 7)) m = metrics(r, rq["think"]) row = {"phase": "request", "request": rid, "think": rq["think"], **m} if before: row["swap_delta"] = {k: swap_state()[k] - before[k] if before[k] is not None else None for k in before} if rid == "R1" and m["cached_tokens"]: row["note"] = "cold prefill had cached_tokens" ans = r["content"] chk = {} if rq.get("fact") is not None: if rq["fact"] >= 0: chk["fact_ok"] = norm(f["val"]) in norm(ans) else: chk["fact_ok"] = bool(re.search(r"not mentioned|no mention|not (?:in|found)|記載|書かれて|言及|ありません|見当たら|不明|don't|cannot", ans, re.I)) if rid in ("R4",): chk.update(format_check(scen["genre"], ans)) chk.update(repetition(ans) if ans else {}) if r["reasoning"]: chk["reasoning_dup20"] = repetition(r["reasoning"])["dup20"] if rq["think"] and not ans: chk["no_answer"] = True row["checks"] = chk (cell_dir / f"{rid}.txt").write_text((r["reasoning"] + "\n=====\n" + ans) if r["reasoning"] else ans) emit(row) if m["error"]: break requests_s = time.time() - t_requests if scen["context_tokens"] >= 32768: c2 = req(cmsg, False, 128, 1) emit({"phase": "canary2", **metrics(c2, False)}) emit({"phase": "cell", "total_e2e_s": time.time() - cell_t0, "requests_e2e_s": requests_s, "load_s": load_s, "swap_after": swap_state(), "thermal_after": thermal(), "cell_footprint_max_proc": fp.cell["max_proc"], "cell_footprint_sum": fp.cell["sum"], "cell_wired": fp.cell["wired"]}) except Exception as exc: emit({"phase": "cell", "failure": "harness", "detail": repr(exc), "total_e2e_s": time.time() - cell_t0}) finally: if fp: fp.stop_event.set() engine.stop() if __name__ == "__main__": main()