"""Build the FINAL Phase 3 results page. Every number comes from results/phase3/final_numbers.json (written by final_report.py from the raw per-item records), plus the per-item records themselves (progress table) and Phase 2's p2_metrics.json (reference accuracies of Stock / CoDA-1.7B / Qwen3-0.6B in Figure 2). Prose is rendered from results/phase3/REPORT.md and code/phase3/README.md, so the page and the report cannot disagree. Usage (repo root): /venv/p2/bin/python -I logs/phase3/extrap/final_report.py /venv/p2/bin/python -I logs/phase3/extrap/build_final.py results/phase3/final_numbers.json results/phase3/REPORT.md logs/phase3/extrap/phase3_redraft.html """ import glob, html, json, os, re, sys, datetime as dt NUM, REPORT, OUT = sys.argv[1:4] N = json.load(open(NUM)); B = N["benchmarks"]; S = N["samples"] P2 = json.load(open("logs/phase3/extrap/p2_metrics.json")) RT = open(REPORT).read() IST = dt.timezone(dt.timedelta(hours=5, minutes=30)) e = html.escape ORDER = ["humaneval", "mbpp", "gsm8k500", "ifeval541", "math500", "gpqa", "aime"] # the Phase 2 page's order NAMES = {"humaneval": "HumanEval", "mbpp": "MBPP", "gsm8k500": "GSM8K-500", "ifeval541": "IFEval-541", "math500": "MATH-500", "gpqa": "GPQA-Diamond", "aime": "AIME"} XSENT = ("EXTRAPOLATED — based on the extrapolation using the measured numbers on 4× GPUs for this dataset for this model, using reference " "from the runs from this model (the base pipeline measured on the Phase 1 8× box).") XT = "extrapolated"; XTA = "extrapolated, drift-adjusted"; MT = "measured on the Phase 1 box" def n_exp(s): return P2[s]["S0_nopool"]["n"] # benchmark size def f1(x): return f"{x:.1f}" def f2(x): return f"{x:.2f}" def f3(x): return f"{x:.3f}" def sg(v, d=1): return ("−" if v < 0 else "+") + f"{abs(v):.{d}f}" # same sign convention as REPORT.md (+0.0 stays +0.0) def dash(): return "·" def wall(m): return f"{m:.1f} min" if m else dash() # ---------------------------------------------------------------- tiny markdown renderer (REPORT.md / README.md prose) def inline(t): codes = [] def stash(m): codes.append(m.group(1)); return f"\x00{len(codes) - 1}\x00" t = re.sub(r"`([^`]+)`", stash, t) # code spans first, so ** inside them (e.g. `decode/**`) is left alone t = html.escape(t, quote=False) t = re.sub(r"\*\*(.+?)\*\*", r"\1", t) return re.sub(r"\x00(\d+)\x00", lambda m: "" + html.escape(codes[int(m.group(1))], quote=False) + "", t) def md_blocks(lines): out, para, i = [], [], 0 def flush(): if para: out.append(("p", " ".join(para))); para.clear() while i < len(lines): l = lines[i] if l.startswith("```"): flush(); j = i + 1; code = [] while j < len(lines) and not lines[j].startswith("```"): code.append(lines[j]); j += 1 out.append(("code", "\n".join(code))); i = j + 1; continue if l.startswith("|") or l.startswith("#"): flush(); i += 1; continue # tables are rebuilt from final_numbers.json m = re.match(r"^(-|\d+\.)\s+(.*)$", l) if m: flush(); kind = "ol" if m.group(1)[0].isdigit() else "ul"; items = [m.group(2)]; i += 1 while i < len(lines): m2 = re.match(r"^(-|\d+\.)\s+(.*)$", lines[i]) if m2: items.append(m2.group(2)); i += 1 elif lines[i].startswith(" ") and lines[i].strip(): items[-1] += " " + lines[i].strip(); i += 1 else: break out.append((kind, items)); continue if not l.strip(): flush(); i += 1; continue para.append(l.strip()); i += 1 flush(); return out def md_html(blocks): h = [] for kind, v in blocks: if kind == "p": h.append(f"

{inline(v)}

") elif kind in ("ul", "ol"): h.append(f"<{kind}>" + "".join(f"
  • {inline(x)}
  • " for x in v) + f"") elif kind == "code": h.append(f"
    {html.escape(v)}
    ") return "".join(h) def sections(text): secs, cur = {}, None for l in text.splitlines(): m = re.match(r"^## (\d+)\. ", l) if m: cur = int(m.group(1)); secs[cur] = [] elif cur is not None: secs[cur].append(l) return secs RS = sections(RT) def pick(sec, *prefixes): """paragraphs of a REPORT section whose text starts with one of the prefixes (in the order given)""" bl = md_blocks(RS.get(sec, [])); out = [] for pf in prefixes: hit = [b for b in bl if b[0] == "p" and b[1].startswith(pf)] if hit: out.append(hit[0]) else: print(f"WARNING: REPORT.md section {sec}: no paragraph starting with {pf!r}", file=sys.stderr) return md_html(out) # ---------------------------------------------------------------- records (progress table) def recinfo(pat): n, last = 0, None for f in glob.glob(pat): if f.endswith("running.jsonl"): continue for l in open(f): if not l.strip(): continue try: r = json.loads(l) except ValueError: continue n += 1; u = r.get("utc") if u and (last is None or u > last): last = u return n, last def ist(u): return dt.datetime.strptime(u, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc).astimezone(IST).strftime("%d %b %H:%M") if u else dash() NOW = dt.datetime.now(dt.timezone.utc) def alive(u): return bool(u) and (NOW - dt.datetime.strptime(u, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)).total_seconds() < 20 * 60 def chip(kind, txt): return f"{e(txt)}" def state_of(done_marker, n, total, last): if os.path.exists(done_marker) and n >= total: return chip("done", "done") if n == 0: return chip("stopped", "not run: stopped by the lead") return chip("running", "running") if alive(last) else chip("stopped", f"stopped at {n}/{total}") prog = [] for s in ORDER: total = n_exp(s); full = s in B for a in ("rd1", "rd2", "base"): if a == "base": pat, mk = (f"logs/phase3/decode/judge/{s}/*.jsonl", f"logs/phase3/decode/judge/{s}/.complete") if full else (f"logs/phase3/decode/judge_sample/{s}/*.jsonl", None) else: pat, mk = f"logs/phase3/decode/{a}/{s}/*.jsonl", f"logs/phase3/decode/{a}/{s}/.complete" n, last = recinfo(pat) if a == "base" and not full: st = chip("done", "done (first items only)") if n else chip("stopped", "not run"); tot = f"{n}/{total}" else: st = state_of(mk, n, total, last); tot = f"{n}/{total}" if full: w = (B[s]["wall_base_min"] if a == "base" else B[s]["arms"][a]["wall_here_min"]) else: w = None label = "base pipeline" if a == "base" else a prog.append(f"{label}{NAMES[s]}{tot}{wall(w)}{ist(last) if n else dash()}{st}") PROGRESS = "".join(prog) # ---------------------------------------------------------------- status banner and summary complete, partial = [], [] for s, b in B.items(): n = n_exp(s) if b["full_base_run"] and b["base_here"]["n"] == n and all(x["all_items"]["n"] == n for x in b["arms"].values()): complete.append(b["name"]) else: bits = [f"{a} {x['all_items']['n']}/{n}" for a, x in b["arms"].items() if x["all_items"]["n"] != n] if not (b["full_base_run"] and b["base_here"]["n"] == n): bits.append(f"base pipeline {b['base_here']['n']}/{n}") partial.append(f"{b['name']} ({', '.join(bits)})") notrun = [v["name"] for v in S.values()] is_final = not partial banner = (f"") gen = re.search(r"^Generated (.*?) by ", RT, re.M) GENERATED = f"numbers computed {gen.group(1)}." if gen else "" STATUSLINE = (f"Updated {NOW.astimezone(IST).strftime('%d %b %H:%M')} IST" f"{'Final' if is_final else 'Not final'}: stopped by the project lead after GSM8K-500" f"{len(complete)} of {len(ORDER)} benchmarks fully measured") sm = [] for s, b in B.items(): base = b["base_here"]; bits = [] for a, x in b["arms"].items(): m = x["all_items"] bits.append(f"{a} {f3(x['speedup_raw'])}× (passes per block {f2(m['passes_blk'])}, expert loads per token {m['loads_tok']:.0f}, accuracy change vs base {sg(x['delta_acc_vs_base'][0])} pts)") sm.append(f"
  • {b['name']}: raw speedup over the base pipeline " + "; ".join(bits) + f"; the base pipeline has passes per block {f2(base['passes_blk'])} and expert loads per token {base['loads_tok']:.0f}.
  • ") SUMMARY = ("

    At a glance (measured, raw, all from Table 1; the host-speed drift of section 3 is not removed from the speedups):

    " "") # ---------------------------------------------------------------- Table 1 (measured) mrows = [] for s in ORDER: if s not in B: continue b = B[s]; base = b["base_here"]; n = n_exp(s); grp = [] part = "" if (b["full_base_run"] and base["n"] == n) else f" running {base['n']}/{n}" grp.append(f"base pipeline{base['n']}{part}{f1(base['acc'])}reference{f2(base['passes_blk'])}{base['loads_tok']:.0f}" f"{f2(base['drafter_fwd_tok'])}{f2(base['tok_s'])}{f1(base['ms_tok'])}{wall(b['wall_base_min'])}1.00 (reference)") for a, x in b["arms"].items(): m = x["all_items"]; d = x["delta_acc_vs_base"] pb = "" if x["paired_items"] == n else " partial base" grp.append(f"{a}{m['n']}{f1(m['acc'])}{sg(d[0])} [{sg(d[1])}, {sg(d[2])}]{f2(m['passes_blk'])}{m['loads_tok']:.0f}" f"{f2(m['drafter_fwd_tok'])}{f2(m['tok_s'])}{f1(m['ms_tok'])}{wall(x['wall_here_min'])}" f"{f3(x['speedup_raw'])}× ({x['paired_items']} paired items){pb}") for i, g in enumerate(grp): lead = f"{b['name']}" if i == 0 else "" mrows.append(f"{lead}{g}") MTABLE = "".join(mrows) # ---------------------------------------------------------------- Table 2 (base pipeline vs Phase 1) brows = [] for s in ORDER: if s in B: b = B[s]; n = n_exp(s); i, t = b["base_identical_to_phase1"] brows.append(f"{b['name']}{b['base_here']['n']}{'' if b['base_here']['n'] == n else f' of {n}'}{i}/{t}{f2(b['base_here']['tok_s'])}{f3(b['box_ratio_base'])}") else: v = S[s] brows.append(f"{v['name']} first items only{v['items']}{v['identical_to_phase1']}/{v['items']}{f2(v['base_tps_here'])}{f3(v['box_ratio'])}") BASETABLE = "".join(brows) # ---------------------------------------------------------------- Tables 3, 4 (drift) hrows, arows = [], [] for s in ORDER: if s not in B: continue for a, x in B[s]["arms"].items(): hrows.append(f"{B[s]['name']}{a}{f3(x['host_index_30b_prefill'])}{f3(x['host_index_drafter_prefill'])}" f"{f3(x['host_index_first_half'])}{f3(x['host_index_second_half'])}") arows.append(f"{B[s]['name']}{a}{f3(x['speedup_raw'])}×{f3(x['host_index_30b_prefill'])}" f"{f3(x['speedup_drift_adjusted'])}×adjusted, NOT a measurement") HTABLE, ADJTABLE = "".join(hrows), "".join(arows) # ---------------------------------------------------------------- Table 5 (extrapolated) xrows = [] for s in ORDER: if s not in B: continue b = B[s] for k, (a, x) in enumerate(b["arms"].items()): lead = f"{b['name']}" if k == 0 else "" xrows.append(f"{lead}{a}" f"{f1(b['base_phase1_box']['tok_s'])} (stock {f1(b['stock_tps_phase1_box'])}){MT}" f"{f1(x['extrap_tps_raw'])}{XT}{f2(x['extrap_x_stock_raw'])}×{XT}" f"{f1(x['extrap_tps_adjusted'])} ({f2(x['extrap_x_stock_adjusted'])}× stock){XTA}" f"{f1(x['extrap_wall_8gpu_min'])} min{XT}") XTABLE = "".join(xrows) XNOTRUN = (f"

    Not run, so nothing to extrapolate: rd1 and rd2 on {', '.join(notrun)}.

    ") # ---------------------------------------------------------------- figures FIG = [] for s in ORDER: nm = NAMES[s]; n = n_exp(s) if s not in B: FIG.append({"name": nm, "n": n, "pts": [], "live": False, "msg": "rd1 and rd2 not run (stopped after GSM8K-500)"}); continue b = B[s]; base = b["base_here"]; pts = [] pts.append({"label": "Stock 30B (Phase 2 records)", "tiny": "Stock", "shape": "diamond", "color": "--s-stock", "acc": P2[s]["stock"]["acc"], "err": None, "note": "Phase 2 records, not measured here"}) pts.append({"label": "Base pipeline (this box)", "tiny": "Base", "shape": "circle", "color": "--s-sdar", "sp": 1.0, "acc": base["acc"], "err": None, "tps": base["tok_s"], "note": f"measured here, {base['n']} items; reference = 1x"}) pts.append({"label": "CoDA-1.7B + judge (Phase 2 records)", "tiny": "CoDA", "shape": "square", "color": "--s-coda", "acc": P2[s]["F2_nopool"]["acc"], "err": None, "note": "Phase 2 records, not measured here"}) pts.append({"label": "Qwen3-0.6B + judge (Phase 2 records)", "tiny": "Qwen3", "shape": "triangle", "color": "--s-qwen", "acc": P2[s]["S1_nopool"]["acc"], "err": None, "note": "Phase 2 records, not measured here"}) for a, shape, col in (("rd1", "pent", "--s-rd1"), ("rd2", "star", "--s-rd2")): x = b["arms"][a]; m = x["all_items"]; d = x["delta_acc_vs_base"] pts.append({"label": a + (" (re-draft every pass)" if a == "rd1" else " (re-draft every 2 passes)"), "tiny": a, "shape": shape, "color": col, "sp": x["speedup_raw"], "acc": m["acc"], "err": [m["acc"] + (d[1] - d[0]), m["acc"] + (d[2] - d[0])], "tps": m["tok_s"], "note": f"raw, measured here on {x['paired_items']} paired items vs the base pipeline (host drift not removed); accuracy delta vs base {d[0]:+.1f} pts [{d[1]:+.1f}, {d[2]:+.1f}]"}) FIG.append({"name": nm, "n": n, "pts": pts, "live": True}) # ---------------------------------------------------------------- prose SEC1 = md_html(md_blocks(RS[1])).replace("(section 6)", "(Table 2)") _gf = re.search(r"`gpu_frac` ([0-9.]+)", RT) if _gf: SEC1 += (f"

    Shared host. The box is a shared, rented server: gpu_frac is {_gf.group(1)} (we rent part of the machine's GPUs; another tenant uses the rest). " "Section 3 shows what that does to the measured speed.

    ") rd = open("code/phase3/README.md").read().splitlines() i0 = next(i for i, l in enumerate(rd) if l.startswith("## Method")); i1 = next(i for i in range(i0 + 1, len(rd)) if rd[i].startswith("## ")) METHOD = md_html(md_blocks(rd[i0 + 1:i1])) DRIFT1 = pick(3, "**Evidence the host is shared:**", "This is a shared, rented server", "**How it is measured:**") DRIFT2 = pick(3, "**Reading:**") DRIFT3 = pick(4, "**How to avoid this next time:**") xs = pick(4, "Formula:") XFORMULA = xs SEC5 = md_html(md_blocks(RS[5])) TIMING = ("

    Timing in detail. Per-item seconds is set in decode_item (code/draftalign/da_decode.py): " "torch.cuda.synchronize(), then time.perf_counter(), then the whole decode, then torch.cuda.synchronize() and " "time.perf_counter() again. The timed span contains prompt prefill, every judge, drafter, re-draft and KV-flush forward, and sampling; " "it excludes tokenisation (encode_prompt), scoring, trace saving and writing the record (code/draftalign/run_da_decode.py). " "The per-forward component times (ms_by_kind, drafter_ms_by_kind, SeqCache._timed in code/draftalign/seqcache.py) also synchronize " "before and after each forward, identically in every setup. There are no busy-polling loops, CUDA-event polling or sleeps in the timed path. " "Wall in Tables 0 and 1 is the run's start-to-done time from logs/phase3/run.log, model load included.

    ") SEC7 = md_html(md_blocks(RS[7])) SEC8 = md_html(md_blocks(RS[8])) REBUILD = ("

    Rebuild this page from the report numbers:

    python logs/phase3/extrap/final_report.py\n"
               "python logs/phase3/extrap/build_final.py results/phase3/final_numbers.json results/phase3/REPORT.md logs/phase3/extrap/phase3_redraft.html
    ") FM = [ ("logs/phase3/run.log", "logs/phase3/run.log", "start / done / skip / pause lines of the whole run (UTC, time of day only)."), ("logs/phase3/decode/rd1/<benchmark>/, decode/rd2/<benchmark>/", "logs/phase3/decode/rd1", "rd1 and rd2: one JSON record per item (*.jsonl, one file per shard), .jsonl.done shard markers, .complete when every shard finished."), ("logs/phase3/decode/judge/<benchmark>/", "logs/phase3/decode/judge", "base pipeline (SDAR-1.7B drafter + trained 128M judge), full-set runs."), ("logs/phase3/decode/judge_sample/<benchmark>/", "logs/phase3/decode/judge_sample", "base pipeline on the first items only (the benchmarks the run was stopped before)."), ("logs/phase3/jobs/<setup>/<benchmark>/", "logs/phase3/jobs", "stdout of every shard process (shardK.attemptN.log)."), ("logs/phase3/setup/", "logs/phase3/setup", "setup checks: checks.json, tests.log, check_stock/, check_judge/ (identity checks against the Phase 1 records)."), ("logs/phase3/analysis/, analysis.log, analysis_snapshot.log", "logs/phase3/analysis", "output of code/phase3/analyze_p3.py (TABLE.md, metrics.json)."), ("logs/phase3/extrap/", "logs/phase3/extrap", "final_report.py (the report and final_numbers.json), build_final.py and final_template.html (this page), extrap.py, status.py, unified.py, build_artifact.py (the live page while the run was going), p2_metrics.json (Phase 2 page metrics), and the shell scripts that ordered the run."), ("logs/phase3/backup.log, snapshot.log, switch.log", "logs/phase3/backup.log", "backup uploads, the periodic snapshot loop, and the run-order switches."), ("logs/phase3/STOP", "logs/phase3/STOP", "empty marker file: the stop signal, checked by run_p3.sh before it starts the next benchmark."), ("logs/phase3/STOPPED_setup_tests.md", "logs/phase3/STOPPED_setup_tests.md", "note from the first stop, at setup, before any decoding (two CPU tests failed on a missing drafter field in their fake arguments); the run was resumed afterwards."), ("results/phase3/", "results/phase3", "REPORT.md and final_numbers.json (this page's source), TABLE.md, metrics.json, EXTRAPOLATION_PHASE1_BOX.md, RESUME.md, setup_checks.json."), ("code/phase3/", "code/phase3", "run_p3.sh (the driver), setup_p3.sh, analyze_p3.py, backup_p3.py, README.md (method), extrap/ (copies of the page and report scripts)."), ("code/draftalign/", "code/draftalign", "the decoder: run_da_decode.py (runner), da_decode.py (decode loop, timing, records), seqcache.py (per-forward timers), drafter.py."), ("weights/c1b_128M/ (Hugging Face dataset)", None, "the trained 128M judge LoRA adapter used by every setup (weights hash 35805974)."), ("ref/phase2/S0_128M_nopool_by_set/ (Hugging Face dataset)", None, "the Phase 1 box's base-pipeline per-item records, used as the reference for token identity and for the Phase 1 box tokens per second."), ] filemap = [] for disp, chk, desc in FM: if chk is not None and not os.path.exists(chk): print(f"WARNING: file map path missing: {chk}", file=sys.stderr); continue filemap.append(f"{disp}{desc}") FILEMAP = "".join(filemap) # ---------------------------------------------------------------- assemble tpl = open("logs/phase3/extrap/page_template.html").read() head = tpl[:tpl.index('
    ')] tail = tpl[tpl.index('