"""Correct, mutation-friendly substrate for KernelBench level-2 problem 39.""" CUDA_SOURCE = r""" #include __global__ void L2p39_gemm_scale_batchnorm_kernel( const float* x, float* out, float* workspace, const float* weight, const float* bias, const float* scale, int rows, int input_features, int output_features, float epsilon) { int output_feature = blockIdx.x * blockDim.x + threadIdx.x; if (output_feature >= output_features) return; // nn.Linear computes x @ weight.T + bias. A thread owns one output // feature and scans all rows, which also makes its BatchNorm reduction // independent of every other thread. float mean = 0.0f; float second_moment = 0.0f; int count = 0; for (int row = 0; row < rows; row++) { float accumulator = 0.0f; for (int input_feature = 0; input_feature < input_features; input_feature++) { long long input_index = (long long)row * input_features + input_feature; long long weight_index = (long long)output_feature * input_features + input_feature; accumulator += x[input_index] * weight[weight_index]; } float linear_value = accumulator + bias[output_feature]; float scaled_value = linear_value * scale[output_feature]; long long output_index = (long long)row * output_features + output_feature; workspace[output_index] = scaled_value; // Training-mode BatchNorm uses the biased population variance for // its output. Welford's recurrence avoids a fragile E[x*x]-E[x]^2. count += 1; float delta = scaled_value - mean; mean += delta / (float)count; float delta_after_mean = scaled_value - mean; second_moment += delta * delta_after_mean; } float variance = second_moment / (float)rows; float inverse_standard_deviation = rsqrtf(variance + epsilon); for (int row = 0; row < rows; row++) { long long output_index = (long long)row * output_features + output_feature; float centered = workspace[output_index] - mean; // BatchNorm1d affine parameters initialize to gamma=1 and beta=0. out[output_index] = centered * inverse_standard_deviation; } } """ def register(K, torch, ctypes): """Register the device-only kernel and deterministic reference state.""" input_features = 4096 output_features = 4096 epsilon = 1.0e-5 # get_init_inputs() is [4096, 4096, (4096,)]. Match Model.__init__'s # random construction order exactly: Linear, then scale; BatchNorm's # initial affine values are deterministic ones and zeros. Forking keeps # registration import-safe with respect to the caller's RNG stream. with torch.random.fork_rng(devices=[]): torch.manual_seed(0) linear = torch.nn.Linear(input_features, output_features, bias=True) frozen_weight = linear.weight.detach().cpu().contiguous() frozen_bias = linear.bias.detach().cpu().contiguous() frozen_scale = torch.randn((output_features,)).cpu().contiguous() device_parameters = {} def parameters_for(x): key = (x.device.type, x.device.index, x.dtype) parameters = device_parameters.get(key) if parameters is None: parameters = ( frozen_weight.to(device=x.device, dtype=x.dtype), frozen_bias.to(device=x.device, dtype=x.dtype), frozen_scale.to(device=x.device, dtype=x.dtype), ) device_parameters[key] = parameters return parameters def ref(x): weight, bias, scale = parameters_for(x) value = torch.nn.functional.linear(x, weight, bias) value = value * scale return torch.nn.functional.batch_norm( value, running_mean=None, running_var=None, weight=value.new_ones((output_features,)), bias=value.new_zeros((output_features,)), training=True, momentum=0.1, eps=epsilon, ) 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, 4096)") if x.shape[0] < 2: raise ValueError("BatchNorm training requires at least two samples") rows = x.shape[0] weight, bias, scale = parameters_for(x) out = torch_module.empty( (rows, output_features), device=x.device, dtype=x.dtype ) workspace = torch_module.empty_like(out) # The launcher supplies x and out automatically; retain all auxiliary # allocations until the asynchronous kernel has finished using them. out._substrate_keepalive = (workspace, weight, bias, scale) args = [ (ctypes.c_void_p, workspace.data_ptr()), (ctypes.c_void_p, weight.data_ptr()), (ctypes.c_void_p, bias.data_ptr()), (ctypes.c_void_p, scale.data_ptr()), (ctypes.c_int, rows), (ctypes.c_int, input_features), (ctypes.c_int, output_features), (ctypes.c_float, epsilon), ] grid = ((output_features + 255) // 256, 1, 1) return out, grid, (256, 1, 1), args def suites(): def t0_original(trial): torch.manual_seed(1000 + trial) return [torch.rand(16384, 4096)] def t1_signed(trial): torch.manual_seed(2000 + trial) return [torch.randn(17, 4096) * 0.05] def t2_misaligned(trial): torch.manual_seed(3000 + trial) return [torch.rand(13, 4096)] def t3_positive_tail_spikes(trial): torch.manual_seed(4000 + trial) value = torch.rand(9, 4096) value[:, -1] = 25.0 value[-1, -31:] = 10.0 return [value] def t4_sparse_fp16_overflow(trial): torch.manual_seed(5000 + trial) value = torch.zeros(7, 4096) value[:, 0] = torch.arange(1, 8, dtype=value.dtype) * 2.0e7 return [value] def t5_low_variance_row_ramp(trial): torch.manual_seed(6000 + trial) value = torch.zeros(11, 4096) value[:, 1] = 8.0 + torch.arange(11, dtype=value.dtype) * 0.125 return [value] def t6_large_baseline_fine_steps(trial): torch.manual_seed(7000 + trial) value = torch.zeros(13, 4096) value[:, 2] = 10000.0 + torch.arange(13, dtype=value.dtype) * 0.25 return [value] return [ ("T0_original", 5, t0_original), ("T1_signed", 1, t1_signed), ("T2_misaligned", 1, t2_misaligned), ("T3_positive_tail_spikes", 1, t3_positive_tail_spikes), ("T4_sparse_fp16_overflow", 1, t4_sparse_fp16_overflow), ("T5_low_variance_row_ramp", 1, t5_low_variance_row_ramp), ("T6_large_baseline_fine_steps", 1, t6_large_baseline_fine_steps), ] def probe(torch_module): torch_module.manual_seed(0) return [ ("p_aligned", [torch_module.rand(16, 4096)]), ("p_misaligned", [torch_module.randn(3, 4096) * 0.05]), ] K.PROBLEMS["L2p39_gemm_scale_batchnorm"] = dict( kb_file="39_Gemm_Scale_BatchNorm.py", cuda=CUDA_SOURCE, kernel_name="L2p39_gemm_scale_batchnorm_kernel", ref=ref, launch=launch, suites=suites, probe=probe, )