"""Correct, mutation-friendly substrate for KernelBench level2 problem 33.""" def register(K, torch, ctypes): cuda_source = r""" #include __global__ void L2p33_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 is x @ weight.T + bias. Each thread owns one output // feature, so it can also perform that feature's BatchNorm reduction. 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; // Welford's recurrence computes the biased population variance used // by BatchNorm's training-mode forward pass without cancellation. 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 start at gamma=1 and beta=0. out[output_index] = centered * inverse_standard_deviation; } } """ input_features = 8192 output_features = 8192 epsilon = 1.0e-5 # Reproduce Model construction order exactly: Linear first, then the # randn-initialized scale Parameter, then BatchNorm (whose affine defaults # are deterministic ones and zeros). Preserve the caller's RNG state. 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 a 2D input whose second dimension is 8192") 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) 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(1024, 8192)] def t1_signed(trial): torch.manual_seed(2000 + trial) return [torch.randn(17, 8192) * 0.05] def t2_misaligned(trial): torch.manual_seed(3000 + trial) return [torch.rand(13, 8192)] def t3_positive_tail_spikes(trial): torch.manual_seed(4000 + trial) x = torch.rand(9, 8192) x[:, -1] = 25.0 x[-1, -32:] = 10.0 return [x] def t4_near_duplicate_pair(trial): torch.manual_seed(5000 + trial) x = torch.full((2, 8192), 0.25) x[1, 0] += 0.01 x[1, -1] += 0.02 return [x] def t5_positive_positional_overflow(trial): torch.manual_seed(6000 + trial) position = torch.arange(8192, dtype=torch.float32) / 8191.0 row_scale = torch.linspace(0.75, 1.25, 17).unsqueeze(1) x = (20000.0 + 100000.0 * position).unsqueeze(0) * row_scale return [x] 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_near_duplicate_pair", 1, t4_near_duplicate_pair), ("T5_positive_positional_overflow", 1, t5_positive_positional_overflow), ] def probe(torch_module): torch_module.manual_seed(0) return [ ("p_aligned", [torch_module.rand(16, 8192)]), ("p_misaligned", [torch_module.randn(3, 8192) * 0.05]), ] K.PROBLEMS["L2p33_gemm_scale_batchnorm"] = dict( kb_file="33_Gemm_Scale_BatchNorm.py", cuda=cuda_source, kernel_name="L2p33_gemm_scale_batchnorm_kernel", ref=ref, launch=launch, suites=suites, probe=probe, )