"""Correct, mutation-friendly substrate for KernelBench level2 problem 11.""" def register(K, torch, ctypes): cuda_source = r""" #include __global__ void L2p11_convtranspose2d_batchn_kernel( const float* x, float* out, float* workspace, const float* weight, const float* bias, int batches, int input_height, int input_width, int conv_height, int conv_width, int pool_height, int pool_width) { int tid = threadIdx.x; long long conv_spatial = (long long)conv_height * conv_width; long long pool_spatial = (long long)pool_height * pool_width; long long conv_elements = (long long)batches * 128 * conv_spatial; long long pool_elements = (long long)batches * 128 * pool_spatial; // ConvTranspose2d: Cin=64, Cout=128, K=5, stride=1, padding=1, // output_padding=0, groups=1, dilation=1, and bias=True. for (long long linear = tid; linear < conv_elements; linear += blockDim.x) { long long position = linear; int ox = (int)(position % conv_width); position /= conv_width; int oy = (int)(position % conv_height); position /= conv_height; int oc = (int)(position % 128); int n = (int)(position / 128); float sum = bias[oc]; for (int ic = 0; ic < 64; ic++) { for (int ky = 0; ky < 5; ky++) { int iy = oy + 1 - ky; if (iy < 0 || iy >= input_height) continue; for (int kx = 0; kx < 5; kx++) { int ix = ox + 1 - kx; if (ix < 0 || ix >= input_width) continue; long long xi = (((long long)n * 64 + ic) * input_height + iy) * input_width + ix; // ConvTranspose2d weights are [Cin, Cout, Kh, Kw]. long long wi = (((long long)ic * 128 + oc) * 5 + ky) * 5 + kx; sum += x[xi] * weight[wi]; } } } workspace[linear] = sum; } __syncthreads(); // sync-after-convolution // BatchNorm2d in training mode: statistics span N,H,W independently for // each channel, and the forward variance is the biased population value. __shared__ float reduce_sum[256]; __shared__ float reduce_sq[256]; for (int c = 0; c < 128; c++) { float local_sum = 0.0f; float local_sq = 0.0f; long long samples = (long long)batches * conv_spatial; for (long long sample = tid; sample < samples; sample += blockDim.x) { long long n = sample / conv_spatial; long long s = sample - n * conv_spatial; float value = workspace[(n * 128 + c) * conv_spatial + s]; local_sum += value; local_sq += value * value; } reduce_sum[tid] = local_sum; reduce_sq[tid] = local_sq; __syncthreads(); // sync-after-batchnorm-partials for (int width = 128; width > 0; width >>= 1) { if (tid < width) { reduce_sum[tid] += reduce_sum[tid + width]; reduce_sq[tid] += reduce_sq[tid + width]; } __syncthreads(); // sync-during-batchnorm-reduction } float mean = reduce_sum[0] / (float)samples; float variance = reduce_sq[0] / (float)samples - mean * mean; variance = fmaxf(variance, 0.0f); float inv_std = rsqrtf(variance + 1.0e-5f); for (long long sample = tid; sample < samples; sample += blockDim.x) { long long n = sample / conv_spatial; long long s = sample - n * conv_spatial; long long index = (n * 128 + c) * conv_spatial + s; workspace[index] = tanhf((workspace[index] - mean) * inv_std); } __syncthreads(); // sync-after-batchnorm-and-tanh } // MaxPool2d defaults: kernel=2, stride=2, padding=0, dilation=1, // ceil_mode=False. conv_height and conv_width are even here. for (long long linear = tid; linear < pool_elements; linear += blockDim.x) { long long position = linear; int px = (int)(position % pool_width); position /= pool_width; int py = (int)(position % pool_height); position /= pool_height; int c = (int)(position % 128); int n = (int)(position / 128); long long base = ((long long)n * 128 + c) * conv_spatial + (long long)(2 * py) * conv_width + 2 * px; float best = workspace[base]; best = fmaxf(best, workspace[base + 1]); best = fmaxf(best, workspace[base + conv_width]); best = fmaxf(best, workspace[base + conv_width + 1]); out[linear] = best; } __syncthreads(); // sync-after-maxpool // GroupNorm: 8 groups, hence 16 channels per group. Statistics are per // sample and group, with biased variance and affine defaults gamma=1,beta=0. for (int ng = 0; ng < batches * 8; ng++) { int n = ng / 8; int group = ng - n * 8; long long group_samples = 16 * pool_spatial; float local_sum = 0.0f; float local_sq = 0.0f; for (long long i = tid; i < group_samples; i += blockDim.x) { int channel_in_group = (int)(i / pool_spatial); long long s = i - (long long)channel_in_group * pool_spatial; int c = group * 16 + channel_in_group; float value = out[((long long)n * 128 + c) * pool_spatial + s]; local_sum += value; local_sq += value * value; } reduce_sum[tid] = local_sum; reduce_sq[tid] = local_sq; __syncthreads(); // sync-after-groupnorm-partials for (int width = 128; width > 0; width >>= 1) { if (tid < width) { reduce_sum[tid] += reduce_sum[tid + width]; reduce_sq[tid] += reduce_sq[tid + width]; } __syncthreads(); // sync-during-groupnorm-reduction } float mean = reduce_sum[0] / (float)group_samples; float variance = reduce_sq[0] / (float)group_samples - mean * mean; variance = fmaxf(variance, 0.0f); float inv_std = rsqrtf(variance + 1.0e-5f); for (long long i = tid; i < group_samples; i += blockDim.x) { int channel_in_group = (int)(i / pool_spatial); long long s = i - (long long)channel_in_group * pool_spatial; int c = group * 16 + channel_in_group; long long index = ((long long)n * 128 + c) * pool_spatial + s; out[index] = (out[index] - mean) * inv_std; } __syncthreads(); // sync-after-groupnorm-output } } """ # get_init_inputs() fixes (64,128,5,1,1,8,8). The `groups` argument is # not passed to ConvTranspose2d in the KB model and therefore does not # affect it. Freeze the ordinary default ConvTranspose2d initialization. with torch.random.fork_rng(devices=[]): torch.manual_seed(0) layer = torch.nn.ConvTranspose2d(64, 128, 5, stride=1, padding=1) frozen_weight = layer.weight.detach().cpu().contiguous() frozen_bias = layer.bias.detach().cpu().contiguous() device_parameters = {} def parameters_for(x): key = (x.device.type, x.device.index, x.dtype) pair = device_parameters.get(key) if pair is None: pair = (frozen_weight.to(device=x.device, dtype=x.dtype), frozen_bias.to(device=x.device, dtype=x.dtype)) device_parameters[key] = pair return pair def ref(x): weight, bias = parameters_for(x) value = torch.nn.functional.conv_transpose2d( x, weight, bias=bias, stride=1, padding=1, output_padding=0, groups=1, dilation=1) value = torch.nn.functional.batch_norm( value, running_mean=None, running_var=None, weight=value.new_ones((128,)), bias=value.new_zeros((128,)), training=True, momentum=0.1, eps=1e-5) value = torch.tanh(value) value = torch.nn.functional.max_pool2d( value, kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) return torch.nn.functional.group_norm( value, num_groups=8, weight=value.new_ones((128,)), bias=value.new_zeros((128,)), eps=1e-5) def launch(inputs, torch_module): x = inputs[0] batches, channels, input_height, input_width = x.shape if channels != 64: raise ValueError("level2 problem 11 requires 64 input channels") conv_height = input_height + 2 conv_width = input_width + 2 pool_height = conv_height // 2 pool_width = conv_width // 2 workspace = torch_module.empty( (batches, 128, conv_height, conv_width), device=x.device, dtype=x.dtype) out = torch_module.empty( (batches, 128, pool_height, pool_width), device=x.device, dtype=x.dtype) # Keep allocations and frozen parameters alive through asynchronous use. weight, bias = parameters_for(x) out._substrate_keepalive = (workspace, weight, bias) args = [ (ctypes.c_void_p, workspace.data_ptr()), (ctypes.c_void_p, weight.data_ptr()), (ctypes.c_void_p, bias.data_ptr()), (ctypes.c_int, batches), (ctypes.c_int, input_height), (ctypes.c_int, input_width), (ctypes.c_int, conv_height), (ctypes.c_int, conv_width), (ctypes.c_int, pool_height), (ctypes.c_int, pool_width), ] return out, (1, 1, 1), (256, 1, 1), args def suites(): def t0_original(trial): torch.manual_seed(1000 + trial) return [torch.rand(512, 64, 32, 32)] def t1_signed(trial): torch.manual_seed(2000 + trial) return [torch.randn(3, 64, 9, 13)] def t2_misaligned(trial): torch.manual_seed(3000 + trial) return [torch.rand(5, 64, 11, 15)] def t3_positive_spikes(trial): torch.manual_seed(4000 + trial) x = torch.rand(2, 64, 10, 14) x[:, :, 0, 0] = 25.0 x[:, :, -1, -1] = 50.0 return [x] def t4_zero_variance_ties(trial): torch.manual_seed(5000 + trial) return [torch.zeros(7, 64, 7, 9)] def t5_lane_alternating_magnitude(trial): torch.manual_seed(6000 + trial) x = torch.empty(5, 64, 13, 17) positions = torch.arange(x.numel(), dtype=x.dtype).reshape_as(x) x.copy_(torch.where((positions.to(torch.int64) & 1) == 0, torch.full_like(x, 1.0e-4), torch.full_like(x, 300.0))) return [x] def t6_positive_positional_spikes(trial): torch.manual_seed(7000 + trial) y = torch.arange(15, dtype=torch.float32).view(1, 1, 15, 1) xcoord = torch.arange(19, dtype=torch.float32).view(1, 1, 1, 19) channel = torch.arange(64, dtype=torch.float32).view(1, 64, 1, 1) x = 100.0 + 3.0 * y + 5.0 * xcoord + (channel % 7) * 11.0 x = x.expand(4, -1, -1, -1).clone() x[:, :, ::4, 1::5] = 1200.0 return [x] def t7_positive_near_constant_quantization(trial): torch.manual_seed(8000 + trial) y = torch.arange(10, dtype=torch.float32).view(1, 1, 10, 1) xcoord = torch.arange(14, dtype=torch.float32).view(1, 1, 1, 14) channel = torch.arange(64, dtype=torch.float32).view(1, 64, 1, 1) batch = torch.arange(3, dtype=torch.float32).view(3, 1, 1, 1) x = (192.0 + 0.03125 * ((3.0 * y + 5.0 * xcoord + channel + 7.0 * batch) % 17.0)) return [x.contiguous()] def t8_batch_lane_stripes(trial): torch.manual_seed(9000 + trial) batch = torch.arange(129, dtype=torch.int64).view(129, 1, 1, 1) channel = torch.arange(64, dtype=torch.int64).view(1, 64, 1, 1) y = torch.arange(2, dtype=torch.int64).view(1, 1, 2, 1) xcoord = torch.arange(2, dtype=torch.int64).view(1, 1, 1, 2) stripe = (batch + channel + 2 * y + xcoord) & 1 x = torch.where(stripe == 0, torch.full(stripe.shape, 1.0e-3), torch.full(stripe.shape, 900.0)) return [x] def t9_tied_pool_spikes(trial): torch.manual_seed(10000 + trial) x = torch.full((4, 64, 6, 10), 0.125) x[:, ::2, ::2, ::2] = 700.0 x[:, 1::2, 1::2, 1::2] = 700.0 x[:, :, 2:4, 4:6] = 1400.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_ties", 1, t4_zero_variance_ties), ("T5_lane_alternating_magnitude", 1, t5_lane_alternating_magnitude), ("T6_positive_positional_spikes", 1, t6_positive_positional_spikes), ("T7_positive_near_constant_quantization", 1, t7_positive_near_constant_quantization), ("T8_batch_lane_stripes", 1, t8_batch_lane_stripes), ("T9_tied_pool_spikes", 1, t9_tied_pool_spikes), ] def probe(torch_module): torch_module.manual_seed(0) return [ ("p_aligned", [torch_module.rand(2, 64, 14, 14)]), ("p_misaligned", [torch_module.randn(1, 64, 7, 11)]), ] K.PROBLEMS["L2p11_convtranspose2d_batchn"] = dict( kb_file="11_ConvTranspose2d_BatchNorm_Tanh_MaxPool_GroupNorm.py", cuda=cuda_source, kernel_name="L2p11_convtranspose2d_batchn_kernel", ref=ref, launch=launch, suites=suites, probe=probe, )