"""Assign each task a DIFFICULTY tier — how hard it is to IMPROVE, not how complex it looks. Structural scope is the wrong axis. A dense GEMM is a one-liner and essentially unbeatable, because cuBLAS/CUTLASS already sit at the hardware limit; a five-pass elementwise chain is trivial to describe and has 5-10x of fusion headroom sitting on the table. So difficulty = HEADROOM x the TECHNIQUE DEPTH needed to capture it. T1 fusion The best available implementation is several separate passes over memory. The win is doing it in one. Techniques: kernel fusion, coalesced/vectorised access, keeping intermediates in registers. Typically 3-10x available. T2 tiling+reduction Needs shared-memory tiling, warp/block reductions, an online (single-pass) reformulation, or a layout change to make access coalesced. Techniques: smem tiling, warp shuffles, online softmax, swizzles. 2-5x. T3 pipelined/MMA Needs async copy (cp.async / TMA), double buffering, warp specialisation, and tensor-core MMA with correct fragment layouts and bank-conflict-free swizzles. The headroom is real but only reachable this way. 1.5-3x. T4 at-roofline A vendor library already runs this within ~1.5x of the hardware limit. Beating it means out-engineering the vendor's own kernel team. Dense GEMM against cuBLAS, FA-class attention. <1.5x available. Two signals, combined: * EMPIRICAL: what fraction of the roofline the shipped reference already attains. Computed from the validated reference metric and the audited roofline. High fraction => little left on the table. * STRUCTURAL: whether the reference's inner loop is a VENDOR call (torch matmul -> cuBLAS, SDPA -> a FlashAttention kernel, conv -> cuDNN). This matters because a vendor-backed reference IS the incumbent an agent has to beat, whereas a hand-written multi-pass reference is not. Neither signal alone is enough: the roofline constant is not dtype-aware (an int8 GEMM's peak is far above the bf16 number), so the fraction can badly understate a quantised task's difficulty. The vendor flag corrects exactly that case. """ import ast import json import pathlib import re import sys LANE = pathlib.Path(__file__).resolve().parent.parent H200_TFLOPS, H200_GBPS, LINK_GBPS = 700.0, 4800.0, 50.0 MATMULish = {"matmul", "mm", "bmm", "addmm", "baddbmm", "einsum", "_int_mm", "_scaled_mm", "scaled_dot_product_attention", "conv1d", "conv2d", "conv3d", "conv_transpose2d", "conv_transpose3d", "linear"} REDUCE = {"sum", "mean", "amax", "amin", "max", "min", "cumsum", "cumprod", "softmax", "logsumexp", "norm", "var", "std", "prod", "argmax", "argsort", "sort", "topk", "rms_norm", "layer_norm", "log_softmax", "scatter_add_", "index_add_", "bincount"} MASKY = {"masked_fill", "masked_fill_", "where", "tril", "triu", "gather", "scatter", "scatter_", "index_select", "take_along_dim", "repeat_interleave", "nonzero", "bucketize"} QUANT = re.compile(r"float8_e[45]m[23]|uint8|int8|int32\b|\.to\(torch\.int|>>|<<|&\s*0x|nibble|" r"e8m0|e2m1|absmax|dequant|qmap", re.I) def analyse_reference(task): """What KIND of kernel is this, structurally? Driven off the AST, not text: the earlier regex missed `a @ b.t()` and `(q*s) @ k[b].transpose(1,2)` -- i.e. most of the matmuls in the lane.""" p = LANE / task / "environment" / "reference.py" if not p.exists(): return None src = p.read_text() try: tree = ast.parse(src) except SyntaxError: return None n_mm, calls = 0, set() for n in ast.walk(tree): if isinstance(n, ast.BinOp) and isinstance(n.op, ast.MatMult): n_mm += 1 # the `@` operator IS a cuBLAS call elif isinstance(n, ast.Call): f = n.func nm = f.attr if isinstance(f, ast.Attribute) else (f.id if isinstance(f, ast.Name) else "") if nm: calls.add(nm) if nm in MATMULish: n_mm += 1 # A vendor kernel only counts as "already at roofline" if it applies to the WHOLE task. # These structures mean it does not: grouped = bool(re.search(r"\boffsets?\b|\bcounts?\b|group_?(?:size|idx|id)|varm|" r"expert_?(?:idx|id|offsets)|cu_seqlens", src, re.I)) custom_conv = bool(re.search(r"F\.pad|padding\s*=\s*\(|causal|groups\s*=|feather|blend|" r"tile|overlap", src, re.I)) epilogue = bool(re.search(r"silu|gelu|swiglu|geglu|sigmoid|tanh\(|\* *gate|gate *\*", src, re.I)) return dict(grouped=grouped, custom_conv=custom_conv, epilogue=epilogue, n_mm=n_mm, sdpa="scaled_dot_product_attention" in calls, conv=any(c.startswith("conv") for c in calls), reduce=bool(calls & REDUCE), masky=bool(calls & MASKY), quant=bool(QUANT.search(src))) def roofline_us(task): v = LANE / task / "tests" / "verify_env.py" if not v.exists(): return None, None src = v.read_text() if "canonical_work" not in src: return None, None ns, shapes = {}, None try: for node in ast.parse(src).body: if isinstance(node, (ast.FunctionDef, ast.Assign)): try: exec(compile(ast.Module([node], []), "", "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": return metric, big / (H200_TFLOPS * 1e12) * 1e6 bw = LINK_GBPS if task.startswith("dist-") else H200_GBPS return metric, big / (bw * 2 ** 30) * 1e6 except Exception: return None, None def peak_for(metric, task): if metric == "TFLOP/s": return H200_TFLOPS return (LINK_GBPS if task.startswith("dist-") else H200_GBPS) # T4 is the highest-stakes label -- it asserts a vendor kernel is already at the hardware limit, i.e. # that the task is near-unbeatable. The structural classifier gets the other tiers right but is too # blunt here, so this small set is reviewed by hand and the reason recorded. Auditable by construction. OVERRIDE = { "dist-allgather-gemm-overlap": ("T3", "2-GPU compute/communication overlap: the GEMM is a library " "call but the overlap schedule is the task"), "moe-grouped-gemm-contiguous": ("T3", "grouped GEMM over a contiguous expert layout: no single " "library call covers it"), "moe-grouped-gemm-varm": ("T3", "variable-M grouped GEMM: cuBLAS has no such call"), "moe-grouped-swiglu": ("T3", "grouped GEMM with a fused SwiGLU epilogue"), "deepseek-mla-vabsorb-outproj": ("T3", "MLA V-absorb folds the value projection into the output " "projection: a fused GEMM pair, not a plain one"), "hunyuan-dualstream-attn-proj": ("T3", "two per-stream output projections plus per-sample gates: " "a 2-group GEMM with M=1e5 against M=1e2"), "spatial-upsample-pixelshuffle3d": ("T2", "pixel-shuffle upsample is a layout transform, not a " "convolution cuDNN accelerates"), } def tier(a, frac): """Technique depth required to beat the best AVAILABLE implementation. This is a structural judgement, deliberately not an empirical one. Measuring the shipped reference cannot answer it: the references are intentionally slow fp32/fp64 specs, so `int8-w8a8-gemm` shows 12.9x of apparent headroom purely because its reference multiplies in float64. And torch.compile(max-autotune) is not a usable proxy either -- it fails to trace most of these references (exec'd source, closures, data-dependent control flow) and barely helps where it does. """ if a is None: return "T2", "unanalysable reference; defaulted" compute = a["n_mm"] > 0 or a["sdpa"] or a["conv"] if not compute: if a["reduce"] or a["masky"]: return "T2", "bandwidth kernel with a reduction/gather: shared-memory tiling and a warp reduction" return "T1", "elementwise/bandwidth chain: the win is fusing the passes into one" # --- compute-bound: does a library kernel apply to the WHOLE task, or only to a piece? --- if a["quant"]: return "T3", ("quantised matmul: cuBLAS will not fuse the dequant, so the MMA pipeline is " "hand-written -- async copy, double buffering, fragment layouts") if a["grouped"]: return "T3", ("grouped / variable-M GEMM: there is no single library call for it, so the " "per-group tiling and scheduling are the task") if a["sdpa"] and not a["masky"]: return "T4", "plain attention: an FA-class kernel applies directly and already sits near roofline" if a["masky"] or a["sdpa"]: return "T3", ("attention with custom masking/sparsity: no library kernel applies as-is, so the " "tiled online-softmax pipeline is written by hand") if a["conv"]: if a["custom_conv"]: return "T3", ("convolution with custom padding/grouping/tiling: cuDNN's path for this case " "is not the fast one, so the tiled kernel is the task") return "T4", "plain convolution: cuDNN applies directly and already runs near roofline" if a["epilogue"]: return "T3", "GEMM with a fused activation/gate epilogue: needs a hand-written MMA pipeline" if a["n_mm"] <= 2 and not a["reduce"]: return "T4", "dense GEMM: cuBLAS/CUTLASS are already at the hardware limit" return "T3", "multi-GEMM block: needs a hand-written, pipelined MMA sequence to beat" def load_measured(): """Reference achieved metrics from the validation sweeps.""" out = {} for f in pathlib.Path("/tmp").glob("*out_*.txt"): try: for line in f.read_text().splitlines(): m = re.match(r"^(\S+)\s+stub\[.*?\]\s+ref\[([0-9.]+)\s", line) if m: out[m.group(1)] = float(m.group(2)) except Exception: pass return out def main(): meas = load_measured() rows = [] for d in sorted(p for p in LANE.iterdir() if p.is_dir() and not p.name.startswith("_")): t = d.name if not (d / "task.toml").exists(): continue metric, rus = roofline_us(t) got = meas.get(t) a = analyse_reference(t) frac = None if metric and got: frac = min(got / peak_for(metric, t), 1.0) tr, why = OVERRIDE.get(t) or tier(a, frac) rows.append(dict(name=t, tier=tr, why=why, frac=round(frac, 4) if frac else None, analysis=a, metric=metric, roofline_us=rus, ref_metric=got)) (LANE / "_factory" / "difficulty.json").write_text(json.dumps(rows, indent=2) + "\n") from collections import Counter c = Counter(r["tier"] for r in rows) print(f"scored {len(rows)} tasks measured={sum(1 for r in rows if r['frac'] is not None)}") for k in ("T1", "T2", "T3", "T4"): print(f" {k}: {c[k]}") return rows if __name__ == "__main__": rows = main() for anchor in sys.argv[1:]: for r in rows: if r["name"] == anchor: print(f"\n{r['name']}: {r['tier']} ({r['why']})")