KernelBench-M / substrates /candidate_L2p14_gemm_divide_sum_scalin.py
Elfsong's picture
KernelBench-M artifact: rules, substrates, witnesses, pipeline, summaries
1276a5c verified
Raw History Blame Contribute Delete
5.34 kB
"""Mutation-friendly substrate for KernelBench level2 problem 14."""
CUDA_SOURCE = r"""
#include <cuda_fp16.h>
__global__ void gemm_divide_sum_scaling_kernel(
const float* x, float* out, const float* weight,
int batch_size, int input_size, int hidden_size) {
int batch = blockIdx.x;
int tid = threadIdx.x;
if (batch >= batch_size) return;
// Each thread computes complete GEMM entries for a strided subset of
// hidden columns. Keeping the inner-product loop explicit provides clear
// mutation sites for both bounds and the two matrix strides.
float thread_sum = 0.0f;
for (int hidden = tid; hidden < hidden_size; hidden += blockDim.x) {
float gemm_value = 0.0f;
for (int inner = 0; inner < input_size; inner++) {
long long x_index = (long long)batch * input_size + inner;
long long weight_index =
(long long)hidden * input_size + inner;
gemm_value += x[x_index] * weight[weight_index];
}
float divided_value = gemm_value / 2.0f;
thread_sum += divided_value;
}
__shared__ float partial_sums[256];
partial_sums[tid] = thread_sum;
__syncthreads(); // sync-after-partial-store
for (int width = 128; width > 0; width >>= 1) {
if (tid < width) {
partial_sums[tid] =
partial_sums[tid] + partial_sums[tid + width];
}
__syncthreads(); // sync-after-reduction-step
}
if (tid == 0) {
out[batch] = partial_sums[0] * 1.5f;
}
}
"""
def register(K, torch, ctypes):
# Model.__init__ calls torch.randn(8192, 8192) exactly once. Freeze an
# ordinary seed-0 realization so the implicit parameter is identical in
# the reference and device paths without perturbing suite RNG state.
with torch.random.fork_rng(devices=[]):
torch.manual_seed(0)
frozen_weight = torch.randn(8192, 8192).contiguous()
device_weights = {}
def weight_for(x):
key = (x.device.type, x.device.index, x.dtype)
weight = device_weights.get(key)
if weight is None:
weight = frozen_weight.to(device=x.device, dtype=x.dtype)
device_weights[key] = weight
return weight
def ref(x):
# Forward is matmul, true division, sum over hidden dim with keepdim,
# then multiplication by get_init_inputs()' scaling_factor=1.5.
value = torch.matmul(x, weight_for(x).T)
value = value / 2
value = torch.sum(value, dim=1, keepdim=True)
return value * 1.5
def launch(inputs, torch_module):
x = inputs[0]
if x.ndim != 2 or x.shape[1] != 8192:
raise ValueError("this substrate requires input shape (batch, 8192)")
batch_size, input_size = x.shape
hidden_size = 8192
out = torch_module.empty(
(batch_size, 1), device=x.device, dtype=x.dtype)
args = [
(ctypes.c_void_p, weight_for(x).data_ptr()),
(ctypes.c_int, batch_size),
(ctypes.c_int, input_size),
(ctypes.c_int, hidden_size),
]
return out, (batch_size, 1, 1), (256, 1, 1), args
def suites():
def t0_original(trial):
torch.manual_seed(1000 + trial)
return [torch.rand(1024, 8192)]
def t1_signed(trial):
torch.manual_seed(2000 + trial)
return [torch.randn(9, 8192) * 0.1]
def t2_misaligned_batch(trial):
torch.manual_seed(3000 + trial)
return [torch.rand(37, 8192)]
def t3_positive_tail_spike(trial):
torch.manual_seed(4000 + trial)
x = torch.rand(5, 8192)
x[:, -1] = 100.0
return [x]
def t4_positive_structured_overflow(trial):
torch.manual_seed(5000 + trial)
position = torch.linspace(0.0, 1.0, 8192)
x = torch.stack([
torch.full((8192,), 32.0),
16.0 + 32.0 * position,
torch.where(
torch.arange(8192) % 2 == 0,
torch.tensor(8.0),
torch.tensor(56.0)),
])
return [x]
def t5_positive_periodic_spikes(trial):
torch.manual_seed(6000 + trial)
x = torch.full((7, 8192), 64.0)
x[:, ::257] = 2048.0
return [x]
return [
("T0_original", 5, t0_original),
("T1_signed", 1, t1_signed),
("T2_misaligned_batch", 1, t2_misaligned_batch),
("T3_positive_tail_spike", 1, t3_positive_tail_spike),
("T4_positive_structured_overflow", 1,
t4_positive_structured_overflow),
("T5_positive_periodic_spikes", 1,
t5_positive_periodic_spikes),
]
def probe(torch_module):
torch_module.manual_seed(0)
return [
("p_aligned", [torch_module.rand(16, 8192)]),
("p_misaligned", [torch_module.randn(7, 8192) * 0.1]),
]
K.PROBLEMS["L2p14_gemm_divide_sum_scalin"] = dict(
kb_file="14_Gemm_Divide_Sum_Scaling.py",
cuda=CUDA_SOURCE,
kernel_name="gemm_divide_sum_scaling_kernel",
ref=ref,
launch=launch,
suites=suites,
probe=probe,
)