#!/usr/bin/env python3 """Single source of truth for the KernelSight workload taxonomy. Defines L1 (12 coarse) + L2 (~73 fine) workload categories, plus the 8-flag implementation-style ``ATTRIBUTE_FLAGS`` (multi-label) and the 5-class ``SPATIAL_STATE_VOCAB`` (single-label). L2 derivation lives behind ``parse_l2_sequence`` and ``infer_from_filename_l2``; per-bin spatial-state derivation is out of scope (no fused kernels in the corpus), but the vocab is exposed here so downstream label tooling can pin its head. Public surface (consumed by ``tools/build_labels.py``, ``tools/build_splits.py``, ``tests/test_tensor_invariants.py`` and the KernelBench harness): VOCAB_L1: list[str] 12 L1 names. Indexes downstream as ``L1_TO_ID``. VOCAB_L2: list[str] ~73 L2 names. Sorted by ``(l1_index, l2_name)`` — VOCAB_L1's order is preserved at the L1 group level, names sort alphabetically inside each group. Indexes downstream as ``L2_TO_ID``. L2_PARENT_L1: dict[str, str] Each L2 -> its L1 parent. ``L2_PARENT_L1[l2] in L1_TO_ID`` is asserted at module import; the hierarchy invariant test in ``tests/test_tensor_invariants.py`` enforces it per-bin / per-segment. TAXONOMY: dict[str, list[str]] L1 -> sorted list of L2 children. Equivalent shape to L2_PARENT_L1 inverted; kept for callers that want to enumerate by L1. ATTRIBUTE_FLAGS: list[str] 8 implementation-style multi-label flags (sparse / tma / cluster / masked / persistent / vectorized_store / atomic_accum / ldgsts). Each is independent — the model side gets a binary head per flag. SPATIAL_STATE_VOCAB: list[str] 5-class spatial-state taxonomy (uniform / wavefront_transition / tail_effect / load_imbalanced / hotspot). Per-bin ``spatial_state[T]`` derivation is out of scope (no fused kernels in the corpus); the vocab is pinned here so the model side can structure its head. ANCHOR_OVERRIDES: dict[str, str] Exact-basename -> L1. The same entries live in ``ANCHOR_OVERRIDES_L2`` (with an L2 attached). ANCHOR_OVERRIDES_L2: dict[str, tuple[str, str]] Exact-basename -> (L1, L2). Covers: * the 5 microbench motif directory names, * the 4 outer ``phase_X_*`` NVTX names emitted by the megakernel host, * the 4 inner ``op_*`` NVTX names emitted by the megakernel host (nested NVTX shape from ``kernels/megakernel/main.cc``). FILENAME_RULES: list[tuple[re.Pattern, str]] Regex fallback for L1 inference on basenames that miss ``ANCHOR_OVERRIDES`` and the KB L1 problem-id table. infer_from_filename(basename: str) -> str L1 label resolution entry point. Resolution order: 1. ``ANCHOR_OVERRIDES`` 2. KB L1 problem-id table (``_KB_L1_PROBLEM_TO_L1``) 3. ``FILENAME_RULES`` regex fallback 4. "other" infer_from_filename_l2(basename: str) -> tuple[str, str] (L1, L2) label resolution entry point. Resolution order: 1. ``ANCHOR_OVERRIDES_L2`` 2. KB L1 problem-id table -> ``_KB_L1_PROBLEM_TO_OPS`` (single op) 3. KB L2 problem-id table -> ``_KB_L2_PROBLEM_TO_OPS`` (override) 4. Token rule fallback (uses ``_OP_TOKEN_TO_L2`` per CamelCase token) 5. ``("other", "other_misc")`` parse_l2_sequence(basename: str) -> list[tuple[str, str]] Sequence-aware version of ``infer_from_filename_l2``. Returns the ordered list of (L1, L2) pairs implied by the filename: * L1 problems return a length-1 list, * L2 problems return a length-N list (one per op token), * anchor basenames return a length-1 list, * unknown basenames return ``[("other", "other_misc")]``. infer_from_aten(aten_op: str) -> str Stub for an aten-op label path. Returns "other". multihot_from_ids(ids, dim: int) -> list[int] Canonical multi-hot primitive (OR of one-hots). Ignores ids outside ``[0, dim)`` (e.g. the -1 unlabeled sentinel), so it subsumes the single-label one-hot case. Used by ``tools/build_labels.py`` to build the additive ``workload_l1_multihot`` / ``workload_l2_multihot`` tracks. l1_multihot_from_l2_multihot(l2_multihot) -> list[int] Project an L2 multi-hot row onto its implied L1 multi-hot row (set the ``L2_PARENT_L1`` parent of every active L2). Encodes the L1/L2 hierarchy invariant the CI enforces on the multi-hot tracks. Smoke check: ``python tools/workload_taxonomy.py`` walks both the KB L1 and KB L2 directories and reports per-L1 / per-L2 coverage. The target is 100/100 coverage on both levels with no ``other_misc`` fallthrough. """ from __future__ import annotations import re import sys from pathlib import Path VOCAB_L1: list[str] = [ "matmul", "conv", "activation", "normalization", "softmax", "pooling", "reduction", "attention", "loss", "elementwise", "memory_movement", "other", ] assert len(VOCAB_L1) == 12, "VOCAB_L1 must hold 12 L1 categories" assert len(set(VOCAB_L1)) == len(VOCAB_L1), "VOCAB_L1 has duplicate entries" L1_TO_ID: dict[str, int] = {n: i for i, n in enumerate(VOCAB_L1)} # --------------------------------------------------------------------------- # L2 taxonomy # --------------------------------------------------------------------------- # Per-L1 list of L2 children. Each L2 name is prefixed with its L1 parent # for traceability and to make the parent recoverable from the name in # emergency debugging. The flattened VOCAB_L2 below is the canonical order # downstream code keys against; the dict is the authoring shape. _L2_BY_L1: dict[str, list[str]] = { "matmul": [ "matmul_bmm", "matmul_gemm", "matmul_matvec", ], "conv": [ "conv_conv1d_standard", "conv_conv2d_depthwise", "conv_conv2d_pointwise", "conv_conv2d_standard", "conv_conv3d_standard", "conv_convtranspose1d", "conv_convtranspose2d", "conv_convtranspose3d", ], "activation": [ "activation_elu", "activation_gelu", "activation_hardsigmoid", "activation_hardswish", "activation_hardtanh", "activation_leaky_relu", "activation_mish", "activation_other", "activation_relu", "activation_selu", "activation_sigmoid", "activation_softplus", "activation_softsign", "activation_swish", "activation_tanh", ], "normalization": [ "normalization_batchnorm", "normalization_frobeniusnorm", "normalization_groupnorm", "normalization_instancenorm", "normalization_l1norm", "normalization_l2norm", "normalization_layernorm", "normalization_rmsnorm", ], "softmax": [ "softmax_log_softmax", "softmax_logsumexp", "softmax_softmax", ], "pooling": [ "pooling_avg_pool", "pooling_global_avg_pool", "pooling_max_pool", ], "reduction": [ "reduction_argmax", "reduction_argmin", "reduction_cumprod", "reduction_cumsum", "reduction_max", "reduction_mean", "reduction_min", "reduction_prod", "reduction_sum", ], "attention": [ "attention_scaled_dot_product", ], "loss": [ "loss_cross_entropy", "loss_hinge", "loss_huber", "loss_kldiv", "loss_mse", "loss_triplet_margin", ], "elementwise": [ "elementwise_add", "elementwise_bias_add", "elementwise_cast", "elementwise_clamp", "elementwise_div", "elementwise_mul", "elementwise_residual_add", "elementwise_scalar_multiplication", "elementwise_scaling", "elementwise_sub", ], "memory_movement": [ "memory_movement_copy", "memory_movement_embedding", "memory_movement_gather", "memory_movement_scatter", "memory_movement_transpose", ], "other": [ "other_dropout", "other_misc", ], } for _l1, _children in _L2_BY_L1.items(): assert _l1 in L1_TO_ID, f"_L2_BY_L1 key {_l1!r} is not in VOCAB_L1" assert _children == sorted(_children), \ f"_L2_BY_L1[{_l1!r}] is not sorted alphabetically" for _c in _children: assert _c.startswith(_l1 + "_"), \ f"L2 name {_c!r} must be prefixed with its L1 parent {_l1!r}" # Flatten in VOCAB_L1 order so L2 ids cluster by L1 family. VOCAB_L2: list[str] = [] for _l1 in VOCAB_L1: VOCAB_L2.extend(_L2_BY_L1[_l1]) assert len(VOCAB_L2) == len(set(VOCAB_L2)), "VOCAB_L2 has duplicate entries" L2_TO_ID: dict[str, int] = {n: i for i, n in enumerate(VOCAB_L2)} L2_PARENT_L1: dict[str, str] = {l2: _l1 for _l1, children in _L2_BY_L1.items() for l2 in children} for _l2, _parent in L2_PARENT_L1.items(): assert _parent in L1_TO_ID, \ f"L2_PARENT_L1[{_l2!r}] = {_parent!r} not in VOCAB_L1" # Public alias. ``TAXONOMY[l1]`` yields the sorted L2 child list. TAXONOMY: dict[str, list[str]] = {l1: list(_L2_BY_L1[l1]) for l1 in VOCAB_L1} # L2 ops that launch NO device kernel during inference (model.eval()). They # appear in problem names / parsed op sequences but produce no observable # launch, so ``tools/build_labels.py`` drops them from the op sequence before # aligning kernel launches to ops -- otherwise an iter with launches < ops is # skipped (e.g. ``66_Matmul_Dropout_Softmax``: 2 launches vs 3 ops) or a real # kernel is mislabeled. Extend as new inference-no-op ops appear. INFERENCE_NOOP_L2: frozenset[str] = frozenset({"other_dropout"}) for _l2 in INFERENCE_NOOP_L2: assert _l2 in L2_TO_ID, f"INFERENCE_NOOP_L2 entry {_l2!r} not in VOCAB_L2" # --------------------------------------------------------------------------- # Auxiliary vocabs (attribute flags + spatial state) # --------------------------------------------------------------------------- # Multi-label flags describing kernel *implementation style*. Each is a # separate binary head on the model side; new variants extend without # retraining the L1/L2 heads. Order is fixed: indexing matches the # ``attribute_flags[S, 8]`` columns in ``labels.npz`` and the # ``EXPECTED_ATTRIBUTE_FLAGS`` invariant in ``tests/test_tensor_invariants.py``. ATTRIBUTE_FLAGS: list[str] = [ "sparse", "tma", "cluster", "masked", "persistent", "vectorized_store", "atomic_accum", "ldgsts", ] assert len(ATTRIBUTE_FLAGS) == 8, "ATTRIBUTE_FLAGS must hold exactly 8 flags" assert len(set(ATTRIBUTE_FLAGS)) == len(ATTRIBUTE_FLAGS), \ "ATTRIBUTE_FLAGS has duplicate entries" # Single-label spatial-state classes (5-class). Per-bin derivation is out # of scope; the vocab is pinned here so the model side can structure its # head. SPATIAL_STATE_VOCAB: list[str] = [ "uniform", "wavefront_transition", "tail_effect", "load_imbalanced", "hotspot", ] assert len(SPATIAL_STATE_VOCAB) == 5, \ "SPATIAL_STATE_VOCAB must hold exactly 5 classes" assert len(set(SPATIAL_STATE_VOCAB)) == len(SPATIAL_STATE_VOCAB), \ "SPATIAL_STATE_VOCAB has duplicate entries" # --------------------------------------------------------------------------- # Multi-hot helpers (overlapping / concurrent per-bin labels) # --------------------------------------------------------------------------- # # The single-label corpus carries one class id per bin. Genuine concurrency # (e.g. a Hopper warp-specialized GEMM whose producer TMA-load phase # overlaps its consumer WGMMA phase in wall-clock time) needs >=2 classes # active in the same bin. ``multihot_from_ids`` is the canonical primitive # used to build the per-bin ``workload_l1_multihot[T, 12]`` / # ``workload_l2_multihot[T, 73]`` tracks in ``tools/build_labels.py`` and to # inject externally-provided overlapping spans. It is numpy-free so this # module keeps its stdlib-only import surface; the label builder does the # vectorized construction. ``l1_multihot_from_l2_multihot`` enforces the # L1/L2 hierarchy on a multi-hot row the same way ``L2_PARENT_L1`` does for # the single-label path. def multihot_from_ids(ids, dim: int) -> list[int]: """Return a length-``dim`` list of 0/1 ints, 1 at each id in ``ids``. The canonical multi-hot primitive (OR of one-hots). ``ids`` may repeat (idempotent). Ids outside ``[0, dim)`` -- notably the ``-1`` unlabeled sentinel -- are ignored, so: * ``multihot_from_ids([single_label_id], dim)`` is the one-hot of a single-label bin (this is why the multi-hot schema subsumes the single-label corpus as a degenerate one-hot), * ``multihot_from_ids([-1], dim)`` is the all-zero (unlabeled) row, * ``multihot_from_ids([a, b], dim)`` is the two-class overlap row. """ vec = [0] * dim for i in ids: j = int(i) if 0 <= j < dim: vec[j] = 1 return vec def l1_multihot_from_l2_multihot(l2_multihot) -> list[int]: """Project an L2 multi-hot row onto its implied L1 multi-hot row. For every active L2 class, its unique L1 parent (``L2_PARENT_L1``) is set in the returned ``len(VOCAB_L1)`` vector. This is the hierarchy invariant the CI enforces on the multi-hot tracks: ``l2_parent_l1[j]`` must be set in L1 wherever L2 ``j`` is set. ``l2_multihot`` is any length-|VOCAB_L2| sequence of truthy/falsy values. """ parents = [] for j, on in enumerate(l2_multihot): if on: parents.append(L1_TO_ID[L2_PARENT_L1[VOCAB_L2[j]]]) return multihot_from_ids(parents, len(VOCAB_L1)) # --------------------------------------------------------------------------- # Anchor overrides (microbench / CUTLASS) # --------------------------------------------------------------------------- # basename -> L1. Kept so callers that only need L1 (e.g. # ``infer_from_filename``) have a direct lookup. ANCHOR_OVERRIDES: dict[str, str] = { "vector_add": "elementwise", "reduction": "reduction", "gather": "memory_movement", "scatter": "memory_movement", "wgmma": "matmul", "cutlass_gemm": "matmul", "cutlass_fmha": "attention", "cutlass_fp8_gemm": "matmul", "cutlass_sparse_gemm": "matmul", "cutlass_grouped_gemm": "matmul", # Device-marker overlap PoC (WGMMA-dominated GEMM op identity). The anchor # is the single-label baseline; the genuine intra-launch phase overlap is # OR'd in by the corpus label driver from %globaltimer markers. "cutlass_ws_overlap": "matmul", } for _l1 in ANCHOR_OVERRIDES.values(): assert _l1 in L1_TO_ID, f"ANCHOR_OVERRIDES references unknown L1 {_l1!r}" # basename -> (L1, L2). Covers the same set as ANCHOR_OVERRIDES. The microbench # entries duplicate ANCHOR_OVERRIDES on the L1 axis by construction (asserted # below). cutlass_grouped_gemm anchors as matmul_bmm (many small GEMMs scheduled # on-device), the other CUTLASS GEMM variants as matmul_gemm. ANCHOR_OVERRIDES_L2: dict[str, tuple[str, str]] = { "vector_add": ("elementwise", "elementwise_add"), "reduction": ("reduction", "reduction_sum"), "gather": ("memory_movement", "memory_movement_gather"), "scatter": ("memory_movement", "memory_movement_scatter"), "wgmma": ("matmul", "matmul_gemm"), "cutlass_gemm": ("matmul", "matmul_gemm"), "cutlass_fmha": ("attention", "attention_scaled_dot_product"), "cutlass_fp8_gemm": ("matmul", "matmul_gemm"), "cutlass_sparse_gemm": ("matmul", "matmul_gemm"), "cutlass_grouped_gemm": ("matmul", "matmul_bmm"), "cutlass_ws_overlap": ("matmul", "matmul_gemm"), } for _name, (_l1, _l2) in ANCHOR_OVERRIDES_L2.items(): assert _l1 in L1_TO_ID, \ f"ANCHOR_OVERRIDES_L2[{_name!r}] L1 {_l1!r} not in VOCAB_L1" assert _l2 in L2_TO_ID, \ f"ANCHOR_OVERRIDES_L2[{_name!r}] L2 {_l2!r} not in VOCAB_L2" assert L2_PARENT_L1[_l2] == _l1, \ f"ANCHOR_OVERRIDES_L2[{_name!r}]: L2 {_l2!r}'s parent " \ f"{L2_PARENT_L1[_l2]!r} != declared L1 {_l1!r}" for _name, _l1 in ANCHOR_OVERRIDES.items(): assert _name in ANCHOR_OVERRIDES_L2, \ f"ANCHOR_OVERRIDES_L2 missing {_name!r}" assert ANCHOR_OVERRIDES_L2[_name][0] == _l1, \ f"ANCHOR_OVERRIDES_L2[{_name!r}] L1 axis drifts from ANCHOR_OVERRIDES" # --------------------------------------------------------------------------- # KernelBench L1 problem-id rule table # --------------------------------------------------------------------------- # # ``_KB_L1_PROBLEM_TO_OPS`` maps id -> [(L1, L2)] (length 1 since L1 # problems are single-op). ``_KB_L1_PROBLEM_TO_L1`` is projected from # the OPS table for callers that only need L1. The two stay in lockstep # -- the assertion at the bottom of this section enforces it. _KB_L1_PROBLEM_TO_OPS: dict[int, list[tuple[str, str]]] = { # 1-18 (except 5): matmul variants 1: [("matmul", "matmul_gemm")], 2: [("matmul", "matmul_gemm")], 3: [("matmul", "matmul_bmm")], 4: [("matmul", "matmul_matvec")], 5: [("elementwise", "elementwise_scalar_multiplication")], 6: [("matmul", "matmul_gemm")], 7: [("matmul", "matmul_gemm")], 8: [("matmul", "matmul_gemm")], 9: [("matmul", "matmul_gemm")], 10: [("matmul", "matmul_bmm")], 11: [("matmul", "matmul_bmm")], 12: [("matmul", "matmul_gemm")], 13: [("matmul", "matmul_gemm")], 14: [("matmul", "matmul_gemm")], 15: [("matmul", "matmul_gemm")], 16: [("matmul", "matmul_gemm")], 17: [("matmul", "matmul_gemm")], 18: [("matmul", "matmul_gemm")], # 19-32: activation 19: [("activation", "activation_relu")], 20: [("activation", "activation_leaky_relu")], 21: [("activation", "activation_sigmoid")], 22: [("activation", "activation_tanh")], 23: [("softmax", "softmax_softmax")], 24: [("softmax", "softmax_log_softmax")], 25: [("activation", "activation_swish")], 26: [("activation", "activation_gelu")], 27: [("activation", "activation_selu")], 28: [("activation", "activation_hardsigmoid")], 29: [("activation", "activation_softplus")], 30: [("activation", "activation_softsign")], 31: [("activation", "activation_elu")], 32: [("activation", "activation_hardtanh")], # 33-40: normalization 33: [("normalization", "normalization_batchnorm")], 34: [("normalization", "normalization_instancenorm")], 35: [("normalization", "normalization_groupnorm")], 36: [("normalization", "normalization_rmsnorm")], 37: [("normalization", "normalization_frobeniusnorm")], 38: [("normalization", "normalization_l1norm")], 39: [("normalization", "normalization_l2norm")], 40: [("normalization", "normalization_layernorm")], # 41-46: pooling 41: [("pooling", "pooling_max_pool")], 42: [("pooling", "pooling_max_pool")], 43: [("pooling", "pooling_max_pool")], 44: [("pooling", "pooling_avg_pool")], 45: [("pooling", "pooling_avg_pool")], 46: [("pooling", "pooling_avg_pool")], # 47-49, 51-53: reduction 47: [("reduction", "reduction_sum")], 48: [("reduction", "reduction_mean")], 49: [("reduction", "reduction_max")], 51: [("reduction", "reduction_argmax")], 52: [("reduction", "reduction_argmin")], 53: [("reduction", "reduction_min")], # 50, 54-87: conv (mixed 1D/2D/3D, standard / transposed / depthwise / # pointwise). Sourced by inspecting # ``KernelBench/KernelBench/level1/*.py`` filenames. 50: [("conv", "conv_conv2d_standard")], 54: [("conv", "conv_conv3d_standard")], 55: [("conv", "conv_conv2d_standard")], 56: [("conv", "conv_conv2d_standard")], 57: [("conv", "conv_convtranspose2d")], 58: [("conv", "conv_convtranspose3d")], 59: [("conv", "conv_conv3d_standard")], 60: [("conv", "conv_conv3d_standard")], 61: [("conv", "conv_convtranspose3d")], 62: [("conv", "conv_conv2d_standard")], 63: [("conv", "conv_conv2d_standard")], 64: [("conv", "conv_convtranspose1d")], 65: [("conv", "conv_convtranspose2d")], 66: [("conv", "conv_conv3d_standard")], 67: [("conv", "conv_conv1d_standard")], 68: [("conv", "conv_convtranspose3d")], 69: [("conv", "conv_convtranspose2d")], 70: [("conv", "conv_convtranspose3d")], 71: [("conv", "conv_convtranspose2d")], 72: [("conv", "conv_convtranspose3d")], 73: [("conv", "conv_convtranspose3d")], 74: [("conv", "conv_convtranspose1d")], 75: [("conv", "conv_convtranspose2d")], 76: [("conv", "conv_conv1d_standard")], 77: [("conv", "conv_convtranspose3d")], 78: [("conv", "conv_convtranspose2d")], 79: [("conv", "conv_convtranspose1d")], 80: [("conv", "conv_conv2d_standard")], 81: [("conv", "conv_convtranspose2d")], 82: [("conv", "conv_conv2d_depthwise")], 83: [("conv", "conv_conv2d_depthwise")], 84: [("conv", "conv_conv2d_depthwise")], 85: [("conv", "conv_conv2d_depthwise")], # 86 is depthwise-separable (depthwise + pointwise stages); treated as # depthwise for L2 labeling purposes since the depthwise stage carries # the dominant compute pattern. 86: [("conv", "conv_conv2d_depthwise")], 87: [("conv", "conv_conv2d_pointwise")], # 88: GELU variant (MinGPT's new_gelu polynomial); collapses to gelu. 88: [("activation", "activation_gelu")], # 89-93: cumsum / cumprod variants. 89: [("reduction", "reduction_cumsum")], 90: [("reduction", "reduction_cumprod")], 91: [("reduction", "reduction_cumsum")], 92: [("reduction", "reduction_cumsum")], 93: [("reduction", "reduction_cumsum")], # 94-100: losses + attention. 94: [("loss", "loss_mse")], 95: [("loss", "loss_cross_entropy")], 96: [("loss", "loss_huber")], 97: [("attention", "attention_scaled_dot_product")], 98: [("loss", "loss_kldiv")], 99: [("loss", "loss_triplet_margin")], 100: [("loss", "loss_hinge")], } assert len(_KB_L1_PROBLEM_TO_OPS) == 100, \ f"KB L1 OPS table has {len(_KB_L1_PROBLEM_TO_OPS)} entries, expected 100" for _pid, _ops in _KB_L1_PROBLEM_TO_OPS.items(): assert len(_ops) == 1, \ f"KB L1 problem {_pid} has {len(_ops)} ops, expected 1" _l1, _l2 = _ops[0] assert _l1 in L1_TO_ID, \ f"KB L1 problem {_pid} -> L1 {_l1!r} not in VOCAB_L1" assert _l2 in L2_TO_ID, \ f"KB L1 problem {_pid} -> L2 {_l2!r} not in VOCAB_L2" assert L2_PARENT_L1[_l2] == _l1, \ f"KB L1 problem {_pid}: L2 {_l2!r} parent " \ f"{L2_PARENT_L1[_l2]!r} != declared L1 {_l1!r}" # ``_KB_L1_PROBLEM_TO_L1`` projected from the OPS table so # ``infer_from_filename`` (L1-only entry point) continues to work. _KB_L1_PROBLEM_TO_L1: dict[int, str] = { pid: ops[0][0] for pid, ops in _KB_L1_PROBLEM_TO_OPS.items() } # --------------------------------------------------------------------------- # KernelBench L2 problem-id override table # --------------------------------------------------------------------------- # # Token-rule fallback (``_OP_TOKEN_TO_L2``) handles every L2 problem on # disk today. This table is reserved for problems where the parser is # ambiguous; it is currently empty and the smoke check at the bottom # of the file fails loudly if a token can't be resolved. _KB_L2_PROBLEM_TO_OPS: dict[int, list[tuple[str, str]]] = {} # --------------------------------------------------------------------------- # Token rule fallback for L2 problem op sequences # --------------------------------------------------------------------------- # Tokens are extracted by splitting the basename on ``_`` and dropping the # leading numeric id and a trailing ``.py``. Each CamelCase / mixed-case # token maps to a single (L1, L2) pair; descriptor words like "for", # "with", "over", "a", "dimension" don't appear here and are silently # skipped by ``_tokens_to_ops``. # # Sources: # * KernelBench/KernelBench/level2/*.py — 100 op-sequence filenames. # * KernelBench/KernelBench/level1/*.py — 100 single-op filenames (the # L1 problem-id table above takes precedence, but the rules cover # ``Argmax``/``Argmin``/``Cumsum``/``Cumprod``/``MSELoss``/... for # defensive resolution when the id table misses). _OP_TOKEN_TO_L2: dict[str, tuple[str, str]] = { # ---- conv ---- "Conv2D": ("conv", "conv_conv2d_standard"), "Conv2d": ("conv", "conv_conv2d_standard"), "Conv3d": ("conv", "conv_conv3d_standard"), "Conv1d": ("conv", "conv_conv1d_standard"), "ConvTranspose2d": ("conv", "conv_convtranspose2d"), "ConvTranspose3d": ("conv", "conv_convtranspose3d"), "ConvTranspose1d": ("conv", "conv_convtranspose1d"), # ---- matmul ---- "Matmul": ("matmul", "matmul_gemm"), "MatMul": ("matmul", "matmul_gemm"), "Gemm": ("matmul", "matmul_gemm"), "GEMM": ("matmul", "matmul_gemm"), "BMM": ("matmul", "matmul_bmm"), "Bmm": ("matmul", "matmul_bmm"), # ---- activation ---- "ReLU": ("activation", "activation_relu"), "LeakyReLU": ("activation", "activation_leaky_relu"), "Sigmoid": ("activation", "activation_sigmoid"), "Tanh": ("activation", "activation_tanh"), "Swish": ("activation", "activation_swish"), "GELU": ("activation", "activation_gelu"), "SELU": ("activation", "activation_selu"), "HardSigmoid": ("activation", "activation_hardsigmoid"), "HardSwish": ("activation", "activation_hardswish"), "HardTanh": ("activation", "activation_hardtanh"), "Hardtanh": ("activation", "activation_hardtanh"), "Softplus": ("activation", "activation_softplus"), "Softsign": ("activation", "activation_softsign"), "ELU": ("activation", "activation_elu"), "Mish": ("activation", "activation_mish"), "NewGelu": ("activation", "activation_gelu"), "MinGPTNewGelu": ("activation", "activation_gelu"), # Generic "Activation" token (KB L2 problem 52). Mapped to # activation_other so the L1 family is still recoverable without # claiming a specific activation function. "Activation": ("activation", "activation_other"), # ---- softmax-family ---- "Softmax": ("softmax", "softmax_softmax"), "LogSoftmax": ("softmax", "softmax_log_softmax"), "LogSumExp": ("softmax", "softmax_logsumexp"), # ---- pooling ---- "MaxPool": ("pooling", "pooling_max_pool"), "AvgPool": ("pooling", "pooling_avg_pool"), "GlobalAvgPool": ("pooling", "pooling_global_avg_pool"), # ---- normalization ---- "BatchNorm": ("normalization", "normalization_batchnorm"), "LayerNorm": ("normalization", "normalization_layernorm"), "GroupNorm": ("normalization", "normalization_groupnorm"), "InstanceNorm": ("normalization", "normalization_instancenorm"), "RMSNorm": ("normalization", "normalization_rmsnorm"), "FrobeniusNorm": ("normalization", "normalization_frobeniusnorm"), "L1Norm": ("normalization", "normalization_l1norm"), "L2Norm": ("normalization", "normalization_l2norm"), # ---- reduction ---- # ``Sum``/``Mean``/``Max``/``Min`` in L2 filenames are reduction # operations (e.g. ``x = torch.sum(x, dim=1, keepdim=True)``). # Elementwise *addition* uses the ``Add`` token instead, so the # ambiguity is resolved by token choice. "Sum": ("reduction", "reduction_sum"), "Mean": ("reduction", "reduction_mean"), "Max": ("reduction", "reduction_max"), "Min": ("reduction", "reduction_min"), "Prod": ("reduction", "reduction_prod"), "Argmax": ("reduction", "reduction_argmax"), "Argmin": ("reduction", "reduction_argmin"), "Cumsum": ("reduction", "reduction_cumsum"), "cumsum": ("reduction", "reduction_cumsum"), "Cumprod": ("reduction", "reduction_cumprod"), "cumprod": ("reduction", "reduction_cumprod"), # ---- attention ---- "ScaledDotProductAttention": ("attention", "attention_scaled_dot_product"), # ---- loss ---- "MSELoss": ("loss", "loss_mse"), "CrossEntropyLoss": ("loss", "loss_cross_entropy"), "HuberLoss": ("loss", "loss_huber"), "KLDivLoss": ("loss", "loss_kldiv"), "TripletMarginLoss": ("loss", "loss_triplet_margin"), "HingeLoss": ("loss", "loss_hinge"), # ---- elementwise ---- "Add": ("elementwise", "elementwise_add"), "Multiply": ("elementwise", "elementwise_mul"), "Mul": ("elementwise", "elementwise_mul"), "Divide": ("elementwise", "elementwise_div"), "Div": ("elementwise", "elementwise_div"), "Subtract": ("elementwise", "elementwise_sub"), "Sub": ("elementwise", "elementwise_sub"), "Clamp": ("elementwise", "elementwise_clamp"), "Scale": ("elementwise", "elementwise_scaling"), "Scaling": ("elementwise", "elementwise_scaling"), "BiasAdd": ("elementwise", "elementwise_bias_add"), "ResidualAdd": ("elementwise", "elementwise_residual_add"), "Cast": ("elementwise", "elementwise_cast"), # ---- memory_movement (none of the KB L2 problems exercise these, but # the table covers ANCHOR_OVERRIDES_L2 names + future motifs) "Gather": ("memory_movement", "memory_movement_gather"), "Scatter": ("memory_movement", "memory_movement_scatter"), "Embedding": ("memory_movement", "memory_movement_embedding"), "Copy": ("memory_movement", "memory_movement_copy"), "Transpose": ("memory_movement", "memory_movement_transpose"), # ---- other ---- "Dropout": ("other", "other_dropout"), } for _tok, (_l1, _l2) in _OP_TOKEN_TO_L2.items(): assert _l1 in L1_TO_ID, \ f"_OP_TOKEN_TO_L2[{_tok!r}] L1 {_l1!r} not in VOCAB_L1" assert _l2 in L2_TO_ID, \ f"_OP_TOKEN_TO_L2[{_tok!r}] L2 {_l2!r} not in VOCAB_L2" assert L2_PARENT_L1[_l2] == _l1, \ f"_OP_TOKEN_TO_L2[{_tok!r}]: L2 {_l2!r} parent " \ f"{L2_PARENT_L1[_l2]!r} != declared L1 {_l1!r}" # --------------------------------------------------------------------------- # Regex fallback (L1 inference for newly-added basenames) # --------------------------------------------------------------------------- FILENAME_RULES: list[tuple[re.Pattern, str]] = [ # matmul family (re.compile(r"(?i)matmul|gemm|matrix_multiplication|matrix_vector"), "matmul"), # conv family (depthwise/pointwise/transposed/etc.) (re.compile(r"(?i)conv(?:\d|_|trans|depth|point|standard)"), "conv"), # normalization family (specifically-named norms BEFORE plain "norm") (re.compile(r"(?i)batch_?norm|layer_?norm|instance_?norm|group_?norm|" r"rms_?norm|frobenius_?norm|l1_?norm|l2_?norm"), "normalization"), # softmax (must precede activation; some activations have 'soft' too) (re.compile(r"(?i)log_?softmax|softmax"), "softmax"), # attention (re.compile(r"(?i)attention"), "attention"), # pooling (re.compile(r"(?i)pooling|max_pool|avg_pool|average_pool|" r"adaptive_pool|lp_pool"), "pooling"), # reduction / scan (cumsum, cumprod, argmax, argmin, sum/mean/max-reduce) (re.compile(r"(?i)(sum|mean|max|min|prod)_reduction|" r"argmax|argmin|cumsum|cumprod|reduce_sum|scan_"), "reduction"), # loss (re.compile(r"(?i)(mse|huber|kldiv|cross_?entropy|triplet|hinge|" r"focal)_?loss"), "loss"), # activation (after softmax, which would otherwise match "soft*") (re.compile(r"(?i)\b(relu|leaky_?relu|sigmoid|tanh|swish|gelu|selu|" r"hard_?sigmoid|soft_?plus|soft_?sign|elu|hard_?tanh|" r"hard_?swish|mish|new_?gelu)\b"), "activation"), # memory movement (re.compile(r"(?i)\b(gather|scatter|embedding|copy|transpose)\b"), "memory_movement"), # elementwise (catch trailing — scalar mul, add, clamp, cast, ...) (re.compile(r"(?i)scalar_multiplication|elementwise|clamp|cast|" r"\b(add|mul|sub|div|scale)\b"), "elementwise"), ] for _pat, _l1 in FILENAME_RULES: assert _l1 in L1_TO_ID, \ f"FILENAME_RULES references unknown L1 {_l1!r} (pattern {_pat.pattern!r})" _KB_L1_BASENAME_RE = re.compile(r"^(\d+)_") # --------------------------------------------------------------------------- # KB filename enumeration (used to disambiguate L1 vs L2 problems sharing # the same leading id, e.g. ``1_Square_matrix_multiplication_.py`` (L1) # vs ``1_Conv2D_ReLU_BiasAdd.py`` (L2)). # --------------------------------------------------------------------------- def _enumerate_kb_stems(level_dir_name: str) -> set[str]: """Return the set of basename stems under ``KernelBench/...//``. Falls back to an empty set when the directory isn't on disk (CPU-only hosts without the KB submodule). Empty sets cause the parser to skip the per-level disambiguation step and route directly to the token rule fallback, which still produces valid output for the L2 cases that matter; the smoke check at the bottom of this file is the canary that actually requires the KB tree to be present. """ repo = Path(__file__).resolve().parents[1] d = repo / "KernelBench" / "KernelBench" / level_dir_name if not d.is_dir(): return set() return {p.stem for p in d.glob("*.py")} _KB_L1_STEMS: set[str] = _enumerate_kb_stems("level1") _KB_L2_STEMS: set[str] = _enumerate_kb_stems("level2") # --------------------------------------------------------------------------- # Public resolution functions # --------------------------------------------------------------------------- def _to_stem(basename: str) -> str: """Normalize an input to a bare stem (no path, no ``.py`` suffix).""" stem = basename if "/" in stem or "\\" in stem: stem = Path(stem).name if stem.endswith(".py"): stem = stem[:-3] return stem def infer_from_filename(basename: str) -> str: """Return the L1 label for a kernel basename. Resolution order: 1. ``ANCHOR_OVERRIDES`` — exact basename match. 2. KB L1 problem-id rule table (basename prefix ``_`` with ``id`` in [1, 100]). 3. ``FILENAME_RULES`` regex fallback. 4. ``"other"``. """ if basename in ANCHOR_OVERRIDES: return ANCHOR_OVERRIDES[basename] stem = _to_stem(basename) if stem in ANCHOR_OVERRIDES: return ANCHOR_OVERRIDES[stem] m = _KB_L1_BASENAME_RE.match(stem) if m: pid = int(m.group(1)) # Only treat the id as a KB-L1 hit when the basename actually # matches a known KB L1 problem — otherwise an L2 problem with # the same id prefix would inherit the L1 problem's label. if pid in _KB_L1_PROBLEM_TO_L1 and (not _KB_L1_STEMS or stem in _KB_L1_STEMS): return _KB_L1_PROBLEM_TO_L1[pid] for pat, l1 in FILENAME_RULES: if pat.search(stem): return l1 return "other" def _tokens_to_ops(stem: str) -> list[tuple[str, str]]: """Parse a CamelCase ``_``-separated stem into a sequence of (L1, L2). Descriptor words ("for", "with", "over", "a", "dimension", "padded", "strided", ...) that aren't keys in ``_OP_TOKEN_TO_L2`` are silently dropped. The empty list signals "no recognised op tokens" so the caller can fall back to ``("other", "other_misc")``. """ parts = stem.split("_") if parts and parts[0].isdigit(): parts = parts[1:] ops: list[tuple[str, str]] = [] for tok in parts: if not tok: continue if tok in _OP_TOKEN_TO_L2: ops.append(_OP_TOKEN_TO_L2[tok]) return ops def parse_l2_sequence(basename: str) -> list[tuple[str, str]]: """Return the (L1, L2) op-sequence implied by an op-sequence basename. Examples: >>> parse_l2_sequence("1_Conv2D_ReLU_BiasAdd.py") [('conv', 'conv_conv2d_standard'), ('activation', 'activation_relu'), ('elementwise', 'elementwise_bias_add')] >>> parse_l2_sequence("99_Matmul_GELU_Softmax.py") [('matmul', 'matmul_gemm'), ('activation', 'activation_gelu'), ('softmax', 'softmax_softmax')] >>> parse_l2_sequence("47_Sum_reduction_over_a_dimension.py") [('reduction', 'reduction_sum')] >>> parse_l2_sequence("vector_add") [('elementwise', 'elementwise_add')] Resolution order: 1. ``ANCHOR_OVERRIDES_L2`` — exact basename match (microbench / megakernel ``phase_*`` / megakernel ``op_*``). 2. KB L1 problem-id table (``_KB_L1_PROBLEM_TO_OPS``) — when the basename is a known L1 problem (so the L2 problem with the same id prefix doesn't shadow it). 3. KB L2 problem-id table (``_KB_L2_PROBLEM_TO_OPS``) — override for L2 problems where the token parser is ambiguous (currently empty). 4. Token rule fallback (``_OP_TOKEN_TO_L2``). 5. ``[("other", "other_misc")]``. """ if basename in ANCHOR_OVERRIDES_L2: return [ANCHOR_OVERRIDES_L2[basename]] stem = _to_stem(basename) if stem in ANCHOR_OVERRIDES_L2: return [ANCHOR_OVERRIDES_L2[stem]] m = _KB_L1_BASENAME_RE.match(stem) pid = int(m.group(1)) if m else None if pid is not None: # Treat as KB L1 only if the basename matches a known L1 stem; # this disambiguates L1 problem 1 (``1_Square_matrix_...``) from # L2 problem 1 (``1_Conv2D_ReLU_BiasAdd``). if pid in _KB_L1_PROBLEM_TO_OPS and ( not _KB_L1_STEMS or stem in _KB_L1_STEMS ): return list(_KB_L1_PROBLEM_TO_OPS[pid]) if pid in _KB_L2_PROBLEM_TO_OPS and ( not _KB_L2_STEMS or stem in _KB_L2_STEMS ): return list(_KB_L2_PROBLEM_TO_OPS[pid]) ops = _tokens_to_ops(stem) if ops: return ops return [("other", "other_misc")] def infer_from_filename_l2(basename: str) -> tuple[str, str]: """Return a single (L1, L2) pair for a kernel basename. L1 problems return their (L1, L2) directly. L2 problems return the *first* op of the parsed sequence — useful for the legacy "one label per trace" code paths in ``build_splits.py`` and the dominant-class heuristic. For per-launch labeling on L2 problems use ``parse_l2_sequence`` and align to the kernel-launch order. """ ops = parse_l2_sequence(basename) if not ops: return ("other", "other_misc") return ops[0] def infer_from_aten(aten_op: str) -> str: """Stub for an aten-op label path. Returns ``"other"`` rather than raising so callers wired in early can keep producing labels without a hard dependency. """ del aten_op return "other" # --------------------------------------------------------------------------- # Smoke checks # --------------------------------------------------------------------------- def _smoke_check_kb_l1() -> tuple[int, int]: """Walk ``KernelBench/KernelBench/level1/`` and report any L1 miss. Returns ``(scanned, fail_count)``. Used by the combined entry point at the bottom of this file to compute a single exit code across L1+L2. """ repo = Path(__file__).resolve().parents[1] l1_dir = repo / "KernelBench" / "KernelBench" / "level1" if not l1_dir.is_dir(): print(f"[smoke L1] KB L1 dir not found at {l1_dir}; " f"skipping coverage check", file=sys.stderr) return 0, 0 files = sorted(p.name for p in l1_dir.glob("*.py")) by_l1: dict[str, list[str]] = {l1: [] for l1 in VOCAB_L1} for name in files: by_l1[infer_from_filename(name)].append(name) n = sum(len(v) for v in by_l1.values()) print(f"[smoke L1] scanned {n} L1 files in {l1_dir}") for l1 in VOCAB_L1: print(f" {l1:<16s} {len(by_l1[l1]):>3d}") other_files = by_l1["other"] if other_files: print("[smoke L1] FAIL — basenames that fell through to 'other':", file=sys.stderr) for fn in other_files: print(f" {fn}", file=sys.stderr) return n, 1 print("[smoke L1] OK — every KB L1 filename resolves to a non-'other' L1") return n, 0 def _smoke_check_kb_l2() -> tuple[int, int]: """Walk ``KernelBench/KernelBench/level2/`` and report any L2 miss. Coverage criterion: every L2 filename resolves to a sequence of one-or-more (L1, L2) pairs with no ``other_misc`` fallthrough. Each op token must produce a recognised pair -- a single ``other_misc`` in any sequence fails the smoke check. Returns ``(scanned, fail_count)``. """ repo = Path(__file__).resolve().parents[1] l2_dir = repo / "KernelBench" / "KernelBench" / "level2" if not l2_dir.is_dir(): print(f"[smoke L2] KB L2 dir not found at {l2_dir}; " f"skipping coverage check", file=sys.stderr) return 0, 0 files = sorted(p.name for p in l2_dir.glob("*.py")) by_l2: dict[str, int] = {l2: 0 for l2 in VOCAB_L2} bad: list[tuple[str, list[tuple[str, str]]]] = [] for name in files: ops = parse_l2_sequence(name) if any(l1 == "other" and l2 == "other_misc" for l1, l2 in ops): bad.append((name, ops)) for _l1, l2 in ops: if l2 in by_l2: by_l2[l2] += 1 n = len(files) print(f"[smoke L2] scanned {n} L2 files in {l2_dir}") # Group counts by L1 family for readability. for l1 in VOCAB_L1: total = sum(by_l2[l2] for l2 in _L2_BY_L1[l1]) print(f" {l1:<16s} {total:>5d} (across " f"{len(_L2_BY_L1[l1])} L2 classes)") if bad: print("[smoke L2] FAIL — L2 problems with at least one unresolved " "token (other_misc):", file=sys.stderr) for fn, ops in bad: print(f" {fn} -> {ops}", file=sys.stderr) return n, 1 print("[smoke L2] OK — every KB L2 filename resolves to a complete " "(L1, L2) sequence with no other_misc fallthrough") return n, 0 def _smoke_check() -> int: """Run both L1 and L2 coverage checks; return 0 iff both pass.""" _, fail_l1 = _smoke_check_kb_l1() _, fail_l2 = _smoke_check_kb_l2() return 1 if (fail_l1 or fail_l2) else 0 if __name__ == "__main__": raise SystemExit(_smoke_check())