File size: 6,667 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Versioned H100 and SM100 kernel suite. Build with python -m kernel_bench.kernel_v07."""
import hashlib
import json
from pathlib import Path
import random
import shutil

from . import main_h100
from .build_sparse_suites import write

ROOT = Path(__file__).resolve().parent
VERSION = "0.7.0"
PACK = "v0.7-kernels"
CSA = "csa2_reindex_reuse"
MOE = "shared_mega_moe"
SIGNATURES = {
    CSA: ("reindex_decode(iq, ik, weights, blocks, lengths, kv, q, window, window_lens, sink)",
          "reuse_decode(ids, kv, q, window, window_lens, sink)",
          "layer_backward(ids, kv, q, window, window_lens, sink, dy, dkv)"),
    MOE: ("run(y, buffer, routed_l1, routed_l2, shared_l1, shared_l2)",
          "moe_backward(dy, shared, experts, weights, capacity, topk, group)"),
}
SPECS = {
    CSA: dict(title="CSA2 Reindex and Reuse decode with a shared KV gradient", group="K04",
              research_ids=["ATT-D06"], hardware="1 x NVIDIA H100 80GB",
              baseline="Triton forward; TorchInductor backward (edge/topk), eager backward (long)"),
    MOE: dict(title="Shared experts in persistent Mega MoE with distributed backward", group="K12",
              research_ids=["KER-M06"], hardware="8 x peer-connected NVIDIA B200 (SM100), EP=8",
              baseline="DeepGEMM 5081f851 native fused BF16 forward; Triton fused SwiGLU VJP + BF16 tensor-core distributed backward"),
}


def catalog():
    data = main_h100.catalog()
    new = [dict(spec, id=task, signatures=list(SIGNATURES[task]), phases=["forward", "backward"],
                qualification="reports/v07/admission.md")
           for task, spec in SPECS.items()]
    return dict(data, version=VERSION, research_entries=52, tasks=data["tasks"] + new)


def suite(smoke=False, seed=None, private=False):
    if private and seed is None:
        raise ValueError("Private split requires an independently generated seed")
    data = main_h100.suite(smoke=smoke, seed=seed, private=private)
    rng = random.Random(seed)
    for task, regimes in ((CSA, (("edge", 37), ("topk", 1051), ("long", 65539))),
                          (MOE, (("t32_s1", 32), ("t128_s1", 128), ("t512_s2", 512)))):
        for level, (regime, capacity) in enumerate(regimes[:1] if smoke else regimes):
            if seed is not None:
                # Disjoint public, calibration and private geometries even across different seeds.
                step = 2 * rng.randint(1, (8, 28, 64)[level]) + int(private)
                capacity += step
            data["cases"].append(dict(id=f"{task}_{regime}", task=task, regime=regime,
                                      capacity=capacity, **{k: SPECS[task][k] for k in ("group", "research_ids")}))
    split = "hidden" if private else "calibration" if seed is not None else "smoke" if smoke else "public"
    return dict(data, suite_id="kernel-v07-" + split, protocol_version=VERSION,
                provenance="50 frozen H100 entries plus CSA2 and EP=8 Mega MoE.",
                input_seed=137 if seed is None else seed)


def validate(data):
    if data.get("protocol_version") != VERSION:
        return
    old = [c for c in data["cases"] if c["task"] not in SPECS]
    main_h100.validate_cases(dict(data, protocol_version=main_h100.VERSION, cases=old))
    if any(c["task"] in SPECS and c["regime"] not in (
            ("edge", "topk", "long") if c["task"] == CSA else ("t32_s1", "t128_s1", "t512_s2"))
           for c in data["cases"]):
        raise ValueError("Unrecognized v0.7 workload regime")


def score_trials(rows):
    ranking = main_h100.score_trials(rows, catalog()["tasks"], VERSION)
    if ranking is not None:
        ranking["task_packs"] = ranking.pop("interfaces")
    return ranking


def build():
    data = catalog()
    write(ROOT / "kernel_catalog_v07.json", data)
    public = suite()
    for name, item in (("public", public), ("calibration", suite(seed=2026111307)), ("smoke", suite(smoke=True))):
        write(ROOT / "suites" / f"kernel_v07_{name}.json", item)
    for spec in data["tasks"]:
        task = spec["id"]
        path = ROOT / "taskpacks" / PACK / task
        if task not in SPECS:
            source = ROOT / "taskpacks" / main_h100.PACK / task
            shutil.copytree(source, path, dirs_exist_ok=True)
            original = json.loads((source / "public_cases.json").read_text())
            write(path / "public_cases.json", dict(original, protocol_version=VERSION))
            continue
        else:
            path.mkdir(exist_ok=True, parents=True)
            contract = (ROOT / "candidates" / task / "TASK.md").read_text()
            # Entrants receive the mathematical contract, separately from grader source and qualification results.
            front = contract.split("## 公开用例")[0].split("## 复现")[0]
            backward = contract.split("## Backward\n")[1].split("- 8 卡 H100")[0].split("- 正式任务要求")[0].split("在本目录测")[0]
            if task == MOE:
                front = front.replace("本题完整候选验收的默认配置为单节点 8 张可互访的 SM100 GPU", "本版本计分配置为单节点 8 张可互访的 B200 GPU")
                front = front.replace("提交可重建的源码 patch 和一个 Python 入口", "提交可重建的源码和一个 Python 入口")
                backward += "\n梯度逐元素 atol/rtol 分别为 dx (0.002,0.012),droute (0.003,0.002),权重 (0.002,0.002)。\n"
            else:
                backward += "\n前向 attention 的 atol/rtol 为 (0.002,0.012)。反向 dq/dwindow 为 (0.002,0.012),dsink 为 (0.0002,0.002),dkv 为 (0.0003,0.002)。\n"
            (path / "contracts.md").write_text(front + "\n## Backward\n" + backward)
            (path / "TASK.md").write_text("# " + spec["title"] + "\n\n" + spec["hardware"] +
                "。实现 contracts.md 中全部入口。前向和反向均需通过 eager 与更新输入的 CUDA Graph 验证。"
                "性能分别与冻结基线配对计时,两个方向等权。支持已安装的库和可重建的自定义 GPU 源码。\n")
            (path / "submission.py").write_text("\n\n".join("def " + sig + ":\n    raise NotImplementedError"
                                                          for sig in SIGNATURES[task]) + "\n")
            write(path / "task.json", dict(spec, prompt_sha256=hashlib.sha256((path/"TASK.md").read_bytes()).hexdigest(),
                                           contract_sha256=hashlib.sha256((path/"contracts.md").read_bytes()).hexdigest()))
        write(path / "public_cases.json", dict(public, cases=[c for c in public["cases"] if c["task"] == task]))


if __name__ == "__main__":
    build()