File size: 11,944 Bytes
2e4c7fe | 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 | """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], []), "<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":
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']})")
|