KernelBench-M / pipeline /problems_ext.py
Elfsong's picture
KernelBench-M artifact: rules, substrates, witnesses, pipeline, summaries
1276a5c verified
Raw
History Blame Contribute Delete
20.2 kB
"""Extended problem registry: 9 more KernelBench level1 problems.
Each entry is registry-driven (no per-problem code in screen_mutants):
cuda device-only CUDA source (mutation substrate)
kernel_name __global__ symbol
ref torch reference callable (must match the KB Model semantics)
launch (inputs, torch) -> (out, grid, block, scalar ctypes args)
suites () -> [(name, n_trials, builder)]
probe (torch) -> [(name, [cpu tensors])] tiny crash-quarantine inputs
Import side effect: registers everything into kernels_def.PROBLEMS.
"""
import ctypes
import torch as _torch # only for type hints in refs; runtime torch passed in
import kernels_def as K
def _seeded(seed):
_torch.manual_seed(seed)
# --------------------------------------------------------------- elementwise
def _ew_launch(inputs, torch):
x = inputs[0]
out = torch.zeros_like(x)
n = x.numel()
return out, ((n + 255) // 256, 1, 1), (256, 1, 1), [(ctypes.c_longlong, n)]
def _ew_suites():
def t0(t):
_seeded(1000 + t)
return [_torch.rand(4096, 393216)]
def t1(t):
_seeded(7)
return [_torch.randn(4096, 393216)]
def t2(t):
_seeded(9)
return [_torch.randn(4096, 393216) * 100.0]
def t3(t):
_seeded(8)
return [_torch.randn(127, 4097)]
return [("T0_original", 5, t0), ("T1_signed", 1, t1),
("T2_large", 1, t2), ("T3_misaligned", 1, t3)]
def _leakyrelu_suites():
suites = _ew_suites()
def t4(t):
_seeded(26043)
x = _torch.full((31, 257), 1e-4)
x[:, -1] = 1e3
x.reshape(-1)[::256] = 2e3
return [x]
def t5(t):
_seeded(26044)
transition = _torch.tensor([
-2e-6, -1e-6, -5e-7, -1e-7, 0.0,
1e-7, 5e-7, 1e-6, 2e-6,
])
return [transition.repeat(29, 29)[:, :257].contiguous()]
suites.extend([
("T4_misaligned_tail_spikes", 1, t4),
("T5_threshold_transition_grid", 1, t5),
])
return suites
def _gelu_suites():
suites = _ew_suites()
def t4(t):
_seeded(26041)
x = _torch.full((127, 4097), 70000.0)
x[:, -1] = 65520.0
return [x]
def t5(t):
_seeded(26042)
transition = _torch.tensor([
-4.0, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5,
0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0,
])
return [transition.repeat(17, 18)[:, :257].contiguous()]
suites.extend([
("T4_misaligned_fp16_overflow", 1, t4),
("T5_erf_transition_grid", 1, t5),
])
return suites
def _sigmoid_suites():
suites = _ew_suites()
def t4(t):
_seeded(26043)
x = _torch.full((255, 257), 12.0)
x[:, ::2] = -12.0
x.reshape(-1)[-1] = 0.0
return [x]
def t5(t):
_seeded(26044)
transition = _torch.tensor([
-6.0, -4.0, -2.0, -1.0, -0.5, -0.125,
0.0, 0.125, 0.5, 1.0, 2.0, 4.0, 6.0,
])
return [transition.repeat(129, 20)[:, :257].contiguous()]
suites.extend([
("T4_misaligned_alternating_tail", 1, t4),
("T5_fp16_transition_grid", 1, t5),
])
return suites
def _ew_probe(torch):
torch.manual_seed(0)
return [("p_aligned", [torch.rand(32, 256)]),
("p_misaligned", [torch.randn(7, 257)])]
_EW_TMPL = r"""
#include <cuda_fp16.h>
__global__ void {kname}(const float* x, float* out, long long n) {{
long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {{ float val = x[idx]; out[idx] = {expr}; }}
}}
"""
_ELEMENTWISE = {
"leakyrelu": dict(
kb="20_LeakyReLU.py",
expr="val > 0.0f ? val : 0.01f * val",
ref=lambda x: _torch.nn.functional.leaky_relu(x, 0.01),
suites=_leakyrelu_suites),
"gelu": dict(
kb="26_GELU_.py",
expr="0.5f * val * (1.0f + erff(val * 0.70710678f))",
ref=lambda x: _torch.nn.functional.gelu(x), suites=_gelu_suites),
"sigmoid": dict(
kb="21_Sigmoid.py",
expr="1.0f / (1.0f + expf(-val))",
ref=lambda x: _torch.sigmoid(x), suites=_sigmoid_suites),
}
# --------------------------------------------------------------- logsoftmax
LOGSOFTMAX_CUDA = r"""
#include <cuda_fp16.h>
#include <math_constants.h>
__global__ void logsoftmax_kernel(const float* x, float* out, int dim) {
long long row = blockIdx.x;
const float* xr = x + row * dim;
float* outr = out + row * dim;
__shared__ float sdata[256];
int tid = threadIdx.x;
int iters = (dim + 255) / 256;
float local_max = -CUDART_INF_F;
for (int it = 0; it < iters; it++) {
int i = it * 256 + tid;
if (i < dim) { local_max = fmaxf(local_max, xr[i]); }
}
sdata[tid] = local_max;
__syncthreads(); // sync-max-store
for (int s = 128; s > 0; s >>= 1) { // max-reduce
if (tid < s) { sdata[tid] = fmaxf(sdata[tid], sdata[tid + s]); }
__syncthreads();
}
float row_max = sdata[0];
__syncthreads(); // sync-max-read
float local_sum = 0.0f;
for (int it = 0; it < iters; it++) {
int i = it * 256 + tid;
if (i < dim) { local_sum += expf(xr[i] - row_max); }
}
sdata[tid] = local_sum;
__syncthreads(); // sync-sum-store
for (int s = 128; s > 0; s >>= 1) { // sum-reduce
if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }
__syncthreads();
}
float log_sum = logf(sdata[0]);
__syncthreads(); // sync-sum-read
for (int it = 0; it < iters; it++) {
int i = it * 256 + tid;
if (i < dim) { outr[i] = xr[i] - row_max - log_sum; }
}
}
"""
def _lsm_launch(inputs, torch):
x = inputs[0]
out = torch.zeros_like(x)
return out, (x.shape[0], 1, 1), (256, 1, 1), [(ctypes.c_int, x.shape[1])]
def _lsm_suites():
def t0(t):
_seeded(1000 + t)
return [_torch.rand(4096, 393216)]
def t2(t):
_seeded(9)
return [_torch.randn(4096, 393216) * 100.0]
def t3(t):
_seeded(11)
x = _torch.zeros(4096, 393216)
cols = _torch.randint(0, 393216, (4096,))
x[_torch.arange(4096), cols] = 20.0
return [x]
def t4(t):
_seeded(13)
x = _torch.randn(64, 4099) * 0.01
x[:, -1] = 20.0
return [x]
def t5(t):
_seeded(17)
x = _torch.ones(64, 513)
x[:, 0] = 3000.0
return [x]
def t6(t):
_seeded(19)
x = _torch.ones(64, 4097)
x[:, 1::2] = 3000.0
x[:, -1] = 6000.0
return [x]
def t7(t):
_seeded(23)
x = _torch.ones(64, 259)
x[:, 258] = 70000.0
return [x]
return [("T0_original", 5, t0), ("T2_large", 1, t2),
("T3_spiky", 1, t3), ("T4_tail_spike_misaligned", 1, t4),
("T5_first_iteration_mass", 1, t5),
("T6_alternating_lane_magnitude", 1, t6),
("T7_fp16_overflow_misaligned", 1, t7)]
def _lsm_probe(torch):
torch.manual_seed(0)
x = torch.randn(16, 259) * 0.01
x[:, -1] = 20.0
return [("p_aligned", [torch.rand(16, 512)]),
("p_large", [torch.randn(16, 512) * 100.0]),
("p_misaligned_spike", [x])]
# --------------------------------------------------------------- matmul MK/TA
MATMUL_MK_CUDA = r"""
#include <cuda_fp16.h>
#define TILE 32
__global__ void matmul_mk_kernel(const float* A, const float* B, float* C,
int M, int K, int N) {
__shared__ float As[TILE][TILE];
__shared__ float Bs[TILE][TILE];
int row = blockIdx.y * TILE + threadIdx.y;
int col = blockIdx.x * TILE + threadIdx.x;
float acc = 0.0f;
int numTiles = (K + TILE - 1) / TILE;
for (int t = 0; t < numTiles; t++) {
int a_col = t * TILE + threadIdx.x;
int b_row = t * TILE + threadIdx.y;
As[threadIdx.y][threadIdx.x] = (row < M && a_col < K) ? A[(long long)row * K + a_col] : 0.0f;
Bs[threadIdx.y][threadIdx.x] = (b_row < K && col < N) ? B[(long long)b_row * N + col] : 0.0f;
__syncthreads(); // sync-after-load
for (int k = 0; k < TILE; k++) {
acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
}
__syncthreads(); // sync-after-compute
}
if (row < M && col < N) { C[(long long)row * N + col] = acc; }
}
"""
MATMUL_TA_CUDA = r"""
#include <cuda_fp16.h>
#define TILE 32
__global__ void matmul_ta_kernel(const float* A, const float* B, float* C,
int M, int K, int N) {
__shared__ float As[TILE][TILE];
__shared__ float Bs[TILE][TILE];
int row = blockIdx.y * TILE + threadIdx.y;
int col = blockIdx.x * TILE + threadIdx.x;
float acc = 0.0f;
int numTiles = (K + TILE - 1) / TILE;
for (int t = 0; t < numTiles; t++) {
int a_k = t * TILE + threadIdx.x;
int b_k = t * TILE + threadIdx.y;
As[threadIdx.y][threadIdx.x] = (a_k < K && row < M) ? A[(long long)a_k * M + row] : 0.0f;
Bs[threadIdx.y][threadIdx.x] = (b_k < K && col < N) ? B[(long long)b_k * N + col] : 0.0f;
__syncthreads(); // sync-after-load
for (int k = 0; k < TILE; k++) {
acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
}
__syncthreads(); // sync-after-compute
}
if (row < M && col < N) { C[(long long)row * N + col] = acc; }
}
"""
def _mm_launch_mk(inputs, torch):
A, B = inputs
M, Kd = A.shape
N = B.shape[1]
out = torch.zeros((M, N), device=A.device, dtype=A.dtype)
return out, ((N + 31) // 32, (M + 31) // 32, 1), (32, 32, 1), \
[(ctypes.c_int, M), (ctypes.c_int, Kd), (ctypes.c_int, N)]
def _mm_launch_ta(inputs, torch):
A, B = inputs
Kd, M = A.shape
N = B.shape[1]
out = torch.zeros((M, N), device=A.device, dtype=A.dtype)
return out, ((N + 31) // 32, (M + 31) // 32, 1), (32, 32, 1), \
[(ctypes.c_int, M), (ctypes.c_int, Kd), (ctypes.c_int, N)]
def _mm_suites(shapes):
(m, k, n), (m3, k3, n3), transposed = shapes
def a_shape(M, Kd):
return (Kd, M) if transposed else (M, Kd)
def t0(t):
_seeded(1000 + t)
return [_torch.rand(*a_shape(m, k)), _torch.rand(k, n)]
def t1(t):
_seeded(7)
return [_torch.randn(*a_shape(m, k)), _torch.randn(k, n)]
def t2(t):
# positive-only large values: kills fp16/precision mutants via overflow
# without triggering legitimate fp32 accumulation-order variance
# (signed large values false-kill correct kernels at K=8192, see sum/T2)
_seeded(9)
return [_torch.rand(*a_shape(m, k)) * 50.0, _torch.rand(k, n) * 50.0]
def t3(t):
_seeded(11)
return [_torch.randn(*a_shape(m3, k3)), _torch.randn(k3, n3)]
def t4(t):
_seeded(13)
A = _torch.rand(*a_shape(m, k))
B = _torch.rand(k, n)
if transposed:
A[-32:, :] = 100.0
else:
A[:, -32:] = 100.0
B[-32:, :] = 100.0
return [A, B]
suites = [("T0_original", 5, t0), ("T1_signed", 1, t1), ("T2_large", 1, t2),
("T3_misaligned", 1, t3), ("T4_last_tile_spike", 1, t4)]
if not transposed:
return suites
def t5(t):
# Every logical dimension ends one lane before a tile boundary. The
# positive ramps make accidental boundary reads distinct and visible.
_seeded(101)
M, Kd, N = 1023, 31, 1023
A = (_torch.arange(Kd)[:, None] + 1.0) * 0.25
A = A.expand(Kd, M).clone()
A += (_torch.arange(M)[None, :] % 17) * 0.01
B = (_torch.arange(Kd)[:, None] + 1.0) * 0.125
B = B.expand(Kd, N).clone()
B += (_torch.arange(N)[None, :] % 19) * 0.01
return [A, B]
def t6(t):
# A one-element K tail puts the padding guard immediately beside a
# dominant, same-sign term while M and N also have partial blocks.
_seeded(103)
M, Kd, N = 95, 65, 93
A = _torch.full((Kd, M), 1.0e-3)
B = _torch.full((Kd, N), 1.0e-3)
A[-1, :] = 200.0 + (_torch.arange(M) % 11) * 0.25
B[-1, :] = 150.0 + (_torch.arange(N) % 13) * 0.25
return [A, B]
def t7(t):
# K == TILE - 1 directly exercises the mutated TILE - 1 tile-count
# expression; alternating positive magnitudes expose stray reads.
_seeded(107)
M, Kd, N = 63, 31, 61
scale = _torch.where(_torch.arange(Kd) % 2 == 0, 1.0e-3, 100.0)
A = scale[:, None].expand(Kd, M).clone()
B = scale[:, None].expand(Kd, N).clone()
A += (_torch.arange(M)[None, :] % 7) * 0.01
B += (_torch.arange(N)[None, :] % 5) * 0.01
return [A, B]
suites.extend([("T5_boundary_positional_ramps", 1, t5),
("T6_single_tail_mass_spike", 1, t6),
("T7_tile_minus1_alternating", 1, t7)])
return suites
def _mm_probe(transposed):
def probe(torch):
torch.manual_seed(0)
def a_shape(M, Kd):
return (Kd, M) if transposed else (M, Kd)
return [("p_aligned", [torch.rand(*a_shape(64, 128)), torch.rand(128, 96)]),
("p_misaligned", [torch.randn(*a_shape(67, 131)), torch.randn(131, 53)])]
return probe
# --------------------------------------------------------- mean / max over dim1
MEAN_CUDA = r"""
#include <cuda_fp16.h>
__global__ void mean_dim1_kernel(const float* x, float* out, int B, int R, int C) {
int c = blockIdx.x * blockDim.x + threadIdx.x;
int b = blockIdx.y;
if (c >= C) return;
float acc = 0.0f;
for (int r = 0; r < R; r++) {
acc += x[(long long)b * R * C + (long long)r * C + c];
}
out[(long long)b * C + c] = acc / R;
}
"""
MAX_CUDA = r"""
#include <cuda_fp16.h>
#include <math_constants.h>
__global__ void max_dim1_kernel(const float* x, float* out, int B, int R, int C) {
int c = blockIdx.x * blockDim.x + threadIdx.x;
int b = blockIdx.y;
if (c >= C) return;
float best = -CUDART_INF_F;
for (int r = 0; r < R; r++) {
best = fmaxf(best, x[(long long)b * R * C + (long long)r * C + c]);
}
out[(long long)b * C + c] = best;
}
"""
def _red2d_launch(inputs, torch):
x = inputs[0]
B, R, C = x.shape
out = torch.zeros((B, C), device=x.device, dtype=x.dtype)
return out, ((C + 255) // 256, B, 1), (256, 1, 1), \
[(ctypes.c_int, B), (ctypes.c_int, R), (ctypes.c_int, C)]
def _red_suites(extra_negative):
def t0(t):
_seeded(1000 + t)
return [_torch.rand(128, 4096, 4095)]
def t1(t):
_seeded(7)
return [_torch.randn(128, 4096, 4095)]
def t4(t):
_seeded(13)
x = _torch.rand(128, 4096, 4095)
x[:, 0, :] += 100.0
x[:, -1, :] += 100.0
return [x]
suites = [("T0_original", 5, t0), ("T1_signed", 1, t1),
("T4_edge_row_spike", 1, t4)]
if extra_negative:
def t5(t):
_seeded(17)
return [-_torch.rand(128, 4096, 4095) - 1.0]
suites.append(("T5_all_negative", 1, t5))
def t6(t):
_seeded(26045)
x = _torch.full((17, 257, 259), 32.0)
x[:, ::2, :] = 2048.0
x[:, 1::2, :] = 2048.0
return [x]
def t7(t):
_seeded(26046)
x = _torch.full((19, 129, 263), -64.0)
x[:, 0, :] = 1536.0
x[:, 64, :] = 1536.0
x[:, -1, :] = 1536.0
return [x]
def t8(t):
_seeded(26047)
x = _torch.full((23, 65, 257), -0.0)
x[:, 1::2, :] = 0.0
return [x]
suites.extend([
("T6_alternating_duplicate_maxima", 1, t6),
("T7_first_middle_last_ties", 1, t7),
("T8_signed_zero_tie_order", 1, t8),
])
return suites
def _red_probe(torch):
torch.manual_seed(0)
return [("p_aligned", [torch.rand(4, 64, 256)]),
("p_misaligned", [torch.randn(4, 64, 255)])]
# --------------------------------------------------------------------- rmsnorm
RMSNORM_CUDA = r"""
#include <cuda_fp16.h>
__global__ void rmsnorm_kernel(const float* x, float* out, int B, int F, int S) {
int s = blockIdx.x * blockDim.x + threadIdx.x;
int b = blockIdx.y;
if (s >= S) return;
float sq = 0.0f;
for (int f = 0; f < F; f++) {
float v = x[(long long)b * F * S + (long long)f * S + s];
sq += v * v;
}
float rms = sqrtf(sq / F + 1e-5f);
for (int f = 0; f < F; f++) {
long long i = (long long)b * F * S + (long long)f * S + s;
out[i] = x[i] / rms;
}
}
"""
def _rms_launch(inputs, torch):
x = inputs[0]
B, F, D1, D2 = x.shape
S = D1 * D2
out = torch.zeros_like(x)
return out, ((S + 255) // 256, B, 1), (256, 1, 1), \
[(ctypes.c_int, B), (ctypes.c_int, F), (ctypes.c_int, S)]
def _rms_ref(x):
rms = _torch.sqrt(_torch.mean(x ** 2, dim=1, keepdim=True) + 1e-5)
return x / rms
def _rms_suites():
def t0(t):
_seeded(1000 + t)
return [_torch.rand(112, 64, 512, 512)]
def t1(t):
_seeded(7)
return [_torch.randn(112, 64, 512, 512)]
def t3(t):
_seeded(11)
return [_torch.randn(7, 13, 33, 65)]
def t4(t):
_seeded(13)
x = _torch.rand(112, 64, 512, 512)
x[:, 0, :, :] += 50.0
x[:, -1, :, :] += 50.0
return [x]
return [("T0_original", 5, t0), ("T1_signed", 1, t1),
("T3_misaligned", 1, t3), ("T4_feature_spike", 1, t4)]
def _rms_probe(torch):
torch.manual_seed(0)
return [("p_aligned", [torch.rand(2, 8, 16, 16)]),
("p_misaligned", [torch.randn(3, 7, 13, 15)])]
# ------------------------------------------------------------------- register
def _register():
for name, spec in _ELEMENTWISE.items():
K.PROBLEMS[name] = dict(
kb_file=spec["kb"],
cuda=_EW_TMPL.format(kname=f"{name}_kernel", expr=spec["expr"]),
kernel_name=f"{name}_kernel", ref=spec["ref"],
launch=_ew_launch, suites=spec.get("suites", _ew_suites), probe=_ew_probe)
K.PROBLEMS["logsoftmax"] = dict(
kb_file="24_LogSoftmax.py", cuda=LOGSOFTMAX_CUDA,
kernel_name="logsoftmax_kernel",
ref=lambda x: _torch.log_softmax(x, dim=1),
launch=_lsm_launch, suites=_lsm_suites, probe=_lsm_probe)
K.PROBLEMS["matmul_mk"] = dict(
kb_file="2_Standard_matrix_multiplication_.py", cuda=MATMUL_MK_CUDA,
kernel_name="matmul_mk_kernel",
ref=lambda A, B: _torch.matmul(A, B),
launch=_mm_launch_mk,
suites=lambda: _mm_suites(((2048, 8192, 4096), (515, 1027, 259), False)),
probe=_mm_probe(False))
K.PROBLEMS["matmul_ta"] = dict(
kb_file="16_Matmul_with_transposed_A.py", cuda=MATMUL_TA_CUDA,
kernel_name="matmul_ta_kernel",
ref=lambda A, B: _torch.matmul(A.T, B),
launch=_mm_launch_ta,
suites=lambda: _mm_suites(((2048, 8192, 4096), (515, 1027, 259), True)),
probe=_mm_probe(True))
K.PROBLEMS["mean"] = dict(
kb_file="48_Mean_reduction_over_a_dimension.py", cuda=MEAN_CUDA,
kernel_name="mean_dim1_kernel",
ref=lambda x: _torch.mean(x, dim=1),
launch=_red2d_launch, suites=lambda: _red_suites(False), probe=_red_probe)
K.PROBLEMS["max"] = dict(
kb_file="49_Max_reduction_over_a_dimension.py", cuda=MAX_CUDA,
kernel_name="max_dim1_kernel",
ref=lambda x: _torch.max(x, dim=1)[0],
launch=_red2d_launch, suites=lambda: _red_suites(True), probe=_red_probe)
K.PROBLEMS["rmsnorm"] = dict(
kb_file="36_RMSNorm_.py", cuda=RMSNORM_CUDA,
kernel_name="rmsnorm_kernel", ref=_rms_ref,
launch=_rms_launch, suites=_rms_suites, probe=_rms_probe)
_register()
try:
import problems_batch2 # noqa: F401 (registers batch-2 substrates)
except ImportError:
pass
try:
import candidates_loader as _cl
_cl.load_accepted()
except Exception as _e:
import sys as _sys
print(f"[candidates] loader itself failed: {_e}", file=_sys.stderr, flush=True)