KernelBench-M / substrates /candidate_L2p42_convtranspose2d_global.py
Elfsong's picture
KernelBench-M artifact: rules, substrates, witnesses, pipeline, summaries
1276a5c verified
Raw History Blame Contribute Delete
10.8 kB
"""Correct, mutation-friendly substrate for KernelBench level-2 problem 42."""
CUDA_SOURCE = r"""
#include <cuda_fp16.h>
__global__ void l2p42_convtranspose2d_global_kernel(
const float* x, float* out, const float* weight,
const float* convolution_bias, const float* added_bias,
int batches, int input_height, int input_width,
long long input_plane_elements) {
int batch = blockIdx.x * blockDim.x + threadIdx.x;
if (batch >= batches) return;
// With the problem's default stride=1, padding=0, dilation=1 and a 3x3
// kernel, every input value contributes once through every kernel weight.
// Thus the exact real-valued spatial sum of ConvTranspose2d can be formed
// without materializing its very large [128, H+2, W+2] result.
double input_sums[64];
for (int input_channel = 0; input_channel < 64; input_channel++) {
double channel_sum = 0.0;
long long base =
((long long)batch * 64 + input_channel) * input_plane_elements;
for (long long spatial = 0; spatial < input_plane_elements; spatial++) {
channel_sum += (double)x[base + spatial];
}
input_sums[input_channel] = channel_sum;
}
long long output_height = (long long)input_height + 2;
long long output_width = (long long)input_width + 2;
double output_area = (double)(output_height * output_width);
// Stable log-sum-exp pass 1: find the maximum channel value.
float maximum = -3.402823466e+38F;
for (int output_channel = 0; output_channel < 128; output_channel++) {
double convolution_sum =
(double)convolution_bias[output_channel] * output_area;
for (int input_channel = 0; input_channel < 64; input_channel++) {
double kernel_sum = 0.0;
long long weight_base =
((long long)input_channel * 128 + output_channel) * 9;
for (int kernel_element = 0; kernel_element < 9; kernel_element++) {
kernel_sum += (double)weight[weight_base + kernel_element];
}
convolution_sum += input_sums[input_channel] * kernel_sum;
}
float pooled = (float)(convolution_sum / output_area);
float value = pooled + added_bias[output_channel];
if (value > maximum) { maximum = value; }
}
// Stable log-sum-exp pass 2: accumulate exp(value - maximum).
double exponential_sum = 0.0;
for (int output_channel = 0; output_channel < 128; output_channel++) {
double convolution_sum =
(double)convolution_bias[output_channel] * output_area;
for (int input_channel = 0; input_channel < 64; input_channel++) {
double kernel_sum = 0.0;
long long weight_base =
((long long)input_channel * 128 + output_channel) * 9;
for (int kernel_element = 0; kernel_element < 9; kernel_element++) {
kernel_sum += (double)weight[weight_base + kernel_element];
}
convolution_sum += input_sums[input_channel] * kernel_sum;
}
float pooled = (float)(convolution_sum / output_area);
float value = pooled + added_bias[output_channel];
exponential_sum += exp((double)value - (double)maximum);
}
// The spatial sum is over two singleton dimensions, then multiplication
// by the problem's literal factor 10.0 is applied.
out[batch] = (maximum + (float)log(exponential_sum)) * 10.0f;
}
"""
def register(K, torch, ctypes):
# Reproduce Model.__init__ construction order exactly: ConvTranspose2d
# initializes its weight and bias before the separate bias parameter is
# sampled. fork_rng prevents registration from perturbing suite RNG.
with torch.random.fork_rng(devices=[]):
torch.manual_seed(0)
convolution = torch.nn.ConvTranspose2d(64, 128, 3)
frozen_weight = convolution.weight.detach().cpu().contiguous()
frozen_convolution_bias = convolution.bias.detach().cpu().contiguous()
frozen_added_bias = torch.randn(128, 1, 1).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_convolution_bias.to(device=x.device, dtype=x.dtype),
frozen_added_bias.to(device=x.device, dtype=x.dtype),
)
device_parameters[key] = parameters
return parameters
def ref(x):
weight, convolution_bias, added_bias = parameters_for(x)
value = torch.nn.functional.conv_transpose2d(
x, weight, bias=convolution_bias, stride=1, padding=0,
output_padding=0, groups=1, dilation=1,
)
value = torch.mean(value, dim=(2, 3), keepdim=True)
value = value + added_bias
value = torch.logsumexp(value, dim=1, keepdim=True)
value = torch.sum(value, dim=(2, 3))
return value * 10.0
def launch(inputs, torch_module):
x = inputs[0]
batches, input_channels, input_height, input_width = x.shape
if input_channels != 64:
raise ValueError("level-2 problem 42 requires 64 input channels")
out = torch_module.empty((batches, 1), device=x.device, dtype=x.dtype)
weight, convolution_bias, added_bias = parameters_for(x)
args = [
(ctypes.c_void_p, weight.data_ptr()),
(ctypes.c_void_p, convolution_bias.data_ptr()),
(ctypes.c_void_p, added_bias.data_ptr()),
(ctypes.c_int, batches),
(ctypes.c_int, input_height),
(ctypes.c_int, input_width),
(ctypes.c_longlong, input_height * input_width),
]
return out, ((batches + 31) // 32, 1, 1), (32, 1, 1), args
def suites():
def t0_original(trial):
torch.manual_seed(1000 + trial)
return [torch.rand(16, 64, 512, 512)]
def t1_signed(trial):
torch.manual_seed(2000 + trial)
return [torch.randn(3, 64, 17, 19)]
def t2_misaligned(trial):
torch.manual_seed(3000 + trial)
return [torch.rand(5, 64, 13, 23)]
def t3_positive_spikes(trial):
torch.manual_seed(4000 + trial)
value = torch.rand(2, 64, 15, 21)
value[:, :, 0, 0] = 8.0
value[:, :, 7, 10] = 16.0
value[:, :, -1, -1] = 32.0
return [value]
def t4_batch_channel_ramp(trial):
torch.manual_seed(5000 + trial)
batches = torch.arange(1, 36, dtype=torch.float32).view(35, 1, 1, 1)
channels = torch.arange(1, 65, dtype=torch.float32).view(1, 64, 1, 1)
return [batches * channels]
def t5_spatial_endpoint_mass(trial):
torch.manual_seed(6000 + trial)
value = torch.full((3, 64, 4, 7), 1.0e-3)
value[:, :, 0, 0] = 128.0
value[:, :, -1, -1] = 512.0
value[:, :, 1::2, ::2] = 16.0
value[1] *= 2.0
value[2] *= 4.0
return [value]
def t6_logsumexp_boundary_channels(trial):
torch.manual_seed(7000 + trial)
value = torch.full((2, 64, 1, 1), 1.0e-3)
first_indices = torch.tensor(
[40, 11, 8, 22, 7, 26, 16, 45, 39, 37, 0, 1]
)
first_values = torch.tensor(
[162.0730, 143.5425, 34.3775, 33.7617, 22.1465, 19.4723,
18.3616, 15.1175, 11.7721, 10.5353, 7.8902, 7.2196]
)
last_indices = torch.tensor(
[22, 4, 6, 19, 17, 60, 21, 29, 8, 55, 0, 3]
)
last_values = torch.tensor(
[1696.1362, 227.4342, 74.3800, 71.9238, 65.3781, 61.1874,
51.2348, 27.8109, 26.5850, 17.2303, 15.3442, 11.7452]
)
value[0, first_indices, 0, 0] = first_values
value[1, last_indices, 0, 0] = last_values
return [value]
def t7_first_spatial_mass(trial):
torch.manual_seed(8000 + trial)
value = torch.full((3, 64, 2, 5), 1.0e-4)
channels = torch.arange(1, 65, dtype=torch.float32)
value[0, :, 0, 0] = channels * 8.0
value[1, :, 0, 0] = channels.flip(0) * 16.0
value[2, 0::2, 0, 0] = 1024.0
value[2, 1::2, 0, 0] = 4.0
return [value]
def t8_positional_checkerboard(trial):
torch.manual_seed(9000 + trial)
rows = torch.arange(1, 4, dtype=torch.float32).view(1, 1, 3, 1)
columns = torch.arange(1, 6, dtype=torch.float32).view(1, 1, 1, 5)
channels = torch.arange(1, 65, dtype=torch.float32).view(1, 64, 1, 1)
value = channels * 0.125 + rows * 16.0 + columns
value[:, 0::2, 0::2, 1::2] *= 16.0
value[:, 1::2, 1::2, 0::2] *= 32.0
return [value.contiguous()]
def t9_batch_channel_codes(trial):
torch.manual_seed(10000 + trial)
batches = torch.arange(1, 36, dtype=torch.float32).view(35, 1, 1, 1)
channels = torch.arange(1, 65, dtype=torch.float32).view(1, 64, 1, 1)
value = torch.full((35, 64, 1, 3), 1.0e-3)
value[:, :, 0, 0] = batches[:, :, 0, 0] * 4.0
value[:, :, 0, 1] = channels[:, :, 0, 0] * 8.0
value[:, :, 0, 2] = batches[:, :, 0, 0] * channels[:, :, 0, 0]
return [value]
return [
("T0_original", 5, t0_original),
("T1_signed", 1, t1_signed),
("T2_misaligned", 1, t2_misaligned),
("T3_positive_spikes", 1, t3_positive_spikes),
("T4_batch_channel_ramp", 1, t4_batch_channel_ramp),
("T5_spatial_endpoint_mass", 1, t5_spatial_endpoint_mass),
("T6_logsumexp_boundary_channels", 1, t6_logsumexp_boundary_channels),
("T7_first_spatial_mass", 1, t7_first_spatial_mass),
("T8_positional_checkerboard", 1, t8_positional_checkerboard),
("T9_batch_channel_codes", 1, t9_batch_channel_codes),
]
def probe(torch_module):
torch_module.manual_seed(0)
return [
("p_aligned", [torch_module.rand(1, 64, 16, 16)]),
("p_misaligned", [torch_module.randn(2, 64, 7, 11)]),
]
K.PROBLEMS["L2p42_convtranspose2d_global"] = dict(
kb_file="42_ConvTranspose2d_GlobalAvgPool_BiasAdd_LogSumExp_Sum_Multiply.py",
cuda=CUDA_SOURCE,
kernel_name="l2p42_convtranspose2d_global_kernel",
ref=ref,
launch=launch,
suites=suites,
probe=probe,
)