"""
06_case_study_check.py -- "each claim needs a cheap check that could prove it
wrong", applied to the AutoModel case study's own tables: do the reported
step times, tokens/s, MFU and incremental gains agree with each other? Do the
memory, KV-cache and RMSNorm-roofline numbers follow from first principles?
And what do the reported MFUs imply about the FLOPs each token costs?

[Questions this demo answers]
  1. The Moonlight-V4-16B-A3B optimization table (8 x H100, 256 x 2,048 tokens
     per step): tokens/s from step time, incremental gains, MFU ratios.    -> Part A
  2. What FLOPs per token does the reported MFU imply, and how does that
     compare with 6 x the activated parameters?                           -> Part B
  3. The memory footprint, the KV-cache table, the RMSNorm roofline, the
     MoK speed-ups, the DeepSeek-V4 activation fractions.                 -> Part C

[How to run]
      python3 06_case_study_check.py      (instant; standard library only)

[How to read the output]
  REPORTED numbers are copied from the course's NeMo AutoModel lecture
  slides (Fall 2026 Lecture 7); "check" columns are COMPUTED from other
  reported numbers or from first principles (H100: 989.4 TFLOP/s BF16 dense,
  3.35 TB/s HBM). "ok" means agreement to the precision the slide prints.
"""

import course_path  # noqa: F401
from console import banner, section, table, observations, fmt_bytes, fmt_time, pct, fmt_count
from hw_specs import H100_SXM

GBS, SEQ, GPUS = 256, 2048, 8
TOKENS = GBS * SEQ
# (change, step time s, MFU %, tokens/s (thousands), reported incremental gain %)
TABLE = [("stock Hugging Face model", 28.734, 3.85, 18.25, None),
         ("native EP8, eager attention", 19.748, 5.59, 26.55, 31.30),
         ("grouped_gemm + DeepEP", 19.853, 5.57, 26.41, -0.5),
         ("TileLang sparse attention, indexer, Sinkhorn", 14.520, 7.61, 36.11, 26.9),
         ("compiled mHC (compile_hc)", 13.721, 8.05, 38.21, 5.5),
         ("BF16 gradient reduction", 13.584, 8.13, 38.60, 1.0),
         ("BF16 mHC and LM-head projections", 13.341, 8.28, 39.30, 1.8),
         ("local batch 2 (16 accumulation steps)", 9.005, 12.268, 58.22, 32.5)]
ACTIVE, TOTAL = 3.0e9, 16.5e9           # Moonlight-V4-16B-A3B, as reported


def close(a, b, rel):
    return abs(a - b) <= rel * max(abs(a), abs(b))


def part_a():
    section("Part A: Moonlight-V4-16B-A3B on 8 x H100 -- does the table agree with itself?")
    rows, bad = [], []
    for i, (name, step, mfu, tps, gain) in enumerate(TABLE):
        tps_chk = TOKENS / step / 1e3
        mfu_chk = TABLE[0][2] * TABLE[0][1] / step
        gain_chk = None if i == 0 else 100 * (1 - step / TABLE[i - 1][1])
        ok = close(tps, tps_chk, 0.003) and close(mfu, mfu_chk, 0.01) and (gain is None or abs(gain - gain_chk) < 0.06)
        if not ok:
            bad.append(name)
        rows.append([name, "%.3f s" % step, "%.2fk" % tps, "%.2fk" % tps_chk, "%.2f%%" % mfu, "%.2f%%" % mfu_chk,
                     "-" if gain is None else "%+.1f%%" % gain, "-" if gain_chk is None else "%+.1f%%" % gain_chk,
                     "ok" if ok else "CHECK"])
    table(["change", "step", "tokens/s", "= 524,288 / step", "MFU", "= 3.85% x 28.734 / step", "gain", "= 1 - step/prev",
           ""], rows)
    total = TABLE[0][1] / TABLE[-1][1]
    return bad, total


def part_b():
    section("Part B: what the reported MFU implies about FLOPs per token")
    peak = H100_SXM.flops("bf16")
    name, step, mfu, tps, _ = TABLE[0]
    flops_tok = mfu / 100 * GPUS * peak / (tps * 1e3)
    implied_n = flops_tok / 6
    rows = [["FLOPs per token implied by MFU x 8 x peak / tokens/s", "%.3g" % flops_tok],
            ["... divided by 6 (the 6N convention)", fmt_count(implied_n)],
            ["reported activated parameters", fmt_count(ACTIVE)],
            ["6 x activated x tokens/s / (8 x peak) = MFU if N = 3.0 B", pct(6 * ACTIVE * tps * 1e3 / (GPUS * peak))]]
    table(["quantity", "value"], rows)
    # Kimi K3: 839.6 tokens/s/GPU at 21.1% MFU of a 2.5 PFLOP/s GB200 peak
    k3 = 0.211 * 2.5e15 / 839.6
    print("  Kimi K3 (256 GB200, reported 839.6 tokens/s/GPU at 21.1%% MFU, 2.5 PFLOP/s peak): %.3g FLOPs per "
          "token, i.e. %s '6N' parameters per token" % (k3, fmt_count(k3 / 6)))
    return flops_tok, implied_n, k3


def part_c():
    section("Part C: memory, KV cache, the RMSNorm roofline, MoK, DeepSeek-V4 sparsity")
    rows = []
    state = TOTAL * (2 + 2 + 4)
    rows.append(["model states 16.5 B x (2 + 2 + 4) B", "132 GB", fmt_bytes(state), "ok" if close(state, 132e9, 0.005) else "CHECK"])
    rows.append(["per GPU with FSDP over 8", "16.5 GB", fmt_bytes(state / 8), "ok" if close(state / 8, 16.5e9, 0.005) else "CHECK"])
    kv8k = 31.1e3 * 8192
    rows.append(["KV cache at 8K: 31.1 KB/token x 8,192", "243 MiB", fmt_bytes(kv8k, binary=True),
                 "ok" if close(kv8k / 2 ** 20, 243, 0.01) else "CHECK"])
    kv1m = 31.1e3 * 2 ** 20
    rows.append(["KV cache at 1M: 31.1 KB/token x 1,048,576", "30.4 GiB", fmt_bytes(kv1m, binary=True),
                 "ok" if close(kv1m / 2 ** 30, 30.4, 0.01) else "CHECK"])
    rms_bytes = 2 * 8192 * 2048 * 2
    roof = rms_bytes / H100_SXM.hbm_bw
    rows.append(["RMSNorm roofline: read + write 8,192 x 2,048 bf16 at 3.35 TB/s", "0.0200 ms", fmt_time(roof),
                 "ok" if close(roof, 20.0e-6, 0.01) else "CHECK"])
    for label, t, rep in (("KF Triton", 23.8e-6, 84), ("TE 2.11", 25.6e-6, 78), ("torch", 27.1e-6, 74),
                          ("shipped torch_fp32", 147.3e-6, 14)):
        rows.append(["  %s %s -> share of the roofline" % (label, fmt_time(t)), "%d%%" % rep, pct(roof / t),
                     "ok" if abs(100 * roof / t - rep) < 1 else "CHECK"])
    for label, a, b, rep in (("MoK BF16 vs HybridEP BF16 (DSv4-Flash, 64 GB200)", 9.1640, 8.0644, 1.136),
                             ("MoK MXFP8 vs HybridEP BF16", 9.1640, 7.4245, 1.234),
                             ("MoK MXFP8 vs MoK BF16", 8.0644, 7.4245, 1.086)):
        rows.append([label, "%.3fx" % rep, "%.3fx" % (a / b), "ok" if abs(a / b - rep) < 0.0015 else "CHECK"])
    for label, act, tot, rep in (("DeepSeek-V4-Pro activated fraction", 49.8, 1573, "3.1% (of 1.6 T)"),
                                 ("DeepSeek-V4-Flash activated fraction", 13.8, 284.3, None),
                                 ("Moonlight-V4-16B-A3B activated fraction", 3.0, 16.5, None)):
        rows.append([label, rep or "-", "%s (%s of 1.6 T)" % (pct(act / tot), pct(act / 1600)) if rep else pct(act / tot),
                     "ok" if rep is None or abs(100 * act / 1600 - 3.1) < 0.05 else "CHECK"])
    table(["claim", "reported", "check", ""], rows)
    return rows


def main():
    banner("06 checking the case study: do the reported numbers agree with each other?")
    bad, total = part_a()
    flops_tok, implied_n, k3 = part_b()
    rows = part_c()
    n_bad_c = sum(1 for r in rows if r[-1] == "CHECK")
    peak = H100_SXM.flops("bf16")
    observations([
        "The optimization table is internally consistent: every row's tokens/s equals 524,288 tokens / step "
        "time, every MFU scales as 1 / step time from the baseline, and every 'incremental gain' is 1 - step / "
        "previous step, to the printed precision (%s). End to end: %.2fx faster, MFU 3.85%% -> 12.27%%."
        % ("all rows" if not bad else "except: " + ", ".join(bad), total),
        "The two biggest wins are not kernels: native expert parallelism (%+.1f%%) and a larger local batch "
        "(%+.1f%%). The biggest kernel change, the TileLang sparse-attention kernels, comes third (%+.1f%%); "
        "fusion (compiled mHC, %+.1f%%) and BF16 gradient reduction (%+.1f%%) are small. One change made things "
        "slightly worse (grouped_gemm + DeepEP, %+.1f%% at this micro-batch) and was still reported -- an "
        "honest table records regressions too."
        % (TABLE[1][4], TABLE[7][4], TABLE[3][4], TABLE[4][4], TABLE[5][4], TABLE[2][4]),
        "The reported MFU implies %.3g FLOPs per token, i.e. %s '6N' parameters, against the 3.0 B activated "
        "parameters reported (6 x 3.0 B would give %s MFU). MFU definitions differ (which parameters count, "
        "whether attention FLOPs are added): a %s disagreement like this is a reason to ask for the definition, "
        "not to distrust the table."
        % (flops_tok, fmt_count(implied_n), pct(6 * ACTIVE * 18250 / (GPUS * peak)), pct(1 - implied_n / ACTIVE)),
        "The first-principles checks hold (%s): 16.5 B x 8 B = 132 GB of model states (16.5 GB per GPU over 8); "
        "31.1 KB/token x 8K = 243 MiB of KV; RMSNorm at 8K tokens reads and writes 67 MB, a 20.0 us roofline, "
        "so the factory kernel's 23.8 us is 84%% of it and the shipped fp32 kernel 14%%; the MoK speed-ups are "
        "the step-time ratios. Kimi K3's reported MFU implies %.3g FLOPs per token (%s '6N' parameters)."
        % ("%d of %d rows" % (len(rows) - n_bad_c, len(rows)), k3, fmt_count(k3 / 6)),
    ])


if __name__ == "__main__":
    main()
