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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
SASS-augmented trace dataloader stub.
|
| 4 |
+
|
| 5 |
+
Cross-attention architecture: trace queries, SASS keys/values -> per-timestep
|
| 6 |
+
features.
|
| 7 |
+
|
| 8 |
+
This stub is the data-side contract for that architecture. It loads
|
| 9 |
+
`tensor_input.npz` (the [24, T] ViT input) and `sass_modality.npz` (per-kernel
|
| 10 |
+
[N_pc, F] SASS matrices) for a single motif and yields the tensors a future
|
| 11 |
+
torch `nn.Module` would consume. No torch dependency — this host is CPU-only
|
| 12 |
+
and torch isn't installed; the same shapes carry over to PyTorch one-to-one.
|
| 13 |
+
|
| 14 |
+
Shape contract per sample:
|
| 15 |
+
|
| 16 |
+
trace_input : float32 [C=24, T=512] ViT input image
|
| 17 |
+
regime_family : float32 [T=512, F=4] per-bin one-hot family
|
| 18 |
+
subregime : float32 [T=512, Z=20] multi-hot within family
|
| 19 |
+
structural : float32 [T=512, K=17] per-kernel structural attrs
|
| 20 |
+
boundaries : float32 [T=512] Gaussian-smoothed transition target
|
| 21 |
+
gt_segments : list[(start, end, fam, sub[20], struct[17])] TAS transcript
|
| 22 |
+
workload_l1 : int64 [T=512] per-bin single L1 id (-1 idle)
|
| 23 |
+
workload_l2 : int64 [T=512] per-bin single L2 id (-1 idle)
|
| 24 |
+
workload_l1_multihot : float32 [T=512, 12] per-bin multi-hot L1 (overlap)
|
| 25 |
+
workload_l2_multihot : float32 [T=512, 73] per-bin multi-hot L2 (overlap)
|
| 26 |
+
multihot_n_active : float32 [T=512] # concurrent L1 classes per bin
|
| 27 |
+
mask_any : float32 [T=512] 1 = some kernel runs
|
| 28 |
+
bin_kernel_id : int64 [T=512] which kernel (-1 = idle)
|
| 29 |
+
sass_matrix : float32 [K, N_pc_max, F=9] per-kernel SASS, padded
|
| 30 |
+
sass_pc_mask : float32 [K, N_pc_max] 1 on real PCs, 0 on pad
|
| 31 |
+
|
| 32 |
+
Cross-attention wiring (forward-pass pseudocode in the docstring below):
|
| 33 |
+
Q = trace_patch_embeddings [B, S_q, d] from the ViT trunk
|
| 34 |
+
K = sass_proj(sass_matrix[bin_k]) [B, N_pc, d] per-bin kernel lookup
|
| 35 |
+
V = sass_proj(sass_matrix[bin_k]) [B, N_pc, d]
|
| 36 |
+
attn = softmax(Q K^T / sqrt(d)) * sass_pc_mask
|
| 37 |
+
out = attn @ V [B, S_q, d]
|
| 38 |
+
|
| 39 |
+
The per-bin kernel index is the bridge between the time grid (from nsys
|
| 40 |
+
kernel_intervals) and the SASS matrix store (per-kernel-function). For
|
| 41 |
+
unprofiled bins (`bin_kernel_id == -1`) the convention is to set Q's attention
|
| 42 |
+
output to zero — i.e. the trace-only path is preserved when SASS isn't
|
| 43 |
+
applicable.
|
| 44 |
+
|
| 45 |
+
Usage:
|
| 46 |
+
python tools/sass_dataloader_stub.py kernels/vector_add/_out
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
from __future__ import annotations
|
| 50 |
+
|
| 51 |
+
import argparse
|
| 52 |
+
import sys
|
| 53 |
+
from dataclasses import dataclass
|
| 54 |
+
from pathlib import Path
|
| 55 |
+
from typing import Optional
|
| 56 |
+
|
| 57 |
+
import numpy as np
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@dataclass
|
| 61 |
+
class SASSSample:
|
| 62 |
+
"""One motif's worth of data, in the shape a SASS-augmented ViT consumes."""
|
| 63 |
+
|
| 64 |
+
trace_input: np.ndarray # float32 [C, T] — tensor_input.npz `data`
|
| 65 |
+
counter_names: list[str]
|
| 66 |
+
time_edges_ns: np.ndarray # int64 [T+1]
|
| 67 |
+
regime_family: Optional[np.ndarray] # float32 [T, F=4]
|
| 68 |
+
regime_family_names: Optional[list[str]]
|
| 69 |
+
subregime: Optional[np.ndarray] # float32 [T, Z=20]
|
| 70 |
+
subregime_names: Optional[list[str]]
|
| 71 |
+
subregime_family_idx: Optional[np.ndarray] # int64 [Z]
|
| 72 |
+
structural: Optional[np.ndarray] # float32 [T, K=17]
|
| 73 |
+
structural_names: Optional[list[str]]
|
| 74 |
+
boundaries: Optional[np.ndarray] # float32 [T]
|
| 75 |
+
gt_segments: Optional[np.ndarray] # object [S] of 5-tuples
|
| 76 |
+
mask_any: Optional[np.ndarray] # float32 [T]
|
| 77 |
+
mask_profiled: Optional[np.ndarray] # float32 [T]
|
| 78 |
+
# Single-label + additive multi-hot (overlapping-label) workload targets.
|
| 79 |
+
workload_l1: Optional[np.ndarray] # int64 [T] (-1 = unlabeled)
|
| 80 |
+
workload_l2: Optional[np.ndarray] # int64 [T] (-1 = unlabeled)
|
| 81 |
+
workload_l1_multihot: Optional[np.ndarray] # float32 [T, 12] multi-label head target
|
| 82 |
+
workload_l2_multihot: Optional[np.ndarray] # float32 [T, 73]
|
| 83 |
+
multihot_n_active: Optional[np.ndarray] # float32 [T] # concurrent L1 classes
|
| 84 |
+
mask_multilabel: Optional[np.ndarray] # float32 [T] 1 where >=1 class active
|
| 85 |
+
vocab_l1: Optional[list[str]]
|
| 86 |
+
vocab_l2: Optional[list[str]]
|
| 87 |
+
bin_kernel_id: np.ndarray # int64 [T] — -1 for idle bins
|
| 88 |
+
sass_matrix: np.ndarray # float32 [K, N_pc_max, F]
|
| 89 |
+
sass_pc_mask: np.ndarray # float32 [K, N_pc_max]
|
| 90 |
+
sass_column_names: list[str]
|
| 91 |
+
sass_kernel_names: list[str] # length K (functions, demangled)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _bin_kernel_index(time_edges_ns: np.ndarray,
|
| 95 |
+
kernels: np.ndarray) -> np.ndarray:
|
| 96 |
+
"""For each time bin, return the index (into `kernels`) of the kernel that
|
| 97 |
+
overlaps the bin's center, or -1 if no kernel overlaps.
|
| 98 |
+
|
| 99 |
+
Bins are half-open [edges[t], edges[t+1]); kernel intervals are inclusive.
|
| 100 |
+
"""
|
| 101 |
+
if kernels.size == 0:
|
| 102 |
+
return np.full(time_edges_ns.shape[0] - 1, -1, dtype=np.int64)
|
| 103 |
+
centers = (time_edges_ns[:-1] + time_edges_ns[1:]) // 2
|
| 104 |
+
starts = kernels[:, 0]
|
| 105 |
+
ends = kernels[:, 1]
|
| 106 |
+
idx = np.clip(np.searchsorted(starts, centers, side="right") - 1,
|
| 107 |
+
0, len(kernels) - 1)
|
| 108 |
+
inside = (centers >= starts[idx]) & (centers <= ends[idx])
|
| 109 |
+
return np.where(inside, idx, -1).astype(np.int64)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _bin_kernel_function_index(
|
| 113 |
+
bin_kernel_id: np.ndarray, kernels: np.ndarray,
|
| 114 |
+
sass_kernel_names: list[str],
|
| 115 |
+
nsys_kernel_names: Optional[list[str]],
|
| 116 |
+
launch_function_index: Optional[np.ndarray] = None,
|
| 117 |
+
) -> np.ndarray:
|
| 118 |
+
"""Map per-bin kernel-launch index -> per-bin kernel-function index.
|
| 119 |
+
|
| 120 |
+
SASS matrices are keyed by kernel *function*, not by individual launch.
|
| 121 |
+
Two precomputed inputs let us avoid the legacy "function-0 for every
|
| 122 |
+
active bin" fallback on heterogeneous traces:
|
| 123 |
+
- `launch_function_index[K]`: the per-launch function index already
|
| 124 |
+
baked into `tensor_input.npz` (post-migration). When present, every
|
| 125 |
+
active bin's index is just a gather from this array.
|
| 126 |
+
- `nsys_kernel_names[K]`: per-launch mangled name, used to compute the
|
| 127 |
+
function index from `sass_kernel_names` when no precomputed index is
|
| 128 |
+
attached.
|
| 129 |
+
Final fallback: function-0 for every active bin.
|
| 130 |
+
"""
|
| 131 |
+
T = bin_kernel_id.shape[0]
|
| 132 |
+
out = np.full(T, -1, dtype=np.int64)
|
| 133 |
+
if not sass_kernel_names:
|
| 134 |
+
return out
|
| 135 |
+
if launch_function_index is not None and len(launch_function_index) > 0:
|
| 136 |
+
active = bin_kernel_id >= 0
|
| 137 |
+
if active.any():
|
| 138 |
+
out[active] = launch_function_index[bin_kernel_id[active]]
|
| 139 |
+
return out
|
| 140 |
+
if nsys_kernel_names is None:
|
| 141 |
+
out[bin_kernel_id >= 0] = 0
|
| 142 |
+
return out
|
| 143 |
+
name_to_fn = {n: i for i, n in enumerate(sass_kernel_names)}
|
| 144 |
+
for t in range(T):
|
| 145 |
+
k = int(bin_kernel_id[t])
|
| 146 |
+
if k < 0 or k >= len(nsys_kernel_names):
|
| 147 |
+
continue
|
| 148 |
+
out[t] = name_to_fn.get(nsys_kernel_names[k], -1)
|
| 149 |
+
return out
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _pad_sass_matrices(matrices: list[np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
|
| 153 |
+
"""Stack per-kernel [N_pc_k, F] matrices into one padded [K, N_pc_max, F].
|
| 154 |
+
|
| 155 |
+
Returns (sass_matrix, sass_pc_mask).
|
| 156 |
+
"""
|
| 157 |
+
if not matrices:
|
| 158 |
+
return (np.zeros((0, 0, 0), dtype=np.float32),
|
| 159 |
+
np.zeros((0, 0), dtype=np.float32))
|
| 160 |
+
F = matrices[0].shape[1]
|
| 161 |
+
N_pc_max = max(M.shape[0] for M in matrices)
|
| 162 |
+
K = len(matrices)
|
| 163 |
+
out = np.zeros((K, N_pc_max, F), dtype=np.float32)
|
| 164 |
+
mask = np.zeros((K, N_pc_max), dtype=np.float32)
|
| 165 |
+
for k, M in enumerate(matrices):
|
| 166 |
+
out[k, :M.shape[0]] = M.astype(np.float32)
|
| 167 |
+
mask[k, :M.shape[0]] = 1.0
|
| 168 |
+
return out, mask
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def load_motif(out_dir: Path) -> SASSSample:
|
| 172 |
+
"""Load tensor_input + (optional) labels + sass_modality for one motif."""
|
| 173 |
+
tin_path = out_dir / "input" / "tensor_input.npz"
|
| 174 |
+
sass_path = out_dir / "sass" / "sass_modality.npz"
|
| 175 |
+
if not tin_path.exists():
|
| 176 |
+
raise FileNotFoundError(tin_path)
|
| 177 |
+
if not sass_path.exists():
|
| 178 |
+
raise FileNotFoundError(sass_path)
|
| 179 |
+
|
| 180 |
+
tin = np.load(tin_path, allow_pickle=True)
|
| 181 |
+
trace_input = tin["data"].astype(np.float32)
|
| 182 |
+
counter_names = list(tin["counter_names"])
|
| 183 |
+
edges = tin["time_edges_ns"].astype(np.int64)
|
| 184 |
+
kernels = tin["kernels"].astype(np.int64)
|
| 185 |
+
nsys_kernel_names = (
|
| 186 |
+
list(tin["kernel_names"]) if "kernel_names" in tin.files else None
|
| 187 |
+
)
|
| 188 |
+
launch_function_index = (
|
| 189 |
+
tin["kernel_function_index"].astype(np.int64)
|
| 190 |
+
if "kernel_function_index" in tin.files else None
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
labels_path = out_dir / "labels" / "labels.npz"
|
| 194 |
+
regime_family = subregime = structural = None
|
| 195 |
+
regime_family_names = subregime_names = structural_names = None
|
| 196 |
+
subregime_family_idx = None
|
| 197 |
+
boundaries = None
|
| 198 |
+
gt_segments = None
|
| 199 |
+
mask_any = mask_prof = None
|
| 200 |
+
workload_l1 = workload_l2 = None
|
| 201 |
+
workload_l1_multihot = workload_l2_multihot = None
|
| 202 |
+
multihot_n_active = mask_multilabel = None
|
| 203 |
+
vocab_l1 = vocab_l2 = None
|
| 204 |
+
if labels_path.exists():
|
| 205 |
+
lab = np.load(labels_path, allow_pickle=True)
|
| 206 |
+
# Every label key is loaded present-aware so the loader works across
|
| 207 |
+
# the schema's additive evolution: a labels.npz that lacks a key
|
| 208 |
+
# leaves the corresponding target None instead of raising.
|
| 209 |
+
def _opt(key, cast=None):
|
| 210 |
+
if key not in lab.files:
|
| 211 |
+
return None
|
| 212 |
+
v = lab[key]
|
| 213 |
+
return v.astype(cast) if cast is not None else v
|
| 214 |
+
|
| 215 |
+
regime_family = _opt("regime_family", np.float32)
|
| 216 |
+
regime_family_names = list(lab["regime_family_names"]) \
|
| 217 |
+
if "regime_family_names" in lab.files else None
|
| 218 |
+
subregime = _opt("subregime", np.float32)
|
| 219 |
+
subregime_names = list(lab["subregime_names"]) \
|
| 220 |
+
if "subregime_names" in lab.files else None
|
| 221 |
+
subregime_family_idx = _opt("subregime_family_idx", np.int64)
|
| 222 |
+
structural = _opt("structural", np.float32)
|
| 223 |
+
structural_names = list(lab["structural_names"]) \
|
| 224 |
+
if "structural_names" in lab.files else None
|
| 225 |
+
mask_any = _opt("mask_any_kernel", np.float32)
|
| 226 |
+
mask_prof = _opt("mask_profiled", np.float32)
|
| 227 |
+
boundaries = _opt("boundaries", np.float32)
|
| 228 |
+
if "gt_segments" in lab.files:
|
| 229 |
+
gt_segments = lab["gt_segments"]
|
| 230 |
+
|
| 231 |
+
# Single-label workload ids (the existing softmax-head targets).
|
| 232 |
+
workload_l1 = _opt("workload_l1", np.int64)
|
| 233 |
+
workload_l2 = _opt("workload_l2", np.int64)
|
| 234 |
+
# Additive multi-hot (overlapping-label) tracks — the sigmoid /
|
| 235 |
+
# multi-label head targets. float32 so they drop straight into a
|
| 236 |
+
# BCEWithLogits loss. For the sequential corpus these are the one-hot
|
| 237 |
+
# of workload_l{1,2}; in genuinely fused traces (e.g. a warp-
|
| 238 |
+
# specialized GEMM) a bin can carry >=2 active classes.
|
| 239 |
+
workload_l1_multihot = _opt("workload_l1_multihot", np.float32)
|
| 240 |
+
workload_l2_multihot = _opt("workload_l2_multihot", np.float32)
|
| 241 |
+
multihot_n_active = _opt("multihot_n_active", np.float32)
|
| 242 |
+
if multihot_n_active is not None:
|
| 243 |
+
# multi-label analog of mask_labeled: 1 where >=1 class is active.
|
| 244 |
+
mask_multilabel = (multihot_n_active > 0).astype(np.float32)
|
| 245 |
+
vocab_l1 = list(lab["vocab_l1"]) if "vocab_l1" in lab.files else None
|
| 246 |
+
vocab_l2 = list(lab["vocab_l2"]) if "vocab_l2" in lab.files else None
|
| 247 |
+
|
| 248 |
+
sass = np.load(sass_path, allow_pickle=True)
|
| 249 |
+
sass_matrices = [np.asarray(m) for m in sass["matrices"]]
|
| 250 |
+
sass_kernel_names = list(sass["kernel_names"])
|
| 251 |
+
sass_column_names = list(sass["column_names"])
|
| 252 |
+
sass_matrix, sass_pc_mask = _pad_sass_matrices(sass_matrices)
|
| 253 |
+
|
| 254 |
+
launch_idx = _bin_kernel_index(edges, kernels)
|
| 255 |
+
bin_kernel_id = _bin_kernel_function_index(
|
| 256 |
+
launch_idx, kernels, sass_kernel_names, nsys_kernel_names,
|
| 257 |
+
launch_function_index=launch_function_index,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
return SASSSample(
|
| 261 |
+
trace_input=trace_input,
|
| 262 |
+
counter_names=counter_names,
|
| 263 |
+
time_edges_ns=edges,
|
| 264 |
+
regime_family=regime_family,
|
| 265 |
+
regime_family_names=regime_family_names,
|
| 266 |
+
subregime=subregime,
|
| 267 |
+
subregime_names=subregime_names,
|
| 268 |
+
subregime_family_idx=subregime_family_idx,
|
| 269 |
+
structural=structural,
|
| 270 |
+
structural_names=structural_names,
|
| 271 |
+
boundaries=boundaries,
|
| 272 |
+
gt_segments=gt_segments,
|
| 273 |
+
mask_any=mask_any,
|
| 274 |
+
mask_profiled=mask_prof,
|
| 275 |
+
workload_l1=workload_l1,
|
| 276 |
+
workload_l2=workload_l2,
|
| 277 |
+
workload_l1_multihot=workload_l1_multihot,
|
| 278 |
+
workload_l2_multihot=workload_l2_multihot,
|
| 279 |
+
multihot_n_active=multihot_n_active,
|
| 280 |
+
mask_multilabel=mask_multilabel,
|
| 281 |
+
vocab_l1=vocab_l1,
|
| 282 |
+
vocab_l2=vocab_l2,
|
| 283 |
+
bin_kernel_id=bin_kernel_id,
|
| 284 |
+
sass_matrix=sass_matrix,
|
| 285 |
+
sass_pc_mask=sass_pc_mask,
|
| 286 |
+
sass_column_names=sass_column_names,
|
| 287 |
+
sass_kernel_names=sass_kernel_names,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def cross_attention_shapes_demo(sample: SASSSample,
|
| 292 |
+
d_model: int = 64,
|
| 293 |
+
patch_shape: tuple[int, int] = (4, 16)) -> None:
|
| 294 |
+
"""Print the shapes a forward pass would touch. No actual attention is run."""
|
| 295 |
+
C, T = sample.trace_input.shape
|
| 296 |
+
P_c, P_t = patch_shape
|
| 297 |
+
assert C % P_c == 0 and T % P_t == 0, \
|
| 298 |
+
f"patch {patch_shape} doesn't divide ({C}, {T})"
|
| 299 |
+
n_tokens = (C // P_c) * (T // P_t)
|
| 300 |
+
K, N_pc_max, F = sample.sass_matrix.shape
|
| 301 |
+
|
| 302 |
+
print(f"trace_input {sample.trace_input.shape} dtype={sample.trace_input.dtype}")
|
| 303 |
+
print(f" -> patches ({n_tokens}, {P_c * P_t}) "
|
| 304 |
+
f"= ({C // P_c} * {T // P_t}, {P_c} * {P_t})")
|
| 305 |
+
print(f" -> Q ({n_tokens}, {d_model}) via patch_embed Linear")
|
| 306 |
+
print(f"sass_matrix ({K}, {N_pc_max}, {F})")
|
| 307 |
+
print(f" -> K = V ({K}, {N_pc_max}, {d_model}) via sass_proj Linear")
|
| 308 |
+
print(f"bin_kernel_id {sample.bin_kernel_id.shape} "
|
| 309 |
+
f"range=[{sample.bin_kernel_id.min()}, {sample.bin_kernel_id.max()}]")
|
| 310 |
+
print(f" -> per-token kernel index: ({n_tokens},) "
|
| 311 |
+
f"(replicate the time-bin's kernel across the {C // P_c} channel patches)")
|
| 312 |
+
print(f"attn output ({n_tokens}, {d_model}) "
|
| 313 |
+
f"= softmax(Q K^T / sqrt(d)) @ V, masked by sass_pc_mask")
|
| 314 |
+
|
| 315 |
+
# Multi-label (overlapping-class) head targets, when present.
|
| 316 |
+
if sample.workload_l1_multihot is not None:
|
| 317 |
+
mh1 = sample.workload_l1_multihot
|
| 318 |
+
mh2 = sample.workload_l2_multihot
|
| 319 |
+
na = sample.multihot_n_active
|
| 320 |
+
n_overlap = int((na >= 2).sum()) if na is not None else 0
|
| 321 |
+
print(f"workload_l1_multihot {mh1.shape} dtype={mh1.dtype} "
|
| 322 |
+
f"(sigmoid head target; BCEWithLogits over {mh1.shape[1]} L1 classes)")
|
| 323 |
+
print(f"workload_l2_multihot {mh2.shape} dtype={mh2.dtype} "
|
| 324 |
+
f"({mh2.shape[1]} L2 classes)")
|
| 325 |
+
print(f" -> bins with >=2 concurrent L1 classes: {n_overlap}/{mh1.shape[0]} "
|
| 326 |
+
f"(0 for the sequential corpus; >0 only on fused/overlapping traces)")
|
| 327 |
+
else:
|
| 328 |
+
print("workload_l*_multihot (absent — labels.npz pre-dates the "
|
| 329 |
+
"multi-hot fields; re-run tools/build_labels.py)")
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def main():
|
| 333 |
+
ap = argparse.ArgumentParser(
|
| 334 |
+
description=__doc__,
|
| 335 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 336 |
+
)
|
| 337 |
+
ap.add_argument("out_dir", type=Path)
|
| 338 |
+
ap.add_argument("--d-model", type=int, default=64)
|
| 339 |
+
args = ap.parse_args()
|
| 340 |
+
sample = load_motif(args.out_dir.resolve())
|
| 341 |
+
print(f"motif: {args.out_dir}")
|
| 342 |
+
print(f" counter_names ({len(sample.counter_names)}): "
|
| 343 |
+
f"{sample.counter_names[:3]} ... {sample.counter_names[-2:]}")
|
| 344 |
+
print(f" sass kernel functions ({len(sample.sass_kernel_names)}): "
|
| 345 |
+
f"{sample.sass_kernel_names}")
|
| 346 |
+
print(f" sass columns ({len(sample.sass_column_names)}): "
|
| 347 |
+
f"{sample.sass_column_names}")
|
| 348 |
+
print()
|
| 349 |
+
cross_attention_shapes_demo(sample, d_model=args.d_model)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
if __name__ == "__main__":
|
| 353 |
+
main()
|
tools/workload_taxonomy.py
ADDED
|
@@ -0,0 +1,1023 @@
|
|
|
|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
+
#!/usr/bin/env python3
|
| 2 |
+
"""Single source of truth for the KernelSight workload taxonomy.
|
| 3 |
+
|
| 4 |
+
Defines L1 (12 coarse) + L2 (~73 fine) workload categories, plus the
|
| 5 |
+
8-flag implementation-style ``ATTRIBUTE_FLAGS`` (multi-label) and the 5-class
|
| 6 |
+
``SPATIAL_STATE_VOCAB`` (single-label). L2 derivation lives behind
|
| 7 |
+
``parse_l2_sequence`` and ``infer_from_filename_l2``; per-bin spatial-state
|
| 8 |
+
derivation is out of scope (no fused kernels in the corpus), but the vocab
|
| 9 |
+
is exposed here so downstream label tooling can pin its head.
|
| 10 |
+
|
| 11 |
+
Public surface (consumed by ``tools/build_labels.py``, ``tools/build_splits.py``,
|
| 12 |
+
``tests/test_tensor_invariants.py`` and the KernelBench harness):
|
| 13 |
+
|
| 14 |
+
VOCAB_L1: list[str]
|
| 15 |
+
12 L1 names. Indexes downstream as ``L1_TO_ID``.
|
| 16 |
+
|
| 17 |
+
VOCAB_L2: list[str]
|
| 18 |
+
~73 L2 names. Sorted by ``(l1_index, l2_name)`` — VOCAB_L1's order is
|
| 19 |
+
preserved at the L1 group level, names sort alphabetically inside each
|
| 20 |
+
group. Indexes downstream as ``L2_TO_ID``.
|
| 21 |
+
|
| 22 |
+
L2_PARENT_L1: dict[str, str]
|
| 23 |
+
Each L2 -> its L1 parent. ``L2_PARENT_L1[l2] in L1_TO_ID`` is asserted
|
| 24 |
+
at module import; the hierarchy invariant test in
|
| 25 |
+
``tests/test_tensor_invariants.py`` enforces it per-bin / per-segment.
|
| 26 |
+
|
| 27 |
+
TAXONOMY: dict[str, list[str]]
|
| 28 |
+
L1 -> sorted list of L2 children. Equivalent shape to L2_PARENT_L1
|
| 29 |
+
inverted; kept for callers that want to enumerate by L1.
|
| 30 |
+
|
| 31 |
+
ATTRIBUTE_FLAGS: list[str]
|
| 32 |
+
8 implementation-style multi-label flags
|
| 33 |
+
(sparse / tma / cluster / masked / persistent / vectorized_store /
|
| 34 |
+
atomic_accum / ldgsts). Each is independent — the model side gets a
|
| 35 |
+
binary head per flag.
|
| 36 |
+
|
| 37 |
+
SPATIAL_STATE_VOCAB: list[str]
|
| 38 |
+
5-class spatial-state taxonomy
|
| 39 |
+
(uniform / wavefront_transition / tail_effect / load_imbalanced /
|
| 40 |
+
hotspot). Per-bin ``spatial_state[T]`` derivation is out of scope
|
| 41 |
+
(no fused kernels in the corpus); the vocab is pinned here so the
|
| 42 |
+
model side can structure its head.
|
| 43 |
+
|
| 44 |
+
ANCHOR_OVERRIDES: dict[str, str]
|
| 45 |
+
Exact-basename -> L1. The same entries live in
|
| 46 |
+
``ANCHOR_OVERRIDES_L2`` (with an L2 attached).
|
| 47 |
+
|
| 48 |
+
ANCHOR_OVERRIDES_L2: dict[str, tuple[str, str]]
|
| 49 |
+
Exact-basename -> (L1, L2). Covers:
|
| 50 |
+
* the 5 microbench motif directory names,
|
| 51 |
+
* the 4 outer ``phase_X_*`` NVTX names emitted by the megakernel host,
|
| 52 |
+
* the 4 inner ``op_*`` NVTX names emitted by the megakernel host
|
| 53 |
+
(nested NVTX shape from ``kernels/megakernel/main.cc``).
|
| 54 |
+
|
| 55 |
+
FILENAME_RULES: list[tuple[re.Pattern, str]]
|
| 56 |
+
Regex fallback for L1 inference on basenames that miss
|
| 57 |
+
``ANCHOR_OVERRIDES`` and the KB L1 problem-id table.
|
| 58 |
+
|
| 59 |
+
infer_from_filename(basename: str) -> str
|
| 60 |
+
L1 label resolution entry point. Resolution order:
|
| 61 |
+
1. ``ANCHOR_OVERRIDES``
|
| 62 |
+
2. KB L1 problem-id table (``_KB_L1_PROBLEM_TO_L1``)
|
| 63 |
+
3. ``FILENAME_RULES`` regex fallback
|
| 64 |
+
4. "other"
|
| 65 |
+
|
| 66 |
+
infer_from_filename_l2(basename: str) -> tuple[str, str]
|
| 67 |
+
(L1, L2) label resolution entry point. Resolution order:
|
| 68 |
+
1. ``ANCHOR_OVERRIDES_L2``
|
| 69 |
+
2. KB L1 problem-id table -> ``_KB_L1_PROBLEM_TO_OPS`` (single op)
|
| 70 |
+
3. KB L2 problem-id table -> ``_KB_L2_PROBLEM_TO_OPS`` (override)
|
| 71 |
+
4. Token rule fallback (uses ``_OP_TOKEN_TO_L2`` per CamelCase token)
|
| 72 |
+
5. ``("other", "other_misc")``
|
| 73 |
+
|
| 74 |
+
parse_l2_sequence(basename: str) -> list[tuple[str, str]]
|
| 75 |
+
Sequence-aware version of ``infer_from_filename_l2``. Returns the
|
| 76 |
+
ordered list of (L1, L2) pairs implied by the filename:
|
| 77 |
+
* L1 problems return a length-1 list,
|
| 78 |
+
* L2 problems return a length-N list (one per op token),
|
| 79 |
+
* anchor basenames return a length-1 list,
|
| 80 |
+
* unknown basenames return ``[("other", "other_misc")]``.
|
| 81 |
+
|
| 82 |
+
infer_from_aten(aten_op: str) -> str
|
| 83 |
+
Stub for an aten-op label path. Returns "other".
|
| 84 |
+
|
| 85 |
+
multihot_from_ids(ids, dim: int) -> list[int]
|
| 86 |
+
Canonical multi-hot primitive (OR of one-hots). Ignores ids outside
|
| 87 |
+
``[0, dim)`` (e.g. the -1 unlabeled sentinel), so it subsumes the
|
| 88 |
+
single-label one-hot case. Used by ``tools/build_labels.py`` to build
|
| 89 |
+
the additive ``workload_l1_multihot`` / ``workload_l2_multihot`` tracks.
|
| 90 |
+
|
| 91 |
+
l1_multihot_from_l2_multihot(l2_multihot) -> list[int]
|
| 92 |
+
Project an L2 multi-hot row onto its implied L1 multi-hot row (set the
|
| 93 |
+
``L2_PARENT_L1`` parent of every active L2). Encodes the L1/L2
|
| 94 |
+
hierarchy invariant the CI enforces on the multi-hot tracks.
|
| 95 |
+
|
| 96 |
+
Smoke check: ``python tools/workload_taxonomy.py`` walks both the KB L1 and
|
| 97 |
+
KB L2 directories and reports per-L1 / per-L2 coverage. The target is
|
| 98 |
+
100/100 coverage on both levels with no ``other_misc`` fallthrough.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
from __future__ import annotations
|
| 102 |
+
|
| 103 |
+
import re
|
| 104 |
+
import sys
|
| 105 |
+
from pathlib import Path
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
VOCAB_L1: list[str] = [
|
| 109 |
+
"matmul",
|
| 110 |
+
"conv",
|
| 111 |
+
"activation",
|
| 112 |
+
"normalization",
|
| 113 |
+
"softmax",
|
| 114 |
+
"pooling",
|
| 115 |
+
"reduction",
|
| 116 |
+
"attention",
|
| 117 |
+
"loss",
|
| 118 |
+
"elementwise",
|
| 119 |
+
"memory_movement",
|
| 120 |
+
"other",
|
| 121 |
+
]
|
| 122 |
+
assert len(VOCAB_L1) == 12, "VOCAB_L1 must hold 12 L1 categories"
|
| 123 |
+
assert len(set(VOCAB_L1)) == len(VOCAB_L1), "VOCAB_L1 has duplicate entries"
|
| 124 |
+
|
| 125 |
+
L1_TO_ID: dict[str, int] = {n: i for i, n in enumerate(VOCAB_L1)}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ---------------------------------------------------------------------------
|
| 129 |
+
# L2 taxonomy
|
| 130 |
+
# ---------------------------------------------------------------------------
|
| 131 |
+
|
| 132 |
+
# Per-L1 list of L2 children. Each L2 name is prefixed with its L1 parent
|
| 133 |
+
# for traceability and to make the parent recoverable from the name in
|
| 134 |
+
# emergency debugging. The flattened VOCAB_L2 below is the canonical order
|
| 135 |
+
# downstream code keys against; the dict is the authoring shape.
|
| 136 |
+
_L2_BY_L1: dict[str, list[str]] = {
|
| 137 |
+
"matmul": [
|
| 138 |
+
"matmul_bmm",
|
| 139 |
+
"matmul_gemm",
|
| 140 |
+
"matmul_matvec",
|
| 141 |
+
],
|
| 142 |
+
"conv": [
|
| 143 |
+
"conv_conv1d_standard",
|
| 144 |
+
"conv_conv2d_depthwise",
|
| 145 |
+
"conv_conv2d_pointwise",
|
| 146 |
+
"conv_conv2d_standard",
|
| 147 |
+
"conv_conv3d_standard",
|
| 148 |
+
"conv_convtranspose1d",
|
| 149 |
+
"conv_convtranspose2d",
|
| 150 |
+
"conv_convtranspose3d",
|
| 151 |
+
],
|
| 152 |
+
"activation": [
|
| 153 |
+
"activation_elu",
|
| 154 |
+
"activation_gelu",
|
| 155 |
+
"activation_hardsigmoid",
|
| 156 |
+
"activation_hardswish",
|
| 157 |
+
"activation_hardtanh",
|
| 158 |
+
"activation_leaky_relu",
|
| 159 |
+
"activation_mish",
|
| 160 |
+
"activation_other",
|
| 161 |
+
"activation_relu",
|
| 162 |
+
"activation_selu",
|
| 163 |
+
"activation_sigmoid",
|
| 164 |
+
"activation_softplus",
|
| 165 |
+
"activation_softsign",
|
| 166 |
+
"activation_swish",
|
| 167 |
+
"activation_tanh",
|
| 168 |
+
],
|
| 169 |
+
"normalization": [
|
| 170 |
+
"normalization_batchnorm",
|
| 171 |
+
"normalization_frobeniusnorm",
|
| 172 |
+
"normalization_groupnorm",
|
| 173 |
+
"normalization_instancenorm",
|
| 174 |
+
"normalization_l1norm",
|
| 175 |
+
"normalization_l2norm",
|
| 176 |
+
"normalization_layernorm",
|
| 177 |
+
"normalization_rmsnorm",
|
| 178 |
+
],
|
| 179 |
+
"softmax": [
|
| 180 |
+
"softmax_log_softmax",
|
| 181 |
+
"softmax_logsumexp",
|
| 182 |
+
"softmax_softmax",
|
| 183 |
+
],
|
| 184 |
+
"pooling": [
|
| 185 |
+
"pooling_avg_pool",
|
| 186 |
+
"pooling_global_avg_pool",
|
| 187 |
+
"pooling_max_pool",
|
| 188 |
+
],
|
| 189 |
+
"reduction": [
|
| 190 |
+
"reduction_argmax",
|
| 191 |
+
"reduction_argmin",
|
| 192 |
+
"reduction_cumprod",
|
| 193 |
+
"reduction_cumsum",
|
| 194 |
+
"reduction_max",
|
| 195 |
+
"reduction_mean",
|
| 196 |
+
"reduction_min",
|
| 197 |
+
"reduction_prod",
|
| 198 |
+
"reduction_sum",
|
| 199 |
+
],
|
| 200 |
+
"attention": [
|
| 201 |
+
"attention_scaled_dot_product",
|
| 202 |
+
],
|
| 203 |
+
"loss": [
|
| 204 |
+
"loss_cross_entropy",
|
| 205 |
+
"loss_hinge",
|
| 206 |
+
"loss_huber",
|
| 207 |
+
"loss_kldiv",
|
| 208 |
+
"loss_mse",
|
| 209 |
+
"loss_triplet_margin",
|
| 210 |
+
],
|
| 211 |
+
"elementwise": [
|
| 212 |
+
"elementwise_add",
|
| 213 |
+
"elementwise_bias_add",
|
| 214 |
+
"elementwise_cast",
|
| 215 |
+
"elementwise_clamp",
|
| 216 |
+
"elementwise_div",
|
| 217 |
+
"elementwise_mul",
|
| 218 |
+
"elementwise_residual_add",
|
| 219 |
+
"elementwise_scalar_multiplication",
|
| 220 |
+
"elementwise_scaling",
|
| 221 |
+
"elementwise_sub",
|
| 222 |
+
],
|
| 223 |
+
"memory_movement": [
|
| 224 |
+
"memory_movement_copy",
|
| 225 |
+
"memory_movement_embedding",
|
| 226 |
+
"memory_movement_gather",
|
| 227 |
+
"memory_movement_scatter",
|
| 228 |
+
"memory_movement_transpose",
|
| 229 |
+
],
|
| 230 |
+
"other": [
|
| 231 |
+
"other_dropout",
|
| 232 |
+
"other_misc",
|
| 233 |
+
],
|
| 234 |
+
}
|
| 235 |
+
for _l1, _children in _L2_BY_L1.items():
|
| 236 |
+
assert _l1 in L1_TO_ID, f"_L2_BY_L1 key {_l1!r} is not in VOCAB_L1"
|
| 237 |
+
assert _children == sorted(_children), \
|
| 238 |
+
f"_L2_BY_L1[{_l1!r}] is not sorted alphabetically"
|
| 239 |
+
for _c in _children:
|
| 240 |
+
assert _c.startswith(_l1 + "_"), \
|
| 241 |
+
f"L2 name {_c!r} must be prefixed with its L1 parent {_l1!r}"
|
| 242 |
+
|
| 243 |
+
# Flatten in VOCAB_L1 order so L2 ids cluster by L1 family.
|
| 244 |
+
VOCAB_L2: list[str] = []
|
| 245 |
+
for _l1 in VOCAB_L1:
|
| 246 |
+
VOCAB_L2.extend(_L2_BY_L1[_l1])
|
| 247 |
+
assert len(VOCAB_L2) == len(set(VOCAB_L2)), "VOCAB_L2 has duplicate entries"
|
| 248 |
+
|
| 249 |
+
L2_TO_ID: dict[str, int] = {n: i for i, n in enumerate(VOCAB_L2)}
|
| 250 |
+
|
| 251 |
+
L2_PARENT_L1: dict[str, str] = {l2: _l1
|
| 252 |
+
for _l1, children in _L2_BY_L1.items()
|
| 253 |
+
for l2 in children}
|
| 254 |
+
for _l2, _parent in L2_PARENT_L1.items():
|
| 255 |
+
assert _parent in L1_TO_ID, \
|
| 256 |
+
f"L2_PARENT_L1[{_l2!r}] = {_parent!r} not in VOCAB_L1"
|
| 257 |
+
|
| 258 |
+
# Public alias. ``TAXONOMY[l1]`` yields the sorted L2 child list.
|
| 259 |
+
TAXONOMY: dict[str, list[str]] = {l1: list(_L2_BY_L1[l1]) for l1 in VOCAB_L1}
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
# L2 ops that launch NO device kernel during inference (model.eval()). They
|
| 263 |
+
# appear in problem names / parsed op sequences but produce no observable
|
| 264 |
+
# launch, so ``tools/build_labels.py`` drops them from the op sequence before
|
| 265 |
+
# aligning kernel launches to ops -- otherwise an iter with launches < ops is
|
| 266 |
+
# skipped (e.g. ``66_Matmul_Dropout_Softmax``: 2 launches vs 3 ops) or a real
|
| 267 |
+
# kernel is mislabeled. Extend as new inference-no-op ops appear.
|
| 268 |
+
INFERENCE_NOOP_L2: frozenset[str] = frozenset({"other_dropout"})
|
| 269 |
+
for _l2 in INFERENCE_NOOP_L2:
|
| 270 |
+
assert _l2 in L2_TO_ID, f"INFERENCE_NOOP_L2 entry {_l2!r} not in VOCAB_L2"
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# ---------------------------------------------------------------------------
|
| 274 |
+
# Auxiliary vocabs (attribute flags + spatial state)
|
| 275 |
+
# ---------------------------------------------------------------------------
|
| 276 |
+
|
| 277 |
+
# Multi-label flags describing kernel *implementation style*. Each is a
|
| 278 |
+
# separate binary head on the model side; new variants extend without
|
| 279 |
+
# retraining the L1/L2 heads. Order is fixed: indexing matches the
|
| 280 |
+
# ``attribute_flags[S, 8]`` columns in ``labels.npz`` and the
|
| 281 |
+
# ``EXPECTED_ATTRIBUTE_FLAGS`` invariant in ``tests/test_tensor_invariants.py``.
|
| 282 |
+
ATTRIBUTE_FLAGS: list[str] = [
|
| 283 |
+
"sparse",
|
| 284 |
+
"tma",
|
| 285 |
+
"cluster",
|
| 286 |
+
"masked",
|
| 287 |
+
"persistent",
|
| 288 |
+
"vectorized_store",
|
| 289 |
+
"atomic_accum",
|
| 290 |
+
"ldgsts",
|
| 291 |
+
]
|
| 292 |
+
assert len(ATTRIBUTE_FLAGS) == 8, "ATTRIBUTE_FLAGS must hold exactly 8 flags"
|
| 293 |
+
assert len(set(ATTRIBUTE_FLAGS)) == len(ATTRIBUTE_FLAGS), \
|
| 294 |
+
"ATTRIBUTE_FLAGS has duplicate entries"
|
| 295 |
+
|
| 296 |
+
# Single-label spatial-state classes (5-class). Per-bin derivation is out
|
| 297 |
+
# of scope; the vocab is pinned here so the model side can structure its
|
| 298 |
+
# head.
|
| 299 |
+
SPATIAL_STATE_VOCAB: list[str] = [
|
| 300 |
+
"uniform",
|
| 301 |
+
"wavefront_transition",
|
| 302 |
+
"tail_effect",
|
| 303 |
+
"load_imbalanced",
|
| 304 |
+
"hotspot",
|
| 305 |
+
]
|
| 306 |
+
assert len(SPATIAL_STATE_VOCAB) == 5, \
|
| 307 |
+
"SPATIAL_STATE_VOCAB must hold exactly 5 classes"
|
| 308 |
+
assert len(set(SPATIAL_STATE_VOCAB)) == len(SPATIAL_STATE_VOCAB), \
|
| 309 |
+
"SPATIAL_STATE_VOCAB has duplicate entries"
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# ---------------------------------------------------------------------------
|
| 313 |
+
# Multi-hot helpers (overlapping / concurrent per-bin labels)
|
| 314 |
+
# ---------------------------------------------------------------------------
|
| 315 |
+
#
|
| 316 |
+
# The single-label corpus carries one class id per bin. Genuine concurrency
|
| 317 |
+
# (e.g. a Hopper warp-specialized GEMM whose producer TMA-load phase
|
| 318 |
+
# overlaps its consumer WGMMA phase in wall-clock time) needs >=2 classes
|
| 319 |
+
# active in the same bin. ``multihot_from_ids`` is the canonical primitive
|
| 320 |
+
# used to build the per-bin ``workload_l1_multihot[T, 12]`` /
|
| 321 |
+
# ``workload_l2_multihot[T, 73]`` tracks in ``tools/build_labels.py`` and to
|
| 322 |
+
# inject externally-provided overlapping spans. It is numpy-free so this
|
| 323 |
+
# module keeps its stdlib-only import surface; the label builder does the
|
| 324 |
+
# vectorized construction. ``l1_multihot_from_l2_multihot`` enforces the
|
| 325 |
+
# L1/L2 hierarchy on a multi-hot row the same way ``L2_PARENT_L1`` does for
|
| 326 |
+
# the single-label path.
|
| 327 |
+
|
| 328 |
+
def multihot_from_ids(ids, dim: int) -> list[int]:
|
| 329 |
+
"""Return a length-``dim`` list of 0/1 ints, 1 at each id in ``ids``.
|
| 330 |
+
|
| 331 |
+
The canonical multi-hot primitive (OR of one-hots). ``ids`` may repeat
|
| 332 |
+
(idempotent). Ids outside ``[0, dim)`` -- notably the ``-1`` unlabeled
|
| 333 |
+
sentinel -- are ignored, so:
|
| 334 |
+
|
| 335 |
+
* ``multihot_from_ids([single_label_id], dim)`` is the one-hot of a
|
| 336 |
+
single-label bin (this is why the multi-hot schema subsumes the
|
| 337 |
+
single-label corpus as a degenerate one-hot),
|
| 338 |
+
* ``multihot_from_ids([-1], dim)`` is the all-zero (unlabeled) row,
|
| 339 |
+
* ``multihot_from_ids([a, b], dim)`` is the two-class overlap row.
|
| 340 |
+
"""
|
| 341 |
+
vec = [0] * dim
|
| 342 |
+
for i in ids:
|
| 343 |
+
j = int(i)
|
| 344 |
+
if 0 <= j < dim:
|
| 345 |
+
vec[j] = 1
|
| 346 |
+
return vec
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def l1_multihot_from_l2_multihot(l2_multihot) -> list[int]:
|
| 350 |
+
"""Project an L2 multi-hot row onto its implied L1 multi-hot row.
|
| 351 |
+
|
| 352 |
+
For every active L2 class, its unique L1 parent (``L2_PARENT_L1``) is set
|
| 353 |
+
in the returned ``len(VOCAB_L1)`` vector. This is the hierarchy invariant
|
| 354 |
+
the CI enforces on the multi-hot tracks: ``l2_parent_l1[j]`` must be set
|
| 355 |
+
in L1 wherever L2 ``j`` is set. ``l2_multihot`` is any length-|VOCAB_L2|
|
| 356 |
+
sequence of truthy/falsy values.
|
| 357 |
+
"""
|
| 358 |
+
parents = []
|
| 359 |
+
for j, on in enumerate(l2_multihot):
|
| 360 |
+
if on:
|
| 361 |
+
parents.append(L1_TO_ID[L2_PARENT_L1[VOCAB_L2[j]]])
|
| 362 |
+
return multihot_from_ids(parents, len(VOCAB_L1))
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# ---------------------------------------------------------------------------
|
| 366 |
+
# Anchor overrides (microbench / CUTLASS)
|
| 367 |
+
# ---------------------------------------------------------------------------
|
| 368 |
+
|
| 369 |
+
# basename -> L1. Kept so callers that only need L1 (e.g.
|
| 370 |
+
# ``infer_from_filename``) have a direct lookup.
|
| 371 |
+
ANCHOR_OVERRIDES: dict[str, str] = {
|
| 372 |
+
"vector_add": "elementwise",
|
| 373 |
+
"reduction": "reduction",
|
| 374 |
+
"gather": "memory_movement",
|
| 375 |
+
"scatter": "memory_movement",
|
| 376 |
+
"wgmma": "matmul",
|
| 377 |
+
"cutlass_gemm": "matmul",
|
| 378 |
+
"cutlass_fmha": "attention",
|
| 379 |
+
"cutlass_fp8_gemm": "matmul",
|
| 380 |
+
"cutlass_sparse_gemm": "matmul",
|
| 381 |
+
"cutlass_grouped_gemm": "matmul",
|
| 382 |
+
# Device-marker overlap PoC (WGMMA-dominated GEMM op identity). The anchor
|
| 383 |
+
# is the single-label baseline; the genuine intra-launch phase overlap is
|
| 384 |
+
# OR'd in by the corpus label driver from %globaltimer markers.
|
| 385 |
+
"cutlass_ws_overlap": "matmul",
|
| 386 |
+
}
|
| 387 |
+
for _l1 in ANCHOR_OVERRIDES.values():
|
| 388 |
+
assert _l1 in L1_TO_ID, f"ANCHOR_OVERRIDES references unknown L1 {_l1!r}"
|
| 389 |
+
|
| 390 |
+
# basename -> (L1, L2). Covers the same set as ANCHOR_OVERRIDES. The microbench
|
| 391 |
+
# entries duplicate ANCHOR_OVERRIDES on the L1 axis by construction (asserted
|
| 392 |
+
# below). cutlass_grouped_gemm anchors as matmul_bmm (many small GEMMs scheduled
|
| 393 |
+
# on-device), the other CUTLASS GEMM variants as matmul_gemm.
|
| 394 |
+
ANCHOR_OVERRIDES_L2: dict[str, tuple[str, str]] = {
|
| 395 |
+
"vector_add": ("elementwise", "elementwise_add"),
|
| 396 |
+
"reduction": ("reduction", "reduction_sum"),
|
| 397 |
+
"gather": ("memory_movement", "memory_movement_gather"),
|
| 398 |
+
"scatter": ("memory_movement", "memory_movement_scatter"),
|
| 399 |
+
"wgmma": ("matmul", "matmul_gemm"),
|
| 400 |
+
"cutlass_gemm": ("matmul", "matmul_gemm"),
|
| 401 |
+
"cutlass_fmha": ("attention", "attention_scaled_dot_product"),
|
| 402 |
+
"cutlass_fp8_gemm": ("matmul", "matmul_gemm"),
|
| 403 |
+
"cutlass_sparse_gemm": ("matmul", "matmul_gemm"),
|
| 404 |
+
"cutlass_grouped_gemm": ("matmul", "matmul_bmm"),
|
| 405 |
+
"cutlass_ws_overlap": ("matmul", "matmul_gemm"),
|
| 406 |
+
}
|
| 407 |
+
for _name, (_l1, _l2) in ANCHOR_OVERRIDES_L2.items():
|
| 408 |
+
assert _l1 in L1_TO_ID, \
|
| 409 |
+
f"ANCHOR_OVERRIDES_L2[{_name!r}] L1 {_l1!r} not in VOCAB_L1"
|
| 410 |
+
assert _l2 in L2_TO_ID, \
|
| 411 |
+
f"ANCHOR_OVERRIDES_L2[{_name!r}] L2 {_l2!r} not in VOCAB_L2"
|
| 412 |
+
assert L2_PARENT_L1[_l2] == _l1, \
|
| 413 |
+
f"ANCHOR_OVERRIDES_L2[{_name!r}]: L2 {_l2!r}'s parent " \
|
| 414 |
+
f"{L2_PARENT_L1[_l2]!r} != declared L1 {_l1!r}"
|
| 415 |
+
for _name, _l1 in ANCHOR_OVERRIDES.items():
|
| 416 |
+
assert _name in ANCHOR_OVERRIDES_L2, \
|
| 417 |
+
f"ANCHOR_OVERRIDES_L2 missing {_name!r}"
|
| 418 |
+
assert ANCHOR_OVERRIDES_L2[_name][0] == _l1, \
|
| 419 |
+
f"ANCHOR_OVERRIDES_L2[{_name!r}] L1 axis drifts from ANCHOR_OVERRIDES"
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
# ---------------------------------------------------------------------------
|
| 423 |
+
# KernelBench L1 problem-id rule table
|
| 424 |
+
# ---------------------------------------------------------------------------
|
| 425 |
+
#
|
| 426 |
+
# ``_KB_L1_PROBLEM_TO_OPS`` maps id -> [(L1, L2)] (length 1 since L1
|
| 427 |
+
# problems are single-op). ``_KB_L1_PROBLEM_TO_L1`` is projected from
|
| 428 |
+
# the OPS table for callers that only need L1. The two stay in lockstep
|
| 429 |
+
# -- the assertion at the bottom of this section enforces it.
|
| 430 |
+
|
| 431 |
+
_KB_L1_PROBLEM_TO_OPS: dict[int, list[tuple[str, str]]] = {
|
| 432 |
+
# 1-18 (except 5): matmul variants
|
| 433 |
+
1: [("matmul", "matmul_gemm")],
|
| 434 |
+
2: [("matmul", "matmul_gemm")],
|
| 435 |
+
3: [("matmul", "matmul_bmm")],
|
| 436 |
+
4: [("matmul", "matmul_matvec")],
|
| 437 |
+
5: [("elementwise", "elementwise_scalar_multiplication")],
|
| 438 |
+
6: [("matmul", "matmul_gemm")],
|
| 439 |
+
7: [("matmul", "matmul_gemm")],
|
| 440 |
+
8: [("matmul", "matmul_gemm")],
|
| 441 |
+
9: [("matmul", "matmul_gemm")],
|
| 442 |
+
10: [("matmul", "matmul_bmm")],
|
| 443 |
+
11: [("matmul", "matmul_bmm")],
|
| 444 |
+
12: [("matmul", "matmul_gemm")],
|
| 445 |
+
13: [("matmul", "matmul_gemm")],
|
| 446 |
+
14: [("matmul", "matmul_gemm")],
|
| 447 |
+
15: [("matmul", "matmul_gemm")],
|
| 448 |
+
16: [("matmul", "matmul_gemm")],
|
| 449 |
+
17: [("matmul", "matmul_gemm")],
|
| 450 |
+
18: [("matmul", "matmul_gemm")],
|
| 451 |
+
# 19-32: activation
|
| 452 |
+
19: [("activation", "activation_relu")],
|
| 453 |
+
20: [("activation", "activation_leaky_relu")],
|
| 454 |
+
21: [("activation", "activation_sigmoid")],
|
| 455 |
+
22: [("activation", "activation_tanh")],
|
| 456 |
+
23: [("softmax", "softmax_softmax")],
|
| 457 |
+
24: [("softmax", "softmax_log_softmax")],
|
| 458 |
+
25: [("activation", "activation_swish")],
|
| 459 |
+
26: [("activation", "activation_gelu")],
|
| 460 |
+
27: [("activation", "activation_selu")],
|
| 461 |
+
28: [("activation", "activation_hardsigmoid")],
|
| 462 |
+
29: [("activation", "activation_softplus")],
|
| 463 |
+
30: [("activation", "activation_softsign")],
|
| 464 |
+
31: [("activation", "activation_elu")],
|
| 465 |
+
32: [("activation", "activation_hardtanh")],
|
| 466 |
+
# 33-40: normalization
|
| 467 |
+
33: [("normalization", "normalization_batchnorm")],
|
| 468 |
+
34: [("normalization", "normalization_instancenorm")],
|
| 469 |
+
35: [("normalization", "normalization_groupnorm")],
|
| 470 |
+
36: [("normalization", "normalization_rmsnorm")],
|
| 471 |
+
37: [("normalization", "normalization_frobeniusnorm")],
|
| 472 |
+
38: [("normalization", "normalization_l1norm")],
|
| 473 |
+
39: [("normalization", "normalization_l2norm")],
|
| 474 |
+
40: [("normalization", "normalization_layernorm")],
|
| 475 |
+
# 41-46: pooling
|
| 476 |
+
41: [("pooling", "pooling_max_pool")],
|
| 477 |
+
42: [("pooling", "pooling_max_pool")],
|
| 478 |
+
43: [("pooling", "pooling_max_pool")],
|
| 479 |
+
44: [("pooling", "pooling_avg_pool")],
|
| 480 |
+
45: [("pooling", "pooling_avg_pool")],
|
| 481 |
+
46: [("pooling", "pooling_avg_pool")],
|
| 482 |
+
# 47-49, 51-53: reduction
|
| 483 |
+
47: [("reduction", "reduction_sum")],
|
| 484 |
+
48: [("reduction", "reduction_mean")],
|
| 485 |
+
49: [("reduction", "reduction_max")],
|
| 486 |
+
51: [("reduction", "reduction_argmax")],
|
| 487 |
+
52: [("reduction", "reduction_argmin")],
|
| 488 |
+
53: [("reduction", "reduction_min")],
|
| 489 |
+
# 50, 54-87: conv (mixed 1D/2D/3D, standard / transposed / depthwise /
|
| 490 |
+
# pointwise). Sourced by inspecting
|
| 491 |
+
# ``KernelBench/KernelBench/level1/*.py`` filenames.
|
| 492 |
+
50: [("conv", "conv_conv2d_standard")],
|
| 493 |
+
54: [("conv", "conv_conv3d_standard")],
|
| 494 |
+
55: [("conv", "conv_conv2d_standard")],
|
| 495 |
+
56: [("conv", "conv_conv2d_standard")],
|
| 496 |
+
57: [("conv", "conv_convtranspose2d")],
|
| 497 |
+
58: [("conv", "conv_convtranspose3d")],
|
| 498 |
+
59: [("conv", "conv_conv3d_standard")],
|
| 499 |
+
60: [("conv", "conv_conv3d_standard")],
|
| 500 |
+
61: [("conv", "conv_convtranspose3d")],
|
| 501 |
+
62: [("conv", "conv_conv2d_standard")],
|
| 502 |
+
63: [("conv", "conv_conv2d_standard")],
|
| 503 |
+
64: [("conv", "conv_convtranspose1d")],
|
| 504 |
+
65: [("conv", "conv_convtranspose2d")],
|
| 505 |
+
66: [("conv", "conv_conv3d_standard")],
|
| 506 |
+
67: [("conv", "conv_conv1d_standard")],
|
| 507 |
+
68: [("conv", "conv_convtranspose3d")],
|
| 508 |
+
69: [("conv", "conv_convtranspose2d")],
|
| 509 |
+
70: [("conv", "conv_convtranspose3d")],
|
| 510 |
+
71: [("conv", "conv_convtranspose2d")],
|
| 511 |
+
72: [("conv", "conv_convtranspose3d")],
|
| 512 |
+
73: [("conv", "conv_convtranspose3d")],
|
| 513 |
+
74: [("conv", "conv_convtranspose1d")],
|
| 514 |
+
75: [("conv", "conv_convtranspose2d")],
|
| 515 |
+
76: [("conv", "conv_conv1d_standard")],
|
| 516 |
+
77: [("conv", "conv_convtranspose3d")],
|
| 517 |
+
78: [("conv", "conv_convtranspose2d")],
|
| 518 |
+
79: [("conv", "conv_convtranspose1d")],
|
| 519 |
+
80: [("conv", "conv_conv2d_standard")],
|
| 520 |
+
81: [("conv", "conv_convtranspose2d")],
|
| 521 |
+
82: [("conv", "conv_conv2d_depthwise")],
|
| 522 |
+
83: [("conv", "conv_conv2d_depthwise")],
|
| 523 |
+
84: [("conv", "conv_conv2d_depthwise")],
|
| 524 |
+
85: [("conv", "conv_conv2d_depthwise")],
|
| 525 |
+
# 86 is depthwise-separable (depthwise + pointwise stages); treated as
|
| 526 |
+
# depthwise for L2 labeling purposes since the depthwise stage carries
|
| 527 |
+
# the dominant compute pattern.
|
| 528 |
+
86: [("conv", "conv_conv2d_depthwise")],
|
| 529 |
+
87: [("conv", "conv_conv2d_pointwise")],
|
| 530 |
+
# 88: GELU variant (MinGPT's new_gelu polynomial); collapses to gelu.
|
| 531 |
+
88: [("activation", "activation_gelu")],
|
| 532 |
+
# 89-93: cumsum / cumprod variants.
|
| 533 |
+
89: [("reduction", "reduction_cumsum")],
|
| 534 |
+
90: [("reduction", "reduction_cumprod")],
|
| 535 |
+
91: [("reduction", "reduction_cumsum")],
|
| 536 |
+
92: [("reduction", "reduction_cumsum")],
|
| 537 |
+
93: [("reduction", "reduction_cumsum")],
|
| 538 |
+
# 94-100: losses + attention.
|
| 539 |
+
94: [("loss", "loss_mse")],
|
| 540 |
+
95: [("loss", "loss_cross_entropy")],
|
| 541 |
+
96: [("loss", "loss_huber")],
|
| 542 |
+
97: [("attention", "attention_scaled_dot_product")],
|
| 543 |
+
98: [("loss", "loss_kldiv")],
|
| 544 |
+
99: [("loss", "loss_triplet_margin")],
|
| 545 |
+
100: [("loss", "loss_hinge")],
|
| 546 |
+
}
|
| 547 |
+
assert len(_KB_L1_PROBLEM_TO_OPS) == 100, \
|
| 548 |
+
f"KB L1 OPS table has {len(_KB_L1_PROBLEM_TO_OPS)} entries, expected 100"
|
| 549 |
+
for _pid, _ops in _KB_L1_PROBLEM_TO_OPS.items():
|
| 550 |
+
assert len(_ops) == 1, \
|
| 551 |
+
f"KB L1 problem {_pid} has {len(_ops)} ops, expected 1"
|
| 552 |
+
_l1, _l2 = _ops[0]
|
| 553 |
+
assert _l1 in L1_TO_ID, \
|
| 554 |
+
f"KB L1 problem {_pid} -> L1 {_l1!r} not in VOCAB_L1"
|
| 555 |
+
assert _l2 in L2_TO_ID, \
|
| 556 |
+
f"KB L1 problem {_pid} -> L2 {_l2!r} not in VOCAB_L2"
|
| 557 |
+
assert L2_PARENT_L1[_l2] == _l1, \
|
| 558 |
+
f"KB L1 problem {_pid}: L2 {_l2!r} parent " \
|
| 559 |
+
f"{L2_PARENT_L1[_l2]!r} != declared L1 {_l1!r}"
|
| 560 |
+
|
| 561 |
+
# ``_KB_L1_PROBLEM_TO_L1`` projected from the OPS table so
|
| 562 |
+
# ``infer_from_filename`` (L1-only entry point) continues to work.
|
| 563 |
+
_KB_L1_PROBLEM_TO_L1: dict[int, str] = {
|
| 564 |
+
pid: ops[0][0] for pid, ops in _KB_L1_PROBLEM_TO_OPS.items()
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
# ---------------------------------------------------------------------------
|
| 569 |
+
# KernelBench L2 problem-id override table
|
| 570 |
+
# ---------------------------------------------------------------------------
|
| 571 |
+
#
|
| 572 |
+
# Token-rule fallback (``_OP_TOKEN_TO_L2``) handles every L2 problem on
|
| 573 |
+
# disk today. This table is reserved for problems where the parser is
|
| 574 |
+
# ambiguous; it is currently empty and the smoke check at the bottom
|
| 575 |
+
# of the file fails loudly if a token can't be resolved.
|
| 576 |
+
_KB_L2_PROBLEM_TO_OPS: dict[int, list[tuple[str, str]]] = {}
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
# ---------------------------------------------------------------------------
|
| 580 |
+
# Token rule fallback for L2 problem op sequences
|
| 581 |
+
# ---------------------------------------------------------------------------
|
| 582 |
+
|
| 583 |
+
# Tokens are extracted by splitting the basename on ``_`` and dropping the
|
| 584 |
+
# leading numeric id and a trailing ``.py``. Each CamelCase / mixed-case
|
| 585 |
+
# token maps to a single (L1, L2) pair; descriptor words like "for",
|
| 586 |
+
# "with", "over", "a", "dimension" don't appear here and are silently
|
| 587 |
+
# skipped by ``_tokens_to_ops``.
|
| 588 |
+
#
|
| 589 |
+
# Sources:
|
| 590 |
+
# * KernelBench/KernelBench/level2/*.py — 100 op-sequence filenames.
|
| 591 |
+
# * KernelBench/KernelBench/level1/*.py — 100 single-op filenames (the
|
| 592 |
+
# L1 problem-id table above takes precedence, but the rules cover
|
| 593 |
+
# ``Argmax``/``Argmin``/``Cumsum``/``Cumprod``/``MSELoss``/... for
|
| 594 |
+
# defensive resolution when the id table misses).
|
| 595 |
+
_OP_TOKEN_TO_L2: dict[str, tuple[str, str]] = {
|
| 596 |
+
# ---- conv ----
|
| 597 |
+
"Conv2D": ("conv", "conv_conv2d_standard"),
|
| 598 |
+
"Conv2d": ("conv", "conv_conv2d_standard"),
|
| 599 |
+
"Conv3d": ("conv", "conv_conv3d_standard"),
|
| 600 |
+
"Conv1d": ("conv", "conv_conv1d_standard"),
|
| 601 |
+
"ConvTranspose2d": ("conv", "conv_convtranspose2d"),
|
| 602 |
+
"ConvTranspose3d": ("conv", "conv_convtranspose3d"),
|
| 603 |
+
"ConvTranspose1d": ("conv", "conv_convtranspose1d"),
|
| 604 |
+
# ---- matmul ----
|
| 605 |
+
"Matmul": ("matmul", "matmul_gemm"),
|
| 606 |
+
"MatMul": ("matmul", "matmul_gemm"),
|
| 607 |
+
"Gemm": ("matmul", "matmul_gemm"),
|
| 608 |
+
"GEMM": ("matmul", "matmul_gemm"),
|
| 609 |
+
"BMM": ("matmul", "matmul_bmm"),
|
| 610 |
+
"Bmm": ("matmul", "matmul_bmm"),
|
| 611 |
+
# ---- activation ----
|
| 612 |
+
"ReLU": ("activation", "activation_relu"),
|
| 613 |
+
"LeakyReLU": ("activation", "activation_leaky_relu"),
|
| 614 |
+
"Sigmoid": ("activation", "activation_sigmoid"),
|
| 615 |
+
"Tanh": ("activation", "activation_tanh"),
|
| 616 |
+
"Swish": ("activation", "activation_swish"),
|
| 617 |
+
"GELU": ("activation", "activation_gelu"),
|
| 618 |
+
"SELU": ("activation", "activation_selu"),
|
| 619 |
+
"HardSigmoid": ("activation", "activation_hardsigmoid"),
|
| 620 |
+
"HardSwish": ("activation", "activation_hardswish"),
|
| 621 |
+
"HardTanh": ("activation", "activation_hardtanh"),
|
| 622 |
+
"Hardtanh": ("activation", "activation_hardtanh"),
|
| 623 |
+
"Softplus": ("activation", "activation_softplus"),
|
| 624 |
+
"Softsign": ("activation", "activation_softsign"),
|
| 625 |
+
"ELU": ("activation", "activation_elu"),
|
| 626 |
+
"Mish": ("activation", "activation_mish"),
|
| 627 |
+
"NewGelu": ("activation", "activation_gelu"),
|
| 628 |
+
"MinGPTNewGelu": ("activation", "activation_gelu"),
|
| 629 |
+
# Generic "Activation" token (KB L2 problem 52). Mapped to
|
| 630 |
+
# activation_other so the L1 family is still recoverable without
|
| 631 |
+
# claiming a specific activation function.
|
| 632 |
+
"Activation": ("activation", "activation_other"),
|
| 633 |
+
# ---- softmax-family ----
|
| 634 |
+
"Softmax": ("softmax", "softmax_softmax"),
|
| 635 |
+
"LogSoftmax": ("softmax", "softmax_log_softmax"),
|
| 636 |
+
"LogSumExp": ("softmax", "softmax_logsumexp"),
|
| 637 |
+
# ---- pooling ----
|
| 638 |
+
"MaxPool": ("pooling", "pooling_max_pool"),
|
| 639 |
+
"AvgPool": ("pooling", "pooling_avg_pool"),
|
| 640 |
+
"GlobalAvgPool": ("pooling", "pooling_global_avg_pool"),
|
| 641 |
+
# ---- normalization ----
|
| 642 |
+
"BatchNorm": ("normalization", "normalization_batchnorm"),
|
| 643 |
+
"LayerNorm": ("normalization", "normalization_layernorm"),
|
| 644 |
+
"GroupNorm": ("normalization", "normalization_groupnorm"),
|
| 645 |
+
"InstanceNorm": ("normalization", "normalization_instancenorm"),
|
| 646 |
+
"RMSNorm": ("normalization", "normalization_rmsnorm"),
|
| 647 |
+
"FrobeniusNorm": ("normalization", "normalization_frobeniusnorm"),
|
| 648 |
+
"L1Norm": ("normalization", "normalization_l1norm"),
|
| 649 |
+
"L2Norm": ("normalization", "normalization_l2norm"),
|
| 650 |
+
# ---- reduction ----
|
| 651 |
+
# ``Sum``/``Mean``/``Max``/``Min`` in L2 filenames are reduction
|
| 652 |
+
# operations (e.g. ``x = torch.sum(x, dim=1, keepdim=True)``).
|
| 653 |
+
# Elementwise *addition* uses the ``Add`` token instead, so the
|
| 654 |
+
# ambiguity is resolved by token choice.
|
| 655 |
+
"Sum": ("reduction", "reduction_sum"),
|
| 656 |
+
"Mean": ("reduction", "reduction_mean"),
|
| 657 |
+
"Max": ("reduction", "reduction_max"),
|
| 658 |
+
"Min": ("reduction", "reduction_min"),
|
| 659 |
+
"Prod": ("reduction", "reduction_prod"),
|
| 660 |
+
"Argmax": ("reduction", "reduction_argmax"),
|
| 661 |
+
"Argmin": ("reduction", "reduction_argmin"),
|
| 662 |
+
"Cumsum": ("reduction", "reduction_cumsum"),
|
| 663 |
+
"cumsum": ("reduction", "reduction_cumsum"),
|
| 664 |
+
"Cumprod": ("reduction", "reduction_cumprod"),
|
| 665 |
+
"cumprod": ("reduction", "reduction_cumprod"),
|
| 666 |
+
# ---- attention ----
|
| 667 |
+
"ScaledDotProductAttention": ("attention", "attention_scaled_dot_product"),
|
| 668 |
+
# ---- loss ----
|
| 669 |
+
"MSELoss": ("loss", "loss_mse"),
|
| 670 |
+
"CrossEntropyLoss": ("loss", "loss_cross_entropy"),
|
| 671 |
+
"HuberLoss": ("loss", "loss_huber"),
|
| 672 |
+
"KLDivLoss": ("loss", "loss_kldiv"),
|
| 673 |
+
"TripletMarginLoss": ("loss", "loss_triplet_margin"),
|
| 674 |
+
"HingeLoss": ("loss", "loss_hinge"),
|
| 675 |
+
# ---- elementwise ----
|
| 676 |
+
"Add": ("elementwise", "elementwise_add"),
|
| 677 |
+
"Multiply": ("elementwise", "elementwise_mul"),
|
| 678 |
+
"Mul": ("elementwise", "elementwise_mul"),
|
| 679 |
+
"Divide": ("elementwise", "elementwise_div"),
|
| 680 |
+
"Div": ("elementwise", "elementwise_div"),
|
| 681 |
+
"Subtract": ("elementwise", "elementwise_sub"),
|
| 682 |
+
"Sub": ("elementwise", "elementwise_sub"),
|
| 683 |
+
"Clamp": ("elementwise", "elementwise_clamp"),
|
| 684 |
+
"Scale": ("elementwise", "elementwise_scaling"),
|
| 685 |
+
"Scaling": ("elementwise", "elementwise_scaling"),
|
| 686 |
+
"BiasAdd": ("elementwise", "elementwise_bias_add"),
|
| 687 |
+
"ResidualAdd": ("elementwise", "elementwise_residual_add"),
|
| 688 |
+
"Cast": ("elementwise", "elementwise_cast"),
|
| 689 |
+
# ---- memory_movement (none of the KB L2 problems exercise these, but
|
| 690 |
+
# the table covers ANCHOR_OVERRIDES_L2 names + future motifs)
|
| 691 |
+
"Gather": ("memory_movement", "memory_movement_gather"),
|
| 692 |
+
"Scatter": ("memory_movement", "memory_movement_scatter"),
|
| 693 |
+
"Embedding": ("memory_movement", "memory_movement_embedding"),
|
| 694 |
+
"Copy": ("memory_movement", "memory_movement_copy"),
|
| 695 |
+
"Transpose": ("memory_movement", "memory_movement_transpose"),
|
| 696 |
+
# ---- other ----
|
| 697 |
+
"Dropout": ("other", "other_dropout"),
|
| 698 |
+
}
|
| 699 |
+
for _tok, (_l1, _l2) in _OP_TOKEN_TO_L2.items():
|
| 700 |
+
assert _l1 in L1_TO_ID, \
|
| 701 |
+
f"_OP_TOKEN_TO_L2[{_tok!r}] L1 {_l1!r} not in VOCAB_L1"
|
| 702 |
+
assert _l2 in L2_TO_ID, \
|
| 703 |
+
f"_OP_TOKEN_TO_L2[{_tok!r}] L2 {_l2!r} not in VOCAB_L2"
|
| 704 |
+
assert L2_PARENT_L1[_l2] == _l1, \
|
| 705 |
+
f"_OP_TOKEN_TO_L2[{_tok!r}]: L2 {_l2!r} parent " \
|
| 706 |
+
f"{L2_PARENT_L1[_l2]!r} != declared L1 {_l1!r}"
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
# ---------------------------------------------------------------------------
|
| 710 |
+
# Regex fallback (L1 inference for newly-added basenames)
|
| 711 |
+
# ---------------------------------------------------------------------------
|
| 712 |
+
|
| 713 |
+
FILENAME_RULES: list[tuple[re.Pattern, str]] = [
|
| 714 |
+
# matmul family
|
| 715 |
+
(re.compile(r"(?i)matmul|gemm|matrix_multiplication|matrix_vector"), "matmul"),
|
| 716 |
+
# conv family (depthwise/pointwise/transposed/etc.)
|
| 717 |
+
(re.compile(r"(?i)conv(?:\d|_|trans|depth|point|standard)"), "conv"),
|
| 718 |
+
# normalization family (specifically-named norms BEFORE plain "norm")
|
| 719 |
+
(re.compile(r"(?i)batch_?norm|layer_?norm|instance_?norm|group_?norm|"
|
| 720 |
+
r"rms_?norm|frobenius_?norm|l1_?norm|l2_?norm"), "normalization"),
|
| 721 |
+
# softmax (must precede activation; some activations have 'soft' too)
|
| 722 |
+
(re.compile(r"(?i)log_?softmax|softmax"), "softmax"),
|
| 723 |
+
# attention
|
| 724 |
+
(re.compile(r"(?i)attention"), "attention"),
|
| 725 |
+
# pooling
|
| 726 |
+
(re.compile(r"(?i)pooling|max_pool|avg_pool|average_pool|"
|
| 727 |
+
r"adaptive_pool|lp_pool"), "pooling"),
|
| 728 |
+
# reduction / scan (cumsum, cumprod, argmax, argmin, sum/mean/max-reduce)
|
| 729 |
+
(re.compile(r"(?i)(sum|mean|max|min|prod)_reduction|"
|
| 730 |
+
r"argmax|argmin|cumsum|cumprod|reduce_sum|scan_"), "reduction"),
|
| 731 |
+
# loss
|
| 732 |
+
(re.compile(r"(?i)(mse|huber|kldiv|cross_?entropy|triplet|hinge|"
|
| 733 |
+
r"focal)_?loss"), "loss"),
|
| 734 |
+
# activation (after softmax, which would otherwise match "soft*")
|
| 735 |
+
(re.compile(r"(?i)\b(relu|leaky_?relu|sigmoid|tanh|swish|gelu|selu|"
|
| 736 |
+
r"hard_?sigmoid|soft_?plus|soft_?sign|elu|hard_?tanh|"
|
| 737 |
+
r"hard_?swish|mish|new_?gelu)\b"), "activation"),
|
| 738 |
+
# memory movement
|
| 739 |
+
(re.compile(r"(?i)\b(gather|scatter|embedding|copy|transpose)\b"), "memory_movement"),
|
| 740 |
+
# elementwise (catch trailing — scalar mul, add, clamp, cast, ...)
|
| 741 |
+
(re.compile(r"(?i)scalar_multiplication|elementwise|clamp|cast|"
|
| 742 |
+
r"\b(add|mul|sub|div|scale)\b"), "elementwise"),
|
| 743 |
+
]
|
| 744 |
+
for _pat, _l1 in FILENAME_RULES:
|
| 745 |
+
assert _l1 in L1_TO_ID, \
|
| 746 |
+
f"FILENAME_RULES references unknown L1 {_l1!r} (pattern {_pat.pattern!r})"
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
_KB_L1_BASENAME_RE = re.compile(r"^(\d+)_")
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
# ---------------------------------------------------------------------------
|
| 753 |
+
# KB filename enumeration (used to disambiguate L1 vs L2 problems sharing
|
| 754 |
+
# the same leading id, e.g. ``1_Square_matrix_multiplication_.py`` (L1)
|
| 755 |
+
# vs ``1_Conv2D_ReLU_BiasAdd.py`` (L2)).
|
| 756 |
+
# ---------------------------------------------------------------------------
|
| 757 |
+
|
| 758 |
+
def _enumerate_kb_stems(level_dir_name: str) -> set[str]:
|
| 759 |
+
"""Return the set of basename stems under ``KernelBench/.../<level>/``.
|
| 760 |
+
|
| 761 |
+
Falls back to an empty set when the directory isn't on disk (CPU-only
|
| 762 |
+
hosts without the KB submodule). Empty sets cause the parser to skip
|
| 763 |
+
the per-level disambiguation step and route directly to the token rule
|
| 764 |
+
fallback, which still produces valid output for the L2 cases that
|
| 765 |
+
matter; the smoke check at the bottom of this file is the canary that
|
| 766 |
+
actually requires the KB tree to be present.
|
| 767 |
+
"""
|
| 768 |
+
repo = Path(__file__).resolve().parents[1]
|
| 769 |
+
d = repo / "KernelBench" / "KernelBench" / level_dir_name
|
| 770 |
+
if not d.is_dir():
|
| 771 |
+
return set()
|
| 772 |
+
return {p.stem for p in d.glob("*.py")}
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
_KB_L1_STEMS: set[str] = _enumerate_kb_stems("level1")
|
| 776 |
+
_KB_L2_STEMS: set[str] = _enumerate_kb_stems("level2")
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
# ---------------------------------------------------------------------------
|
| 780 |
+
# Public resolution functions
|
| 781 |
+
# ---------------------------------------------------------------------------
|
| 782 |
+
|
| 783 |
+
def _to_stem(basename: str) -> str:
|
| 784 |
+
"""Normalize an input to a bare stem (no path, no ``.py`` suffix)."""
|
| 785 |
+
stem = basename
|
| 786 |
+
if "/" in stem or "\\" in stem:
|
| 787 |
+
stem = Path(stem).name
|
| 788 |
+
if stem.endswith(".py"):
|
| 789 |
+
stem = stem[:-3]
|
| 790 |
+
return stem
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def infer_from_filename(basename: str) -> str:
|
| 794 |
+
"""Return the L1 label for a kernel basename.
|
| 795 |
+
|
| 796 |
+
Resolution order:
|
| 797 |
+
|
| 798 |
+
1. ``ANCHOR_OVERRIDES`` — exact basename match.
|
| 799 |
+
2. KB L1 problem-id rule table (basename prefix ``<id>_`` with
|
| 800 |
+
``id`` in [1, 100]).
|
| 801 |
+
3. ``FILENAME_RULES`` regex fallback.
|
| 802 |
+
4. ``"other"``.
|
| 803 |
+
"""
|
| 804 |
+
if basename in ANCHOR_OVERRIDES:
|
| 805 |
+
return ANCHOR_OVERRIDES[basename]
|
| 806 |
+
|
| 807 |
+
stem = _to_stem(basename)
|
| 808 |
+
if stem in ANCHOR_OVERRIDES:
|
| 809 |
+
return ANCHOR_OVERRIDES[stem]
|
| 810 |
+
|
| 811 |
+
m = _KB_L1_BASENAME_RE.match(stem)
|
| 812 |
+
if m:
|
| 813 |
+
pid = int(m.group(1))
|
| 814 |
+
# Only treat the id as a KB-L1 hit when the basename actually
|
| 815 |
+
# matches a known KB L1 problem — otherwise an L2 problem with
|
| 816 |
+
# the same id prefix would inherit the L1 problem's label.
|
| 817 |
+
if pid in _KB_L1_PROBLEM_TO_L1 and (not _KB_L1_STEMS or stem in _KB_L1_STEMS):
|
| 818 |
+
return _KB_L1_PROBLEM_TO_L1[pid]
|
| 819 |
+
|
| 820 |
+
for pat, l1 in FILENAME_RULES:
|
| 821 |
+
if pat.search(stem):
|
| 822 |
+
return l1
|
| 823 |
+
|
| 824 |
+
return "other"
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def _tokens_to_ops(stem: str) -> list[tuple[str, str]]:
|
| 828 |
+
"""Parse a CamelCase ``_``-separated stem into a sequence of (L1, L2).
|
| 829 |
+
|
| 830 |
+
Descriptor words ("for", "with", "over", "a", "dimension", "padded",
|
| 831 |
+
"strided", ...) that aren't keys in ``_OP_TOKEN_TO_L2`` are silently
|
| 832 |
+
dropped. The empty list signals "no recognised op tokens" so the
|
| 833 |
+
caller can fall back to ``("other", "other_misc")``.
|
| 834 |
+
"""
|
| 835 |
+
parts = stem.split("_")
|
| 836 |
+
if parts and parts[0].isdigit():
|
| 837 |
+
parts = parts[1:]
|
| 838 |
+
ops: list[tuple[str, str]] = []
|
| 839 |
+
for tok in parts:
|
| 840 |
+
if not tok:
|
| 841 |
+
continue
|
| 842 |
+
if tok in _OP_TOKEN_TO_L2:
|
| 843 |
+
ops.append(_OP_TOKEN_TO_L2[tok])
|
| 844 |
+
return ops
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def parse_l2_sequence(basename: str) -> list[tuple[str, str]]:
|
| 848 |
+
"""Return the (L1, L2) op-sequence implied by an op-sequence basename.
|
| 849 |
+
|
| 850 |
+
Examples:
|
| 851 |
+
|
| 852 |
+
>>> parse_l2_sequence("1_Conv2D_ReLU_BiasAdd.py")
|
| 853 |
+
[('conv', 'conv_conv2d_standard'),
|
| 854 |
+
('activation', 'activation_relu'),
|
| 855 |
+
('elementwise', 'elementwise_bias_add')]
|
| 856 |
+
>>> parse_l2_sequence("99_Matmul_GELU_Softmax.py")
|
| 857 |
+
[('matmul', 'matmul_gemm'),
|
| 858 |
+
('activation', 'activation_gelu'),
|
| 859 |
+
('softmax', 'softmax_softmax')]
|
| 860 |
+
>>> parse_l2_sequence("47_Sum_reduction_over_a_dimension.py")
|
| 861 |
+
[('reduction', 'reduction_sum')]
|
| 862 |
+
>>> parse_l2_sequence("vector_add")
|
| 863 |
+
[('elementwise', 'elementwise_add')]
|
| 864 |
+
|
| 865 |
+
Resolution order:
|
| 866 |
+
|
| 867 |
+
1. ``ANCHOR_OVERRIDES_L2`` — exact basename match (microbench /
|
| 868 |
+
megakernel ``phase_*`` / megakernel ``op_*``).
|
| 869 |
+
2. KB L1 problem-id table (``_KB_L1_PROBLEM_TO_OPS``) — when the
|
| 870 |
+
basename is a known L1 problem (so the L2 problem with the same
|
| 871 |
+
id prefix doesn't shadow it).
|
| 872 |
+
3. KB L2 problem-id table (``_KB_L2_PROBLEM_TO_OPS``) — override for
|
| 873 |
+
L2 problems where the token parser is ambiguous (currently empty).
|
| 874 |
+
4. Token rule fallback (``_OP_TOKEN_TO_L2``).
|
| 875 |
+
5. ``[("other", "other_misc")]``.
|
| 876 |
+
"""
|
| 877 |
+
if basename in ANCHOR_OVERRIDES_L2:
|
| 878 |
+
return [ANCHOR_OVERRIDES_L2[basename]]
|
| 879 |
+
stem = _to_stem(basename)
|
| 880 |
+
if stem in ANCHOR_OVERRIDES_L2:
|
| 881 |
+
return [ANCHOR_OVERRIDES_L2[stem]]
|
| 882 |
+
|
| 883 |
+
m = _KB_L1_BASENAME_RE.match(stem)
|
| 884 |
+
pid = int(m.group(1)) if m else None
|
| 885 |
+
if pid is not None:
|
| 886 |
+
# Treat as KB L1 only if the basename matches a known L1 stem;
|
| 887 |
+
# this disambiguates L1 problem 1 (``1_Square_matrix_...``) from
|
| 888 |
+
# L2 problem 1 (``1_Conv2D_ReLU_BiasAdd``).
|
| 889 |
+
if pid in _KB_L1_PROBLEM_TO_OPS and (
|
| 890 |
+
not _KB_L1_STEMS or stem in _KB_L1_STEMS
|
| 891 |
+
):
|
| 892 |
+
return list(_KB_L1_PROBLEM_TO_OPS[pid])
|
| 893 |
+
if pid in _KB_L2_PROBLEM_TO_OPS and (
|
| 894 |
+
not _KB_L2_STEMS or stem in _KB_L2_STEMS
|
| 895 |
+
):
|
| 896 |
+
return list(_KB_L2_PROBLEM_TO_OPS[pid])
|
| 897 |
+
|
| 898 |
+
ops = _tokens_to_ops(stem)
|
| 899 |
+
if ops:
|
| 900 |
+
return ops
|
| 901 |
+
|
| 902 |
+
return [("other", "other_misc")]
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
def infer_from_filename_l2(basename: str) -> tuple[str, str]:
|
| 906 |
+
"""Return a single (L1, L2) pair for a kernel basename.
|
| 907 |
+
|
| 908 |
+
L1 problems return their (L1, L2) directly. L2 problems return the
|
| 909 |
+
*first* op of the parsed sequence — useful for the legacy "one label
|
| 910 |
+
per trace" code paths in ``build_splits.py`` and the dominant-class
|
| 911 |
+
heuristic. For per-launch labeling on L2 problems use
|
| 912 |
+
``parse_l2_sequence`` and align to the kernel-launch order.
|
| 913 |
+
"""
|
| 914 |
+
ops = parse_l2_sequence(basename)
|
| 915 |
+
if not ops:
|
| 916 |
+
return ("other", "other_misc")
|
| 917 |
+
return ops[0]
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def infer_from_aten(aten_op: str) -> str:
|
| 921 |
+
"""Stub for an aten-op label path.
|
| 922 |
+
|
| 923 |
+
Returns ``"other"`` rather than raising so callers wired in early can
|
| 924 |
+
keep producing labels without a hard dependency.
|
| 925 |
+
"""
|
| 926 |
+
del aten_op
|
| 927 |
+
return "other"
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
# ---------------------------------------------------------------------------
|
| 931 |
+
# Smoke checks
|
| 932 |
+
# ---------------------------------------------------------------------------
|
| 933 |
+
|
| 934 |
+
def _smoke_check_kb_l1() -> tuple[int, int]:
|
| 935 |
+
"""Walk ``KernelBench/KernelBench/level1/`` and report any L1 miss.
|
| 936 |
+
|
| 937 |
+
Returns ``(scanned, fail_count)``. Used by the combined entry point at
|
| 938 |
+
the bottom of this file to compute a single exit code across L1+L2.
|
| 939 |
+
"""
|
| 940 |
+
repo = Path(__file__).resolve().parents[1]
|
| 941 |
+
l1_dir = repo / "KernelBench" / "KernelBench" / "level1"
|
| 942 |
+
if not l1_dir.is_dir():
|
| 943 |
+
print(f"[smoke L1] KB L1 dir not found at {l1_dir}; "
|
| 944 |
+
f"skipping coverage check", file=sys.stderr)
|
| 945 |
+
return 0, 0
|
| 946 |
+
|
| 947 |
+
files = sorted(p.name for p in l1_dir.glob("*.py"))
|
| 948 |
+
by_l1: dict[str, list[str]] = {l1: [] for l1 in VOCAB_L1}
|
| 949 |
+
for name in files:
|
| 950 |
+
by_l1[infer_from_filename(name)].append(name)
|
| 951 |
+
|
| 952 |
+
n = sum(len(v) for v in by_l1.values())
|
| 953 |
+
print(f"[smoke L1] scanned {n} L1 files in {l1_dir}")
|
| 954 |
+
for l1 in VOCAB_L1:
|
| 955 |
+
print(f" {l1:<16s} {len(by_l1[l1]):>3d}")
|
| 956 |
+
|
| 957 |
+
other_files = by_l1["other"]
|
| 958 |
+
if other_files:
|
| 959 |
+
print("[smoke L1] FAIL — basenames that fell through to 'other':",
|
| 960 |
+
file=sys.stderr)
|
| 961 |
+
for fn in other_files:
|
| 962 |
+
print(f" {fn}", file=sys.stderr)
|
| 963 |
+
return n, 1
|
| 964 |
+
print("[smoke L1] OK — every KB L1 filename resolves to a non-'other' L1")
|
| 965 |
+
return n, 0
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
def _smoke_check_kb_l2() -> tuple[int, int]:
|
| 969 |
+
"""Walk ``KernelBench/KernelBench/level2/`` and report any L2 miss.
|
| 970 |
+
|
| 971 |
+
Coverage criterion: every L2 filename resolves to a sequence of
|
| 972 |
+
one-or-more (L1, L2) pairs with no ``other_misc`` fallthrough. Each
|
| 973 |
+
op token must produce a recognised pair -- a single ``other_misc``
|
| 974 |
+
in any sequence fails the smoke check.
|
| 975 |
+
|
| 976 |
+
Returns ``(scanned, fail_count)``.
|
| 977 |
+
"""
|
| 978 |
+
repo = Path(__file__).resolve().parents[1]
|
| 979 |
+
l2_dir = repo / "KernelBench" / "KernelBench" / "level2"
|
| 980 |
+
if not l2_dir.is_dir():
|
| 981 |
+
print(f"[smoke L2] KB L2 dir not found at {l2_dir}; "
|
| 982 |
+
f"skipping coverage check", file=sys.stderr)
|
| 983 |
+
return 0, 0
|
| 984 |
+
|
| 985 |
+
files = sorted(p.name for p in l2_dir.glob("*.py"))
|
| 986 |
+
by_l2: dict[str, int] = {l2: 0 for l2 in VOCAB_L2}
|
| 987 |
+
bad: list[tuple[str, list[tuple[str, str]]]] = []
|
| 988 |
+
for name in files:
|
| 989 |
+
ops = parse_l2_sequence(name)
|
| 990 |
+
if any(l1 == "other" and l2 == "other_misc" for l1, l2 in ops):
|
| 991 |
+
bad.append((name, ops))
|
| 992 |
+
for _l1, l2 in ops:
|
| 993 |
+
if l2 in by_l2:
|
| 994 |
+
by_l2[l2] += 1
|
| 995 |
+
|
| 996 |
+
n = len(files)
|
| 997 |
+
print(f"[smoke L2] scanned {n} L2 files in {l2_dir}")
|
| 998 |
+
# Group counts by L1 family for readability.
|
| 999 |
+
for l1 in VOCAB_L1:
|
| 1000 |
+
total = sum(by_l2[l2] for l2 in _L2_BY_L1[l1])
|
| 1001 |
+
print(f" {l1:<16s} {total:>5d} (across "
|
| 1002 |
+
f"{len(_L2_BY_L1[l1])} L2 classes)")
|
| 1003 |
+
|
| 1004 |
+
if bad:
|
| 1005 |
+
print("[smoke L2] FAIL — L2 problems with at least one unresolved "
|
| 1006 |
+
"token (other_misc):", file=sys.stderr)
|
| 1007 |
+
for fn, ops in bad:
|
| 1008 |
+
print(f" {fn} -> {ops}", file=sys.stderr)
|
| 1009 |
+
return n, 1
|
| 1010 |
+
print("[smoke L2] OK — every KB L2 filename resolves to a complete "
|
| 1011 |
+
"(L1, L2) sequence with no other_misc fallthrough")
|
| 1012 |
+
return n, 0
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def _smoke_check() -> int:
|
| 1016 |
+
"""Run both L1 and L2 coverage checks; return 0 iff both pass."""
|
| 1017 |
+
_, fail_l1 = _smoke_check_kb_l1()
|
| 1018 |
+
_, fail_l2 = _smoke_check_kb_l2()
|
| 1019 |
+
return 1 if (fail_l1 or fail_l2) else 0
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
if __name__ == "__main__":
|
| 1023 |
+
raise SystemExit(_smoke_check())
|