KernelBench-M / substrates /candidate_L2p37_matmul_swish_sum_group.py
Elfsong's picture
KernelBench-M artifact: rules, substrates, witnesses, pipeline, summaries
1276a5c verified
Raw History Blame Contribute Delete
10.5 kB
"""Correct, mutation-friendly substrate for KernelBench level-2 problem 37."""
CUDA_SOURCE = r"""
#include <cuda_fp16.h>
// A block owns one (batch row, normalization group). Problem 37 has
// 4096 / 64 = 64 channels per group, so each of the 64 threads computes one
// complete Linear output and then participates in the two GroupNorm sums.
__global__ void l2p37_matmul_swish_sum_group_kernel(
const float* x, float* out, const float* linear_weight,
const float* linear_bias, const float* added_bias,
const float* norm_weight, const float* norm_bias,
int rows, int input_features, int output_features, int groups) {
int thread = threadIdx.x;
int batch_group = blockIdx.x;
int batch = batch_group / groups;
int group = batch_group - batch * groups;
if (batch >= rows) return;
int channels_per_group = output_features / groups;
int channel_in_group = thread;
int output_channel = group * channels_per_group + channel_in_group;
__shared__ float group_values[64];
__shared__ float partial_sums[64];
__shared__ float group_mean;
__shared__ float inverse_standard_deviation;
float linear_value = 0.0f;
if (channel_in_group < channels_per_group) {
const float* input_row = x + (long long)batch * input_features;
const float* weight_row =
linear_weight + (long long)output_channel * input_features;
for (int input_channel = 0;
input_channel < input_features; input_channel++) {
linear_value += input_row[input_channel] * weight_row[input_channel];
}
linear_value += linear_bias[output_channel];
// Model.forward uses sigmoid(z) * z, then adds its separate learned
// length-4096 bias before normalization.
float sigmoid_value = 1.0f / (1.0f + expf(-linear_value));
float biased_swish = linear_value * sigmoid_value
+ added_bias[output_channel];
group_values[channel_in_group] = biased_swish;
partial_sums[thread] = biased_swish;
} else {
partial_sums[thread] = 0.0f;
}
__syncthreads(); // sync-after-linear-and-swish
for (int width = 32; width > 0; width >>= 1) {
if (thread < width) {
partial_sums[thread] += partial_sums[thread + width];
}
__syncthreads(); // sync-during-mean-reduction
}
if (thread == 0) {
group_mean = partial_sums[0] / (float)channels_per_group;
}
__syncthreads(); // sync-after-mean
float squared_deviation = 0.0f;
if (channel_in_group < channels_per_group) {
float centered = group_values[channel_in_group] - group_mean;
squared_deviation = centered * centered;
}
partial_sums[thread] = squared_deviation;
__syncthreads(); // sync-after-squared-deviation
for (int width = 32; width > 0; width >>= 1) {
if (thread < width) {
partial_sums[thread] += partial_sums[thread + width];
}
__syncthreads(); // sync-during-variance-reduction
}
if (thread == 0) {
// GroupNorm uses the population (biased) variance and eps=1e-5.
float variance = partial_sums[0] / (float)channels_per_group;
inverse_standard_deviation = rsqrtf(variance + 1.0e-5f);
}
__syncthreads(); // sync-after-variance
if (channel_in_group < channels_per_group) {
float normalized = (group_values[channel_in_group] - group_mean)
* inverse_standard_deviation;
float affine = normalized * norm_weight[output_channel]
+ norm_bias[output_channel];
long long output_index =
(long long)batch * output_features + output_channel;
out[output_index] = affine;
}
}
"""
def register(K, torch, ctypes):
input_features = 1024
output_features = 4096
groups = 64
# Model.__init__ constructs Linear, samples its separate bias, and then
# constructs GroupNorm. Reproduce that exact RNG-consuming order while
# preserving the caller's RNG stream. Both execution paths share these
# frozen parameters.
with torch.random.fork_rng(devices=[]):
torch.manual_seed(0)
linear = torch.nn.Linear(input_features, output_features)
standalone_bias = torch.randn((output_features,))
group_norm = torch.nn.GroupNorm(groups, output_features)
frozen_parameters = tuple(
parameter.detach().cpu().contiguous()
for parameter in (
linear.weight,
linear.bias,
standalone_bias,
group_norm.weight,
group_norm.bias,
)
)
parameter_cache = {}
def parameters_for(x):
key = (x.device.type, x.device.index, x.dtype)
parameters = parameter_cache.get(key)
if parameters is None:
parameters = tuple(
parameter.to(device=x.device, dtype=x.dtype)
for parameter in frozen_parameters
)
parameter_cache[key] = parameters
return parameters
def ref(x):
linear_weight, linear_bias, added_bias, norm_weight, norm_bias = (
parameters_for(x)
)
value = torch.nn.functional.linear(x, linear_weight, linear_bias)
value = torch.sigmoid(value) * value
value = value + added_bias
return torch.nn.functional.group_norm(
value,
num_groups=groups,
weight=norm_weight,
bias=norm_bias,
eps=1.0e-5,
)
def launch(inputs, torch_module):
x = inputs[0]
if x.ndim != 2 or x.shape[1] != input_features:
raise ValueError("expected input shape (batch_size, 1024)")
rows = x.shape[0]
parameters = parameters_for(x)
out = torch_module.empty(
(rows, output_features), device=x.device, dtype=x.dtype
)
out._substrate_keepalive = parameters
args = [
(ctypes.c_void_p, parameters[0].data_ptr()),
(ctypes.c_void_p, parameters[1].data_ptr()),
(ctypes.c_void_p, parameters[2].data_ptr()),
(ctypes.c_void_p, parameters[3].data_ptr()),
(ctypes.c_void_p, parameters[4].data_ptr()),
(ctypes.c_int, rows),
(ctypes.c_int, input_features),
(ctypes.c_int, output_features),
(ctypes.c_int, groups),
]
return out, (rows * groups, 1, 1), (64, 1, 1), args
def suites():
def t0_original(trial):
torch.manual_seed(1000 + trial)
return [torch.rand(32768, 1024)]
def t1_signed(trial):
torch.manual_seed(2000 + trial)
return [torch.randn(17, 1024) * 0.05]
def t2_misaligned_batch(trial):
torch.manual_seed(3000 + trial)
return [torch.rand(13, 1024)]
def t3_positive_feature_spikes(trial):
torch.manual_seed(4000 + trial)
value = torch.rand(7, 1024)
value[:, 0] = 4.0
value[:, 511] = 8.0
value[:, -1] = 16.0
return [value]
def t4_zero_linear_baseline(trial):
torch.manual_seed(5000 + trial)
return [torch.zeros(3, 1024)]
def t5_single_feature_overflow_spikes(trial):
torch.manual_seed(6000 + trial)
value = torch.full((5, 1024), 1.0e-4)
spike_positions = (0, 1, 511, 512, 1023)
for row, position in enumerate(spike_positions):
value[row, position] = 4.0e6
return [value]
def t6_alternating_sparse_magnitudes(trial):
torch.manual_seed(7000 + trial)
value = torch.full((3, 1024), 1.0e-4)
value[0, 0::2] = 512.0
value[1, 1::2] = 512.0
value[2, 31::32] = 4096.0
return [value]
def t7_lane_boundary_feature_spikes(trial):
torch.manual_seed(8000 + trial)
value = torch.full((9, 1024), 1.0e-3)
spike_positions = (0, 31, 32, 63, 64, 511, 512, 1022, 1023)
for row, position in enumerate(spike_positions):
value[row, position] = 8192.0
return [value]
def t8_positive_checkerboard_contrast(trial):
torch.manual_seed(9000 + trial)
value = torch.full((5, 1024), 1.0e-3)
value[0, 0::2] = 1024.0
value[1, 1::2] = 1024.0
value[2, 0::32] = 4096.0
value[3, 31::32] = 4096.0
value[4, 15::16] = 2048.0
return [value]
def t9_positive_positional_steps(trial):
torch.manual_seed(10000 + trial)
feature = torch.arange(1024, dtype=torch.float32)
value = torch.empty((7, 1024), dtype=torch.float32)
value[0] = 1.0 + feature / 8.0
value[1] = 128.0 - feature / 8.0
value[2] = 1.0 + (feature % 32) * 32.0
value[3] = 1.0 + (feature // 32) * 32.0
value[4] = torch.where(feature < 512, 1.0, 1024.0)
value[5] = torch.where(feature % 64 < 32, 2.0, 2048.0)
value[6] = 256.0
return [value]
return [
("T0_original", 5, t0_original),
("T1_signed", 1, t1_signed),
("T2_misaligned_batch", 1, t2_misaligned_batch),
("T3_positive_feature_spikes", 1, t3_positive_feature_spikes),
("T4_zero_linear_baseline", 1, t4_zero_linear_baseline),
("T5_single_feature_overflow_spikes", 1, t5_single_feature_overflow_spikes),
("T6_alternating_sparse_magnitudes", 1, t6_alternating_sparse_magnitudes),
("T7_lane_boundary_feature_spikes", 1, t7_lane_boundary_feature_spikes),
("T8_positive_checkerboard_contrast", 1, t8_positive_checkerboard_contrast),
("T9_positive_positional_steps", 1, t9_positive_positional_steps),
]
def probe(torch_module):
torch_module.manual_seed(0)
return [
("p_aligned", [torch_module.rand(16, 1024)]),
("p_misaligned", [torch_module.randn(3, 1024) * 0.05]),
]
K.PROBLEMS["L2p37_matmul_swish_sum_group"] = dict(
kb_file="37_Matmul_Swish_Sum_GroupNorm.py",
cuda=CUDA_SOURCE,
kernel_name="l2p37_matmul_swish_sum_group_kernel",
ref=ref,
launch=launch,
suites=suites,
probe=probe,
)