File size: 10,753 Bytes
0da1f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/env python3
"""Build the REPORT.md tables from this run's results.json files.

Reads the original Ray run plus the serial reruns, preferring a rerun when one
exists for a scenario index. Every harness family writes a different schema, so
each extractor below is keyed off what the harness actually emits rather than a
shared shape.

    python3 make_tables.py            # writes tables/*.md
"""

from __future__ import annotations

import json
import os
import glob
import statistics

HERE = os.path.dirname(os.path.abspath(__file__))
ORIG = os.path.join(HERE, "validate", "20260923-065922")
RERUN = os.path.join(HERE, "rerun")
OUT = os.path.join(HERE, "tables")

# Paper Table 7/8 "Speedup" column, arXiv 2605.23215 (H100 SXM5, locked clocks).
# Keyed by our scenario index so the mapping is explicit and auditable.
PAPER = {
    0: ("Llama-3.1", 1.04), 1: ("Mixtral", 0.97), 3: ("BitNet 1.58b", 1.12),
    4: ("GPT-OSS (MXFP4)", 1.02), 5: ("EAGLE-3", 0.98), 6: ("Gemma-4", 1.00),
    7: ("Mamba", 1.05), 8: ("Mamba2", 0.97), 9: ("RWKV-7", 1.18),
    10: ("GLA", 1.85), 11: ("RetNet", 1.86), 12: ("Qwen-3-Next", 1.24),
    13: ("Kimi-Linear", 1.20), 14: ("TTT-E2E", 1.10), 15: ("Jamba", 1.02),
    16: ("FLUX.1-Dev", 1.01), 17: ("HunyuanVideo-1.5", 0.97), 18: ("SDXL", 1.17),
    19: ("SAM3.1", 1.05), 20: ("Whisper", 0.95), 21: ("CosyVoice3", 2.13),
    22: ("Qwen2-VL", 0.91), 23: ("Qwen3-VL", 1.39), 25: ("Qwen-2.5-Omni", 2.02),
    26: ("SigLIP-2", 0.93), 27: ("DINOv3", 0.99), 28: ("SwinV2", 1.17),
    29: ("MobileNetV4", 1.15), 30: ("ConvNeXtV2", 0.99), 31: ("EfficientNetV2", 1.05),
    32: ("YOLOv10", 1.06), 33: ("RTDetrV2", 1.08), 34: ("3DGS", 0.99),
    35: ("InstantNGP", 0.97), 36: ("PointTransformerV3", 1.00), 37: ("OpenFold3", 1.03),
    38: ("Pi0", 3.48), 39: ("DP3", 1.42), 40: ("DLRMv2", 1.06), 41: ("LightGCN", 1.03),
    42: ("BGE-M3", 1.06), 43: ("ColBERTv2", 3.08), 44: ("LLaDA", 1.07),
    45: ("Oasis", 1.29), 46: ("V-JEPA 2", 1.01),
}
# 24 (Qwen3-VL-235B-FP8) has no distinct paper row; the paper's single Qwen3-VL
# row is mapped to 23 (the 8B checkpoint).


def load_tasks() -> dict:
    tasks = {}
    with open(os.path.join(ORIG, "run.jsonl")) as fh:
        for line in fh:
            rec = json.loads(line)
            if rec.get("event") == "task_finished":
                tasks[rec["result"]["index"]] = rec["result"]
    return tasks


def rerun_paths() -> dict:
    out = {}
    for path in glob.glob(os.path.join(RERUN, "*", "results.json")):
        out[int(os.path.basename(os.path.dirname(path))[:3])] = path
    return out


def walk(obj, path=""):
    if isinstance(obj, dict):
        for key, val in obj.items():
            yield from walk(val, f"{path}.{key}")
    elif isinstance(obj, list):
        for i, val in enumerate(obj):
            yield from walk(val, f"{path}[{i}]")
    else:
        yield path, obj


THROUGHPUT_KEYS = (
    "images_per_second", "videos_per_second", "utterances_per_second",
    "throughput_req_s", "points_per_second", "samples_per_second",
)


def throughput_ratios(data: dict) -> list[tuple[str, float]]:
    """(scenario, fastkernels/reference) for every throughput scenario."""
    rows = []
    for key in ("scenarios", "throughput_scenarios"):
        for entry in data.get(key) or []:
            if not isinstance(entry, dict):
                continue
            for field in ("speedup", "speedup_vs_sglang"):
                if isinstance(entry.get(field), (int, float)):
                    rows.append((str(entry.get("scenario")), float(entry[field])))
                    break
    if rows:
        return rows
    ours = data.get("fastkernels") or data.get("ours")
    ref = data.get("reference") or data.get("vllm_omni") or data.get("timm")
    if isinstance(ours, dict) and isinstance(ref, dict):
        ours_t = {t["name"]: t for t in ours.get("throughput", []) if isinstance(t, dict)}
        ref_t = {t["name"]: t for t in ref.get("throughput", []) if isinstance(t, dict)}
        for name, o in ours_t.items():
            r = ref_t.get(name)
            if not r:
                continue
            for field in THROUGHPUT_KEYS:
                if o.get(field) and r.get(field):
                    rows.append((name, o[field] / r[field]))
                    break
    return rows


def latency_speedups(data: dict) -> list[tuple[str, float]]:
    rows = []
    for entry in data.get("latency_scenarios") or []:
        if not isinstance(entry, dict):
            continue
        for field in ("speedup", "speedup_vs_sglang"):
            if isinstance(entry.get(field), (int, float)):
                rows.append((str(entry.get("scenario")), float(entry[field])))
                break
    return rows


VERDICT_LEAVES = ("overall_pass", "pass", "passed", "correctness_pass")


def verdicts(data: dict) -> list[tuple[str, bool]]:
    out = []
    for path, val in walk(data):
        leaf = path.split(".")[-1].split("[")[0]
        if isinstance(val, bool) and leaf in VERDICT_LEAVES:
            out.append((path, val))
    return out


def similarity_metrics(data: dict) -> list[tuple[str, float]]:
    """Alignment-ish scalars, so the report can show what was actually checked."""
    out = []
    for path, val in walk(data):
        leaf = path.split(".")[-1].split("[")[0]
        if not isinstance(val, (int, float)) or isinstance(val, bool):
            continue
        if any(tag in leaf for tag in ("cosine", "cos", "match_rate", "psnr", "exact_match")):
            out.append((path.lstrip("."), float(val)))
    return out


def fmt(x, nd=3):
    return "—" if x is None else f"{x:.{nd}f}"


def main() -> None:
    os.makedirs(OUT, exist_ok=True)
    tasks = load_tasks()
    reruns = rerun_paths()

    records = {}
    for idx in sorted(tasks):
        task = tasks[idx]
        path = reruns.get(idx) or os.path.join(
            ORIG, os.path.basename(task["run_dir"]), "results.json"
        )
        if not os.path.isfile(path):
            records[idx] = {"task": task, "data": None, "source": "missing"}
            continue
        with open(path) as fh:
            data = json.load(fh)
        records[idx] = {
            "task": task,
            "data": data,
            "source": "rerun" if idx in reruns else "orig",
        }

    # ---- coverage ----
    lines = ["| # | model | harness | tp | source | results.json | internal verdict |",
             "| --- | --- | --- | --- | --- | --- | --- |"]
    for idx, rec in records.items():
        task, data = rec["task"], rec["data"]
        if data is None:
            verdict = "—"
            have = "no"
        else:
            have = "yes"
            vs = verdicts(data)
            bad = [p for p, v in vs if v is False]
            verdict = "**FAIL** " + ", ".join(b.lstrip(".") for b in bad) if bad else (
                "pass" if vs else "no boolean field")
        lines.append(
            f"| {idx} | `{task['name']}` | `{task['harness']}` | {task['tp']} | "
            f"{rec['source']} | {have} | {verdict} |"
        )
    open(os.path.join(OUT, "coverage.md"), "w").write("\n".join(lines) + "\n")

    # ---- throughput ----
    lines = ["| # | model | scenario | fastkernels / reference |",
             "| --- | --- | --- | --- |"]
    means = {}
    for idx, rec in records.items():
        if rec["data"] is None:
            continue
        rows = throughput_ratios(rec["data"])
        if rows:
            means[idx] = statistics.fmean(r for _, r in rows)
        for scen, ratio in rows:
            lines.append(f"| {idx} | `{rec['task']['name']}` | {scen} | {ratio:.3f}x |")
    open(os.path.join(OUT, "throughput.md"), "w").write("\n".join(lines) + "\n")

    # ---- latency ----
    lines = ["| # | model | scenario | speedup |", "| --- | --- | --- | --- |"]
    for idx, rec in records.items():
        if rec["data"] is None:
            continue
        for scen, ratio in latency_speedups(rec["data"]):
            lines.append(f"| {idx} | `{rec['task']['name']}` | {scen} | {ratio:.3f}x |")
    open(os.path.join(OUT, "latency.md"), "w").write("\n".join(lines) + "\n")

    # ---- alignment ----
    lines = ["| # | model | metric | value |", "| --- | --- | --- | --- |"]
    for idx, rec in records.items():
        if rec["data"] is None:
            continue
        for path, val in similarity_metrics(rec["data"]):
            if "latencies" in path:
                continue
            lines.append(f"| {idx} | `{rec['task']['name']}` | `{path}` | {val:.6f} |")
    open(os.path.join(OUT, "alignment.md"), "w").write("\n".join(lines) + "\n")

    # ---- paper comparison ----
    lines = ["| # | architecture | paper (H100, locked) | this run (H200, unlocked) | delta |",
             "| --- | --- | --- | --- | --- |"]
    deltas = []
    for idx, (arch, paper_val) in sorted(PAPER.items()):
        ours = means.get(idx)
        if ours is None:
            lines.append(f"| {idx} | {arch} | {paper_val:.2f}x | — | — |")
            continue
        delta = (ours - paper_val) / paper_val * 100.0
        deltas.append((arch, delta, paper_val, ours))
        lines.append(
            f"| {idx} | {arch} | {paper_val:.2f}x | {ours:.3f}x | {delta:+.1f}% |"
        )
    absd = [abs(d) for _, d, _, _ in deltas]
    flipped = [(a, p, o) for a, _, p, o in deltas if (p - 1) * (o - 1) < 0]
    lines += [
        "",
        f"Comparable architectures: **{len(deltas)}**. "
        f"Exact matches: **{sum(1 for x in absd if x == 0)}**. "
        f"Median \\|delta\\|: **{statistics.median(absd):.1f}%**. "
        f"Max \\|delta\\|: **{max(absd):.1f}%**.",
        "",
        f"Within 2%: {sum(1 for x in absd if x <= 2)}/{len(absd)} &middot; "
        f"within 5%: {sum(1 for x in absd if x <= 5)}/{len(absd)} &middot; "
        f"within 10%: {sum(1 for x in absd if x <= 10)}/{len(absd)} &middot; "
        f"within 20%: {sum(1 for x in absd if x <= 20)}/{len(absd)}",
        "",
        f"Direction reversals (one side above 1x, the other below): **{len(flipped)}**",
        "",
        "| architecture | paper | this run |",
        "| --- | --- | --- |",
    ]
    for arch, paper_val, ours in flipped:
        lines.append(f"| {arch} | {paper_val:.2f}x | {ours:.3f}x |")
    open(os.path.join(OUT, "paper_comparison.md"), "w").write("\n".join(lines) + "\n")

    print(f"wrote {OUT}/coverage.md, throughput.md, latency.md, alignment.md, paper_comparison.md")
    print(f"  scenarios with results: {sum(1 for r in records.values() if r['data'])}/{len(records)}")
    print(f"  comparable vs paper   : {len(deltas)}")
    print(f"  median |delta|        : {statistics.median(absd):.1f}%")
    print(f"  direction reversals   : {len(flipped)}")


if __name__ == "__main__":
    main()