"""Mutation-friendly substrate for KernelBench level 2 problem 15.""" CUDA_SOURCE = r""" #include __global__ void L2p15_convtranspose3d_batchn_kernel( const float* x, float* out, const float* weight, const float* bias, int batches, int input_depth, int input_height, int input_width, int output_depth, int output_height, int output_width) { int output_channel = blockIdx.x; int tid = threadIdx.x; long long input_spatial = (long long)input_depth * input_height * input_width; long long output_spatial = (long long)output_depth * output_height * output_width; long long channel_elements = (long long)batches * output_spatial; long long passes = (channel_elements + 255) / 256; __shared__ float partial[256]; // First materialize ConvTranspose3d. Its weight layout is // [input_channel, output_channel, kz, ky, kx]. float local_sum = 0.0f; for (long long pass = 0; pass < passes; pass++) { long long channel_index = pass * 256 + tid; if (channel_index < channel_elements) { int batch = (int)(channel_index / output_spatial); long long spatial_index = channel_index % output_spatial; int output_x = (int)(spatial_index % output_width); spatial_index /= output_width; int output_y = (int)(spatial_index % output_height); int output_z = (int)(spatial_index / output_height); float value = bias[output_channel]; for (int input_channel = 0; input_channel < 16; input_channel++) { for (int kernel_z = 0; kernel_z < 3; kernel_z++) { int z_numerator = output_z + 1 - kernel_z; if (z_numerator < 0 || (z_numerator & 1)) continue; int input_z = z_numerator / 2; if (input_z >= input_depth) continue; for (int kernel_y = 0; kernel_y < 3; kernel_y++) { int y_numerator = output_y + 1 - kernel_y; if (y_numerator < 0 || (y_numerator & 1)) continue; int input_y = y_numerator / 2; if (input_y >= input_height) continue; for (int kernel_x = 0; kernel_x < 3; kernel_x++) { int x_numerator = output_x + 1 - kernel_x; if (x_numerator < 0 || (x_numerator & 1)) continue; int input_x = x_numerator / 2; if (input_x >= input_width) continue; long long input_index = (long long)batch * 16 * input_spatial + (long long)input_channel * input_spatial + ((long long)input_z * input_height + input_y) * input_width + input_x; long long weight_index = (((((long long)input_channel * 32 + output_channel) * 3 + kernel_z) * 3 + kernel_y) * 3 + kernel_x); value += x[input_index] * weight[weight_index]; } } } } long long output_index = (long long)batch * 32 * output_spatial + (long long)output_channel * output_spatial + channel_index % output_spatial; out[output_index] = value; local_sum += value; } } partial[tid] = local_sum; __syncthreads(); // sync-after-global-sum-store for (int offset = 128; offset > 0; offset >>= 1) { if (tid < offset) { partial[tid] += partial[tid + offset]; } __syncthreads(); // sync-during-global-sum-reduction } float global_mean = partial[0] / (float)channel_elements; // BatchNorm3d uses the biased, population variance for its output. float local_square_deviation = 0.0f; for (long long pass = 0; pass < passes; pass++) { long long channel_index = pass * 256 + tid; if (channel_index < channel_elements) { int batch = (int)(channel_index / output_spatial); long long spatial_index = channel_index % output_spatial; long long output_index = (long long)batch * 32 * output_spatial + (long long)output_channel * output_spatial + spatial_index; float centered = out[output_index] - global_mean; local_square_deviation += centered * centered; } } partial[tid] = local_square_deviation; __syncthreads(); // sync-after-variance-store for (int offset = 128; offset > 0; offset >>= 1) { if (tid < offset) { partial[tid] += partial[tid + offset]; } __syncthreads(); // sync-during-variance-reduction } float inverse_std = rsqrtf(partial[0] / (float)channel_elements + 1.0e-5f); __syncthreads(); // sync-before-sample-loop // Subtracting each sample's spatial mean after BatchNorm cancels the // convolution bias, BN beta, and global BN mean. Default BN gamma is 1. long long sample_passes = (output_spatial + 255) / 256; for (int batch = 0; batch < batches; batch++) { float local_sample_sum = 0.0f; long long sample_base = (long long)batch * 32 * output_spatial + (long long)output_channel * output_spatial; for (long long pass = 0; pass < sample_passes; pass++) { long long spatial_index = pass * 256 + tid; if (spatial_index < output_spatial) { local_sample_sum += out[sample_base + spatial_index]; } } partial[tid] = local_sample_sum; __syncthreads(); // sync-after-sample-sum-store for (int offset = 128; offset > 0; offset >>= 1) { if (tid < offset) { partial[tid] += partial[tid + offset]; } __syncthreads(); // sync-during-sample-sum-reduction } float sample_mean = partial[0] / (float)output_spatial; __syncthreads(); // sync-before-sample-write for (long long pass = 0; pass < sample_passes; pass++) { long long spatial_index = pass * 256 + tid; if (spatial_index < output_spatial) { float value = out[sample_base + spatial_index]; out[sample_base + spatial_index] = (value - sample_mean) * inverse_std; } } __syncthreads(); // sync-after-sample-write } } """ def register(K, torch, ctypes): """Register the device-only kernel and deterministic input families.""" # get_init_inputs() is [16, 32, 3, 2, 1], with bias retaining its # constructor default True. Freeze one ordinary default initialization # for the reference and CUDA paths while preserving the caller's CPU RNG. with torch.random.fork_rng(devices=[]): torch.manual_seed(0) module = torch.nn.ConvTranspose3d( 16, 32, 3, stride=2, padding=1, bias=True) frozen_weight = module.weight.detach().cpu().contiguous() frozen_bias = module.bias.detach().cpu().contiguous() device_parameters = {} def parameters_for(x): key = (x.device.type, x.device.index, x.dtype) values = device_parameters.get(key) if values is None: values = ( frozen_weight.to(device=x.device, dtype=x.dtype), frozen_bias.to(device=x.device, dtype=x.dtype), ) device_parameters[key] = values return values def ref(x): weight, bias = parameters_for(x) value = torch.nn.functional.conv_transpose3d( x, weight, bias=bias, stride=2, padding=1, output_padding=0, groups=1, dilation=1) value = torch.nn.functional.batch_norm( value, running_mean=None, running_var=None, weight=None, bias=None, training=True, momentum=0.1, eps=1.0e-5) return value - torch.mean(value, dim=(2, 3, 4), keepdim=True) def launch(inputs, torch_module): x = inputs[0] batches, input_channels, input_depth, input_height, input_width = x.shape if input_channels != 16: raise ValueError("level 2 problem 15 requires 16 input channels") output_depth = 2 * input_depth - 1 output_height = 2 * input_height - 1 output_width = 2 * input_width - 1 out = torch_module.empty( (batches, 32, output_depth, output_height, output_width), device=x.device, dtype=x.dtype) weight, bias = parameters_for(x) args = [ (ctypes.c_void_p, weight.data_ptr()), (ctypes.c_void_p, bias.data_ptr()), (ctypes.c_int, batches), (ctypes.c_int, input_depth), (ctypes.c_int, input_height), (ctypes.c_int, input_width), (ctypes.c_int, output_depth), (ctypes.c_int, output_height), (ctypes.c_int, output_width), ] return out, (32, 1, 1), (256, 1, 1), args def suites(): def t0_original(trial): torch.manual_seed(1000 + trial) return [torch.rand(16, 16, 16, 32, 32)] def t1_signed(trial): torch.manual_seed(2000 + trial) return [torch.randn(2, 16, 5, 7, 9)] def t2_misaligned(trial): torch.manual_seed(3000 + trial) return [torch.rand(3, 16, 4, 6, 11)] def t3_positive_spikes(trial): torch.manual_seed(4000 + trial) x = torch.rand(2, 16, 5, 7, 9) x[:, :, 0, 0, 0] = 20.0 x[:, :, -1, -1, -1] = 40.0 return [x] def t4_zero_variance_eps(trial): torch.manual_seed(5000 + trial) return [torch.zeros(2, 16, 3, 5, 7)] def t5_positive_alternating_lanes(trial): torch.manual_seed(6000 + trial) x = torch.full((3, 16, 5, 8, 9), 1.0e-3) x.view(-1)[1::2] = 3000.0 return [x] def t6_batch_tail_spikes(trial): torch.manual_seed(7000 + trial) x = torch.full((5, 16, 4, 6, 11), 1.0e-3) x[1::2] = 2000.0 x[:, :, -1, -1, -1] = 3000.0 return [x] def t7_small_misaligned_boundary_spikes(trial): torch.manual_seed(8000 + trial) x = torch.full((7, 16, 2, 3, 5), 2.0e-2) x[:, :, 0, 0, 0] = 400.0 x[:, :, -1, -1, -1] = 2400.0 x[-1, :, :, :, -1] = 3000.0 return [x] def t8_positive_spatial_checkerboard(trial): torch.manual_seed(9000 + trial) x = torch.full((3, 16, 4, 5, 10), 1.0e-3) x[:, :, :, :, 1::2] = 1800.0 x[:, 1::2, 1::2, ::2, :] = 3000.0 return [x] def t9_batch_channel_positional_ramp(trial): torch.manual_seed(10000 + trial) x = torch.full((5, 16, 3, 4, 7), 1.0e-2) batch = torch.arange(5, dtype=x.dtype).view(5, 1, 1, 1, 1) channel = torch.arange(16, dtype=x.dtype).view(1, 16, 1, 1, 1) width = torch.arange(7, dtype=x.dtype).view(1, 1, 1, 1, 7) x += 120.0 * batch + 35.0 * channel + 210.0 * width x[:, :, -1, -1, -1] = 3000.0 return [x] return [ ("T0_original", 5, t0_original), ("T1_signed", 1, t1_signed), ("T2_misaligned", 1, t2_misaligned), ("T3_positive_spikes", 1, t3_positive_spikes), ("T4_zero_variance_eps", 1, t4_zero_variance_eps), ("T5_positive_alternating_lanes", 1, t5_positive_alternating_lanes), ("T6_batch_tail_spikes", 1, t6_batch_tail_spikes), ("T7_small_misaligned_boundary_spikes", 1, t7_small_misaligned_boundary_spikes), ("T8_positive_spatial_checkerboard", 1, t8_positive_spatial_checkerboard), ("T9_batch_channel_positional_ramp", 1, t9_batch_channel_positional_ramp), ] def probe(torch_module): torch_module.manual_seed(0) return [ ("p_aligned", [torch_module.rand(1, 16, 4, 8, 8)]), ("p_misaligned", [torch_module.randn(2, 16, 3, 5, 7)]), ] K.PROBLEMS["L2p15_convtranspose3d_batchn"] = dict( kb_file="15_ConvTranspose3d_BatchNorm_Subtract.py", cuda=CUDA_SOURCE, kernel_name="L2p15_convtranspose3d_batchn_kernel", ref=ref, launch=launch, suites=suites, probe=probe, )