KBench / tools /factory /make_catalog.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 2)
2e4c7fe verified
Raw
History Blame Contribute Delete
12.6 kB
"""Generate CATALOG.json + README.md for the kernels/ suite.
The task directories stay FLAT on purpose: _factory/build.py, _factory/validate.sh and
_factory/audit_sizes.py all address tasks as LANE/<name>, and harbor is pointed at a task path
directly. Nesting them would break the build chain for no functional gain. Navigability comes from
this catalog instead.
Everything here is derived from what is already on disk -- task.toml keywords, the grader's metric and
GRADER_SHAPES, and canonical_work -- so it cannot drift from the tasks themselves. Re-run after adding
tasks: python3 _factory/make_catalog.py
"""
import ast
import json
import pathlib
import re
LANE = pathlib.Path(__file__).resolve().parent.parent
H200_TFLOPS, H200_GBPS, LINK_GBPS = 700.0, 4800.0, 50.0
# Ordered: first match wins. Keyed on task.toml keywords, falling back to the name.
FAMILIES = [
# Includes the E2 "enabling primitives": persistent-kernel building blocks that are part of the
# megakernel family but do not carry the megakernel- prefix.
("Megakernel — whole-model fusion & primitives", lambda n, k: n.startswith("megakernel-") or
"megakernel" in k or "persistent-kernel" in k or re.match(
r"(gridwide-barrier|instruction-interpreter|async-weight-prefetch|warp-specialized|"
r"persistent-|cross-layer-fusion)", n)),
("Distributed — multi-GPU collectives", lambda n, k: n.startswith("dist-")),
# NOTE: match these on the NAME, before the model-specific families. Keyword matching on
# "wan"/"hunyuanvideo" is far too greedy -- VAE and sparse-attention tasks tag those keywords
# merely because they use Wan/HunyuanVideo shapes, and get mis-filed into the DiT families.
("Video — 3D causal VAE / tokenizer", lambda n, k: re.match(
r"(causal-conv3d|conv3d-|groupnorm3d|temporal-(up|down)sample|spatial-upsample|trilinear|"
r"wavelet|video-latent|latent-normalize|depthwise-separable-conv3d|vae-)", n)),
("Video — sparse / efficient attention", lambda n, k: re.match(
r"(sliding-tile|sta-|radial-|svg-|block-sparse-video|video-attn|frame-anchor|"
r"temporal-strided|spatial-window|hierarchical-coarse|causal-video|sparse-attn-mask|"
r"latent-patchify|tile-permute|adaptive-sparsity|compressed-kv-video|rolling-window-video|"
r"video-cfg-zero-star|"
r"attn-density|sparse-block-worklist|pyramid-kv)", n)),
("Image generation — FLUX / SD3 MMDiT", lambda n, k: re.match(r"(flux-|sd3-)", n)),
("Video — CogVideoX / Mochi / LTX", lambda n, k: re.match(r"(cogvideox-|mochi-|ltx-)", n)),
("Video — Wan DiT", lambda n, k: n.startswith("wan-")),
("Video — HunyuanVideo MMDiT", lambda n, k: n.startswith("hunyuan-")),
("Diffusion — sampling, scheduling, caching", lambda n, k: "diffusion" in k and "video-diffusion" not in k
or re.match(r"(flow-match|dpmsolver|ddim|teacache|feature-cache|cache-hit|residual-diff|"
r"cfg-|noise-add|latent-blend|latent-interp|scheduler-|step-distill|sigma-)", n)),
("Multimodal & audio", lambda n, k: re.match(
r"(vision-patch|clip-|mrope|image-token|any-res|mm-embed|audio-|whisper|siglip|dinov2|vit-|tts-|"
r"qwen-vl|conformer-|hifigan-|istft-|snake-antialias|mel-)", n)),
# Each family carries a NAME fallback as well as keywords: several tasks predate the keyword
# vocabulary and would otherwise land in "Other".
("Linear attention & SSM", lambda n, k: "linear-attention" in k or "delta-rule" in k or "ssm" in k
or "mamba" in k or re.match(
r"(mamba|titans|ttt-|rwkv|gla-|gsa-|retention|comba|kda-|delta|hgrn|based-|lightning|"
r"log-linear|mesa|path-attn|simple-gla|hybrid-layer)", n)),
("MoE — routing & grouped GEMM", lambda n, k: "moe" in k or n.startswith("moe-")),
("Quantization & low-precision GEMM", lambda n, k: "quantization" in k or "low-precision" in k
or "gemm" in k or "fp8" in k),
("Training, optimizer & RL", lambda n, k: "training" in k or "optimizer" in k or "rl" in k
or re.match(r"(dpo-|grpo-|gae-|ppo-|muon|sequence-packing|gradient-accum|lora|dora|qlora|"
r"quantized-optimizer|fused-adamw|grad-global|distill-kl|entropy-bonus|"
r"adafactor|mtp-multi-head|activation-recompute|flow-match-loss)", n)),
("Sampling & speculative decoding", lambda n, k: "sampling" in k or "speculative" in k
or "decoding" in k or re.match(
r"(draft-tree|ngram|spec-decode|beam-search|min-p|repetition|guided-decoding|fused-topk|"
r"logits-gather)", n)),
("KV cache & paging", lambda n, k: "kv-cache" in k or "paged" in k or re.match(
r"(radix-prefix|sequence-unpad|paged-kv|kv-cache|int4-kv|prefix-cache|kv-layout|kv-block|"
r"kv-repage|grammar-jump|multi-lora|penalty-count|speculative-draft)", n)),
("Normalization, RoPE & elementwise fusion", lambda n, k: re.match(
r"(fused-residual-rmsnorm|fused-rmsnorm|rmsnorm-|layernorm-|rope-|yarn-|fused-qk-norm|"
r"dyt-|layerscale-|sandwich-norm|"
r"swiglu|attention-qk-norm|embedding-backward)", n)),
("Attention — text LLM", lambda n, k: "attention" in k or re.match(
r"(dsa-|moba|nsa-|mla-|chunked-prefill|prefix-lm|cascade|streaming|softcap|alibi|"
r"deepseek-|qwen3-next-gated|altup-|laurel-|"
r"diff-attention|flex-|forgetting|qk-clip|cross-attention|varlen|gqa-|attention-)", n)),
("Other", lambda n, k: True),
]
def parse_toml(p):
txt = p.read_text()
def grab(field, default=""):
m = re.search(rf'^{field}\s*=\s*"(.*)"\s*$', txt, re.M)
return m.group(1) if m else default
kws = []
m = re.search(r"^keywords\s*=\s*\[(.*?)\]", txt, re.M | re.S)
if m:
kws = [x.strip().strip('"') for x in m.group(1).split(",") if x.strip()]
g = re.search(r"^gpus\s*=\s*(\d+)", txt, re.M)
return grab("name", p.parent.name), grab("description"), kws, int(g.group(1)) if g else 1
def roofline(task_dir, name):
"""Replicates audit_sizes.py so the catalog cannot disagree with the size audit."""
v = task_dir / "tests" / "verify_env.py"
if not v.exists():
return None, None
src = v.read_text()
if "canonical_work" not in src:
return "tokens/s", None # megakernel family: sized by MegaSpec.floor_us()
ns, shapes = {}, None
try:
for node in ast.parse(src).body:
if isinstance(node, (ast.FunctionDef, ast.Assign)):
try:
exec(compile(ast.Module([node], []), "<c>", "exec"), ns)
except Exception:
pass
if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "") == "GRADER_SHAPES":
shapes = ast.literal_eval(node.value)
metric = "GB/s" if "GB/s" in src else "TFLOP/s"
big = max(ns["canonical_work"](*s) for s in shapes)
if metric == "TFLOP/s":
us = big / (H200_TFLOPS * 1e12) * 1e6
else:
bw = LINK_GBPS if name.startswith("dist-") else H200_GBPS
us = big / (bw * 2 ** 30) * 1e6
return metric, round(us, 1)
except Exception:
return None, None
def _slug(s):
"""GitHub heading anchor: lowercase, drop punctuation, each space -> one hyphen."""
s = re.sub(r"[^\w\s-]", "", s.lower())
return re.sub(r"\s", "-", s.strip())
def family_of(name, kws):
for fam, pred in FAMILIES:
try:
if pred(name, kws):
return fam
except Exception:
pass
return "Other"
def main():
diff = {}
dp = LANE / "_factory" / "difficulty.json"
if dp.exists():
for r in json.loads(dp.read_text()):
diff[r["name"]] = (r["tier"], r["why"])
rows = []
for d in sorted(p for p in LANE.iterdir() if p.is_dir() and not p.name.startswith("_")):
t = d / "task.toml"
if not t.exists():
continue
name, desc, kws, gpus = parse_toml(t)
metric, us = roofline(d, d.name)
tier, why = diff.get(d.name, ("", ""))
rows.append(dict(name=d.name, family=family_of(d.name, kws), tier=tier, tier_why=why,
metric=metric, roofline_us=us, gpus=gpus, keywords=kws, description=desc))
(LANE / "CATALOG.json").write_text(json.dumps(rows, indent=2) + "\n")
order = [f for f, _ in FAMILIES]
by_fam = {}
for r in rows:
by_fam.setdefault(r["family"], []).append(r)
out = [
"# Kernel-generation suite",
"",
f"**{len(rows)} tasks.** Each gives the agent a correct-but-slow reference and an empty stub; the",
"agent writes a fast GPU kernel.",
"",
" reward = 0 if the submission is incorrect",
" reward = achieved TFLOP/s or GB/s otherwise, UNCAPPED",
"",
"Correctness is the gate, speed is the reward. There is no oracle and no gold solution — the score",
"is an absolute hardware metric, so it is hardware-portable and nothing needs re-benchmarking.",
"",
"Task directories are deliberately **flat**: the factory (`_factory/build.py`), the validator",
"(`_factory/validate.sh`) and the size audit (`_factory/audit_sizes.py`) all address tasks as",
"`kernels/<name>`, and harbor is pointed at a task path directly. This catalog provides the",
"structure instead, and is generated from what is on disk (`python3 _factory/make_catalog.py`),",
"so it cannot drift.",
"",
"`roofline` is the implied runtime of a perfect kernel at the largest graded shape (700 TFLOP/s",
"bf16 / 4.8 TB/s HBM; multi-GPU tasks are bounded by the 50 GB/s interconnect instead). Every task",
"is above 250 us, so the kernel dominates rather than launch overhead.",
"",
"## Difficulty",
"",
"Tasks are tiered by **how hard it is to improve on the best available implementation**, not by",
"how complex they look. A dense GEMM is a one-liner and near-unbeatable; a five-pass elementwise",
"chain is trivial to describe and has most of its performance still on the table.",
"",
"| tier | what it takes to win | typical headroom |",
"|---|---|---|",
"| **T1** | fusing several passes into one; coalesced/vectorised access, intermediates in registers | large |",
"| **T2** | shared-memory tiling, warp reductions, an online single-pass reformulation, layout/swizzle changes | moderate |",
"| **T3** | async copy (cp.async/TMA), double buffering, warp specialisation, hand-written MMA with correct fragment layouts | real but only reachable this way |",
"| **T4** | out-engineering a vendor kernel that is already at the hardware limit | very little |",
"",
"## Contents",
"",
]
for fam in order:
if fam in by_fam:
anchor = _slug(fam)
out.append(f"- [{fam}](#{anchor}) — {len(by_fam[fam])}")
out.append("")
for fam in order:
if fam not in by_fam:
continue
out += [f"## {fam}", "", "| task | diff | metric | roofline | what the kernel does |",
"|---|---|---|---|---|"]
for r in sorted(by_fam[fam], key=lambda x: x["name"]):
us = f"{r['roofline_us']:.0f} us" if r["roofline_us"] else "—"
d = (r["description"] or "").replace("|", "\\|")
d = (d[:150] + "…") if len(d) > 150 else d
g = " **2-GPU**" if r["gpus"] > 1 else ""
out += [f"| `{r['name']}`{g} | {r.get('tier') or '—'} | {r['metric'] or '—'} | {us} | {d} |"]
out.append("")
out += [
"## Generators",
"",
"| dir | what it builds |",
"|---|---|",
"| `_factory/` | the standard single-function tasks. `AGENT_GUIDE.md` is the contract for adding one. |",
"| `_mega_factory/` | the megakernel family (stateful multi-step, measured fusion gates). `CALIBRATION.md` records every measured design decision. |",
"| `_dist_factory/` | the 2-GPU `dist-*` tasks. |",
"| `_parked/` | tasks that do not yet validate. **Excluded from the suite** — never shipped. |",
"",
]
(LANE / "README.md").write_text("\n".join(out))
print(f"CATALOG.json + README.md written: {len(rows)} tasks in {len(by_fam)} families")
for fam in order:
if fam in by_fam:
print(f" {len(by_fam[fam]):4d} {fam}")
if __name__ == "__main__":
main()