File size: 10,166 Bytes
c921540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env python3
"""Efficiency table per arm, from run manifests only; plus a labelled compute ESTIMATE for the budget decision.



  table     per arm: training wall-clock, GPU-hours, tokens trained on, retention, weight-file hash (all from the

            arm's training-run manifest), and Tier-1 tokens generated per resolved task (from tier1_grade grades.jsonl).

  estimate  planning estimate of Tier-1 / Tier-2 H200 hours. NOT a measurement; every input is printed.



TRAINING MANIFEST CONTRACT (the trainer must write these; looked up by dotted path, first alias that exists wins):

  wall_clock_s        train.wall_clock_s | wall_clock_s | train_seconds

  n_gpus              train.n_gpus | n_gpus

  tokens_trained_on   train.tokens_trained_on | tokens_trained_on   (sum over steps of tokens with w > 0)

  retention           weights.retention | retention                 (tokens with w > 0 / tokens in C)

  weight_file_sha256  weights.sha256 | weight_file_sha256           (charter rule 3: baseline hash logged next to STAR's)

  scoring_wall_clock_s scoring.wall_clock_s | scoring_wall_clock_s

A key that is absent prints MISSING; GPU-hours = wall_clock_s / 3600 * n_gpus only when BOTH exist. Nothing is assumed or

filled (n_gpus is not defaulted to 1). Every cell carries the path of the manifest/log it came from.

"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import _common as C  # noqa: E402

ALIASES = {
    "wall_clock_s": ("train.wall_clock_s", "wall_clock_s", "train_seconds"),
    "n_gpus": ("train.n_gpus", "n_gpus"),
    "tokens_trained_on": ("train.tokens_trained_on", "tokens_trained_on"),
    "retention": ("weights.retention", "retention"),
    "weight_file_sha256": ("weights.sha256", "weight_file_sha256"),
    "scoring_wall_clock_s": ("scoring.wall_clock_s", "scoring_wall_clock_s"),
}


def dig(j: dict, dotted: str):
    cur = j
    for k in dotted.split("."):
        if not isinstance(cur, dict) or k not in cur:
            return None
        cur = cur[k]
    return cur


def lookup(j: dict, key: str):
    for al in ALIASES[key]:
        v = dig(j, al)
        if v is not None:
            return v
    return None


def cell(v, f="{}"):
    return "MISSING" if v is None else f.format(v)


def cmd_table(a) -> int:
    grades = [json.loads(l) for l in Path(a.grades).read_text(encoding="utf-8").splitlines() if l.strip()] if a.grades else []
    manifests = dict(x.split("=", 1) for x in a.arm_manifest)
    out_rows, lines = {}, ["arm | train wall-clock (s) | GPU-h | tokens trained on | retention | weight sha256 | scoring (s) | "
                           "T1 tokens/resolved (pooled; per-seed) | resolved/graded | source"]
    for arm in a.arms:
        mp = manifests.get(arm)
        j = json.loads(Path(mp).read_text(encoding="utf-8")) if mp and Path(mp).exists() else {}
        row = {"arm": arm, "manifest": mp if j else None}
        for k in ALIASES:
            row[k] = lookup(j, k)
        row["gpu_hours"] = (row["wall_clock_s"] / 3600 * row["n_gpus"]) if row["wall_clock_s"] is not None and row["n_gpus"] is not None else None
        rs = [g for g in grades if g["arm"] == arm and g["status"] in ("resolved", "unresolved")]
        per = {}
        for s in sorted({g["seed"] for g in rs}):
            r = [g for g in rs if g["seed"] == s]
            n_res = sum(g["status"] == "resolved" for g in r)
            tg = sum(g.get("tokens_generated") or 0 for g in r)
            per[s] = {"graded": len(r), "resolved": n_res, "tokens_generated": tg, "tokens_per_resolved": (tg / n_res) if n_res else None}
        missing_seeds = sorted({g["seed"] for g in grades if g["arm"] == arm} - set(per))     # seed rows exist but nothing graded: MISSING (rule 9)
        tg_all = sum(p["tokens_generated"] for p in per.values())
        res_all = sum(p["resolved"] for p in per.values())
        row |= {"tier1_per_seed": per, "tier1_tokens_per_resolved_pooled": (tg_all / res_all) if res_all else None,
                "tier1_seeds_missing": missing_seeds, "tier1_resolved": res_all, "tier1_graded": sum(p["graded"] for p in per.values()), "tier1_source": a.grades}
        out_rows[arm] = row
        pers = ", ".join([f"{s}:{cell(p['tokens_per_resolved'], '{:.0f}') if p['tokens_per_resolved'] is not None else 'n/a(0 resolved)'}" for s, p in per.items()]
                         + [f"{s}:MISSING (no graded task)" for s in missing_seeds]) or "MISSING"
        pooled = row["tier1_tokens_per_resolved_pooled"]
        lines.append(f"{arm} | {cell(row['wall_clock_s'])} | {cell(row['gpu_hours'], '{:.3f}')} | {cell(row['tokens_trained_on'])} | "
                     f"{cell(row['retention'], '{:.4f}')} | {cell(row['weight_file_sha256'])} | {cell(row['scoring_wall_clock_s'])} | "
                     f"{'n/a(0 resolved)' if pooled is None and per else cell(pooled, '{:.0f}')}; {pers} | "
                     f"{row['tier1_resolved']}/{row['tier1_graded']} | {mp or 'NO MANIFEST'} ; {a.grades or 'NO GRADES'}")
    chroot = C.uses_chroot(a.rollout_root)
    lines = [f"runner: {C.RUNNER_NAME}"] + lines + C.tier1_footer(chroot)[1:]
    Path(a.out_dir).mkdir(parents=True, exist_ok=True)
    C.write_json_atomic(Path(a.out_dir) / "efficiency_table.json", {"arms": out_rows, "contract": __doc__, **C.tier1_meta(chroot)})
    (Path(a.out_dir) / "efficiency_table.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
    print("\n".join(lines))
    return 0


def est_tier1(turns, f_trunc, gen_per_turn, decode_tps, lora, util, n_roll, prefill_16k_s=0.655, prefill_inc_s=0.06):
    gpu_s = lora * (turns * f_trunc * prefill_16k_s + turns * (1 - f_trunc) * prefill_inc_s + turns * gen_per_turn / decode_tps)
    return {"gpu_s_per_rollout": gpu_s, "gpu_busy_h": gpu_s * n_roll / 3600, "billed_h": gpu_s * n_roll / 3600 / util}


def cmd_estimate(a) -> int:
    scen = {  # (turns, f_trunc, gen/turn, decode tok/s aggregate, lora multiplier, utilisation)
        "low": (45, 0.4, 150, 3000, 1.1, 0.8),
        "central": (70, 0.6, 200, 2000, 1.2, 0.7),
        "high": (100, 0.8, 250, 1000, 1.5, 0.6),
    }
    res = {"ESTIMATE_NOT_A_MEASUREMENT": True,
           "measured_anchor": {"what": "HF bf16 sdpa forward over one 16,384-token trajectory on an H200 = 0.655 s (mean)",
                               "source": str(C.RESULTS_DIR / "scoring_summary.txt"), "per_16k_prefill_s": 0.655},
           "assumptions": {k: dict(zip(("turns_per_rollout", "frac_turns_with_prompt_over_16384", "generated_tokens_per_turn",
                                        "aggregate_decode_tok_per_s", "lora_overhead_x", "gpu_utilisation"), v)) for k, v in scen.items()},
           "model": "per rollout GPU-s = lora * (turns*f*0.655 + turns*(1-f)*0.06 + turns*gen/decode_tps); a prompt over 16,384 "
                    "tokens is head+tail truncated every turn, so the shifted tail cannot be prefix-cached and the whole window is re-prefilled",
           "scenarios": {}}
    if a.custom:  # --custom turns f_trunc gen decode_tps lora util : one extra labelled scenario, e.g. a lower turn cap
        t, f, g, d, l, u = [float(x) for x in a.custom]
        scen["custom"] = (t, f, int(g), d, l, u)
        res["assumptions"]["custom"] = dict(zip(("turns_per_rollout", "frac_turns_with_prompt_over_16384", "generated_tokens_per_turn",
                                                 "aggregate_decode_tok_per_s", "lora_overhead_x", "gpu_utilisation"), scen["custom"]))
    for name, (t, f, g, d, l, u) in scen.items():
        r1 = est_tier1(t, f, g, d, l, u, a.arms * a.tasks)
        res["scenarios"][name] = {"tier1_one_seed_all_arms": r1,
                                  "tier1_three_seeds_all_arms": {k: v * 3 if k != "gpu_s_per_rollout" else v for k, v in r1.items()}}
    # tier 2 (central-ish, one scenario): HumanEvalFix + NLL + next-action, shared vLLM server
    hef = (164 * 300 / 1000 + 5) / 3600 * (a.arms + 1)                     # decode ~300 tok x 164 at ~1000 tok/s + 5 s overhead, per model incl. base
    nll = (100 * 0.655 + a.arms * 100 * 0.655 * 1.3) / 3600 + 0.05          # base + adapters (unmerged x1.3) + model load
    nxt = a.spans * (a.arms + 1) * (0.655 + 150 / 100) / 3600               # prefill + ~150 decode tokens at ~100 tok/s single stream equivalent
    res["tier2"] = {"humanevalfix_h": hef, "nll_h": nll, "next_action_h": nxt, "assumed_kept_spans": a.spans,
                    "server_startup_h": 0.1, "total_busy_h": hef + nll + nxt + 0.1,
                    "note": "kept-span count is an extrapolation (held-out v3 counts: ~1.7 T4-T6 events/trajectory, ~58% of spans survive 16,384); the detector has not been run on the 100 ids"}
    C.write_json_atomic(a.out, res) if a.out else None
    print(json.dumps(res, indent=1))
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    sub = ap.add_subparsers(dest="cmd", required=True)
    t = sub.add_parser("table")
    t.add_argument("--arms", nargs="+", default=list(C.ARMS))
    t.add_argument("--arm-manifest", action="append", default=[], metavar="ARM=PATH")
    t.add_argument("--grades", help="grades.jsonl from tier1_grade.py collect")
    t.add_argument("--rollout-root", default=str(C.RESULTS_DIR / "tier1"), help="only used to detect whether the chroot runner produced the numbers (footer hashes)")
    t.add_argument("--out-dir", default=str(C.RESULTS_DIR / "efficiency"))
    t.set_defaults(fn=cmd_table)
    e = sub.add_parser("estimate")
    e.add_argument("--arms", type=int, default=6)
    e.add_argument("--tasks", type=int, default=50)
    e.add_argument("--spans", type=int, default=130)
    e.add_argument("--custom", nargs=6, metavar=("TURNS", "F_TRUNC", "GEN", "DECODE_TPS", "LORA", "UTIL"))
    e.add_argument("--out")
    e.set_defaults(fn=cmd_estimate)
    a = ap.parse_args()
    return a.fn(a)


if __name__ == "__main__":
    raise SystemExit(main())