diff --git a/S1/wut0n_#34/instancenorm_dropout_cudacode.py b/S1/wut0n_#34/instancenorm_dropout_cudacode.py new file mode 100644 index 00000000..286e6277 --- /dev/null +++ b/S1/wut0n_#34/instancenorm_dropout_cudacode.py @@ -0,0 +1,196 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.cpp_extension import load_inline + +instancenorm_dropout_source = """ +#include +#include +#include +#include + +// 分块归约函数 +__inline__ __device__ void blockReduceSum(float* sdata, float val, int tid) { + sdata[tid] = val; + __syncthreads(); + + for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) { + if (tid < stride) { + sdata[tid] += sdata[tid + stride]; + } + __syncthreads(); + } +} + +// InstanceNorm + Dropout融合kernel +__global__ void instancenorm_dropout_kernel( + const float* __restrict__ x, + const float* __restrict__ weight, + const float* __restrict__ bias, + const float* __restrict__ dropout_mask, // 预生成的dropout mask + float* __restrict__ y, + int batch, int channels, int height, int width, + float eps, float dropout_scale, bool training +) { + int spatial_size = height * width; + int instance_idx = blockIdx.x; + int channel_idx = blockIdx.y; + + if (instance_idx >= batch || channel_idx >= channels) return; + + int tid = threadIdx.x; + int instance_offset = instance_idx * channels * spatial_size + channel_idx * spatial_size; + + // 共享内存:sum和sum_sq + extern __shared__ float shared_mem[]; + float* sum_smem = shared_mem; + float* sum_sq_smem = shared_mem + blockDim.x; + + // 每个线程计算部分和 + float local_sum = 0.0f; + float local_sum_sq = 0.0f; + + for (int i = tid; i < spatial_size; i += blockDim.x) { + float val = x[instance_offset + i]; + local_sum += val; + local_sum_sq += val * val; + } + + // 归约求和 + blockReduceSum(sum_smem, local_sum, tid); + blockReduceSum(sum_sq_smem, local_sum_sq, tid); + + // 计算统计量并广播 + __shared__ float mean_val; + __shared__ float inv_std_val; + __shared__ float weight_val; + __shared__ float bias_val; + + if (tid == 0) { + float mean = sum_smem[0] / spatial_size; + float var = (sum_sq_smem[0] / spatial_size) - (mean * mean); + var = fmaxf(var, 0.0f); + + mean_val = mean; + inv_std_val = rsqrtf(var + eps); + weight_val = weight[channel_idx]; + bias_val = bias[channel_idx]; + } + __syncthreads(); + + // 应用InstanceNorm + Dropout + for (int i = tid; i < spatial_size; i += blockDim.x) { + int idx = instance_offset + i; + int mask_idx = instance_idx * channels * spatial_size + channel_idx * spatial_size + i; + + float val = x[idx]; + float normalized = (val - mean_val) * inv_std_val * weight_val + bias_val; + + if (training) { + // 使用预生成的mask:0表示丢弃,dropout_scale表示保留并缩放 + y[idx] = normalized * dropout_mask[mask_idx]; + } else { + // 推理模式:只应用InstanceNorm + y[idx] = normalized; + } + } +} + +torch::Tensor instancenorm_dropout_cuda_forward( + torch::Tensor x, torch::Tensor weight, torch::Tensor bias, + torch::Tensor dropout_mask, float eps, float dropout_scale, bool training +) { + auto x_contig = x.contiguous(); + int batch = x_contig.size(0); + int channels = x_contig.size(1); + int height = x_contig.size(2); + int width = x_contig.size(3); + + auto y = torch::empty_like(x_contig); + + dim3 blocks(batch, channels); + int threads = 256; + size_t shared_mem = 2 * threads * sizeof(float) + 4 * sizeof(float); + + instancenorm_dropout_kernel<<>>( + x_contig.data_ptr(), + weight.data_ptr(), + bias.data_ptr(), + dropout_mask.data_ptr(), + y.data_ptr(), + batch, channels, height, width, eps, dropout_scale, training + ); + + return y; +} +""" + +instancenorm_dropout_cpp_source = """ +torch::Tensor instancenorm_dropout_cuda_forward( + torch::Tensor x, torch::Tensor weight, torch::Tensor bias, + torch::Tensor dropout_mask, float eps, float dropout_scale, bool training +); +""" + +# 编译CUDA扩展 +instancenorm_dropout = load_inline( + name="instancenorm_dropout_fused", + cpp_sources=instancenorm_dropout_cpp_source, + cuda_sources=instancenorm_dropout_source, + functions=["instancenorm_dropout_cuda_forward"], + extra_cuda_cflags=["-O3", "--use_fast_math"], + verbose=True +) + +class ModelNew(torch.nn.Module): + """ + InstanceNorm + Dropout融合模型 + """ + def __init__(self, num_features=64, eps=1e-5, affine=True, dropout_p=0.1, track_running_stats=False): + super(ModelNew, self).__init__() + self.num_features = num_features + self.eps = eps + self.affine = affine + self.dropout_p = dropout_p + self.track_running_stats = False # 强制为False + self.dropout_scale = 1.0 / (1.0 - dropout_p) + + if affine: + self.weight = torch.nn.Parameter(torch.ones(num_features)) + self.bias = torch.nn.Parameter(torch.zeros(num_features)) + else: + self.register_parameter('weight', None) + self.register_parameter('bias', None) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + 融合实现:InstanceNorm + Dropout + + Args: + x (torch.Tensor): 输入张量 shape [B, C, H, W] + + Returns: + torch.Tensor: Dropout(InstanceNorm(x)) + """ + if self.training: + # 使用PyTorch的Dropout生成mask,确保完全一致 + with torch.no_grad(): + # 创建一个与x相同的张量用于生成mask + dummy_input = torch.ones_like(x) + dropout_mask = torch.nn.functional.dropout(dummy_input, p=self.dropout_p, training=True, inplace=False) + # 将mask转换为0或dropout_scale的形式 + dropout_mask = dropout_mask / dummy_input + else: + # 推理时mask全为1 + dropout_mask = torch.ones_like(x) + + if self.affine: + return instancenorm_dropout.instancenorm_dropout_cuda_forward( + x, self.weight, self.bias, dropout_mask, self.eps, self.dropout_scale, self.training + ) + else: + weight = torch.ones(self.num_features, device=x.device) + bias = torch.zeros(self.num_features, device=x.device) + return instancenorm_dropout.instancenorm_dropout_cuda_forward( + x, weight, bias, dropout_mask, self.eps, self.dropout_scale, self.training + ) diff --git a/S1/wut0n_#34/instancenorm_dropout_torchcode.py b/S1/wut0n_#34/instancenorm_dropout_torchcode.py new file mode 100644 index 00000000..cc5fccbe --- /dev/null +++ b/S1/wut0n_#34/instancenorm_dropout_torchcode.py @@ -0,0 +1,86 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + """ + 原始模型:InstanceNorm + Dropout + """ + def __init__(self, num_features=64, eps=1e-5, affine=True, dropout_p=0.1, track_running_stats=False): + super(Model, self).__init__() + self.num_features = num_features + self.eps = eps + self.affine = affine + self.dropout_p = dropout_p + self.track_running_stats = track_running_stats + + # 创建InstanceNorm层 + self.instance_norm = nn.InstanceNorm2d( + num_features=num_features, + eps=eps, + affine=affine, + track_running_stats=track_running_stats + ) + + # 创建Dropout层 + self.dropout = nn.Dropout(p=dropout_p) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + 原始实现:先InstanceNorm,再Dropout + + Args: + x (torch.Tensor): 输入张量 shape [B, C, H, W] + + Returns: + torch.Tensor: Dropout(InstanceNorm(x)) + """ + x_normalized = self.instance_norm(x) + return self.dropout(x_normalized) + +class ModelNew(torch.nn.Module): + """ + 融合模型:直接实现InstanceNorm + Dropout + """ + def __init__(self, num_features=64, eps=1e-5, affine=True, dropout_p=0.1, track_running_stats=False): + super(ModelNew, self).__init__() + self.num_features = num_features + self.eps = eps + self.affine = affine + self.dropout_p = dropout_p + self.track_running_stats = False # 强制为False以支持CUDA实现 + + if affine: + self.weight = torch.nn.Parameter(torch.ones(num_features)) + self.bias = torch.nn.Parameter(torch.zeros(num_features)) + else: + self.register_parameter('weight', None) + self.register_parameter('bias', None) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + 融合实现:在CUDA kernel中直接完成InstanceNorm + Dropout + + Args: + x (torch.Tensor): 输入张量 shape [B, C, H, W] + + Returns: + torch.Tensor: Dropout(InstanceNorm(x)) + """ + # 这个将在CUDA中实现 + pass + +# 测试参数 +batch_size = 128 +num_features = 64 +height = 128 +width = 128 +dropout_p = 0.1 + +def get_inputs(): + """生成测试输入""" + x = torch.randn(batch_size, num_features, height, width) + return [x] + +def get_init_inputs(): + """获取初始化参数""" + return [num_features] diff --git a/S1/wut0n_#34/prompt.txt b/S1/wut0n_#34/prompt.txt new file mode 100644 index 00000000..62ff2baf --- /dev/null +++ b/S1/wut0n_#34/prompt.txt @@ -0,0 +1,76 @@ +Write a custom CUDA kernel to replace PyTorch's InstanceNorm + Dropout implementation for CNN layers. + +You are given the following PyTorch architecture: + +python +import torch +import torch.nn as nn + +class Model(nn.Module): +""" +Simple model that performs InstanceNorm + Dropout. +""" +def init(self, num_features=64, eps=1e-5, affine=True, dropout_p=0.1, track_running_stats=False): +super(Model, self).init() +self.instance_norm = nn.InstanceNorm2d( + num_features=num_features, + eps=eps, + affine=affine, + track_running_stats=track_running_stats +) +self.dropout = nn.Dropout(p=dropout_p) + +def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Applies InstanceNorm to the input tensor and then applies dropout. + + Args: + x (torch.Tensor): Input tensor of shape [B, C, H, W]. + + Returns: + torch.Tensor: Dropout(InstanceNorm(x)), same shape as input. + """ + x_normalized = self.instance_norm(x) + return self.dropout(x_normalized) + +batch_size = 32 +num_features = 64 +height = 128 +width = 128 + +def get_inputs(): +x = torch.randn(batch_size, num_features, height, width) +return [x] + +def get_init_inputs(): +return [num_features] + + +Your task is to optimize this InstanceNorm + Dropout implementation by: + +1. **Operator Fusion**: Combine InstanceNorm computation (mean, variance, normalization) and Dropout masking into a single CUDA kernel to eliminate intermediate tensor storage and reduce memory bandwidth overhead. + +2. **Memory Access Optimization**: Minimize global memory access by keeping intermediate computations in registers, and ensure coalesced memory access patterns for the [B, C, H, W] tensor layout. + +3. **Shared Memory Optimization**: Use shared memory for efficient parallel reduction when computing mean and variance across spatial dimensions (H*W) within each instance and channel. + +4. **Dropout Mask Integration**: Implement dropout masking directly within the kernel to avoid separate mask generation and application steps, ensuring consistent random number generation with PyTorch's dropout behavior. + +5. **Training/Inference Modes**: Support both training mode (with dropout) and inference mode (without dropout) for optimal performance in different scenarios. + +6. **Thread Configuration**: Use optimal block size (e.g., 256 threads) and compute grid dimensions based on batch_size and num_features to maximize GPU utilization. + +7. **Numerical Stability**: Ensure proper epsilon handling in InstanceNorm computation to avoid division by zero and maintain numerical precision. + +The optimized CUDA kernel should: +- Take input tensor x, weight, and bias as input (all float32) +- Compute InstanceNorm (mean, variance, normalization) and apply dropout in a single kernel +- Support both training and inference modes +- Handle dropout probability scaling correctly (1/(1-p) for retained elements) +- Use shared memory for efficient mean and variance computation +- Maintain numerical stability with proper epsilon handling +- Achieve significant speedup over PyTorch's separate InstanceNorm + Dropout implementation +- Support both affine and non-affine modes +- Ensure dropout behavior is consistent with PyTorch's implementation + +Follow the inline CUDA extension syntax example provided in reference. The kernel should be optimized for GPU architectures and demonstrate performance improvements through reduced memory access, fused computation, and efficient parallel reduction. diff --git a/S1/wut0n_#34/run_code.py b/S1/wut0n_#34/run_code.py new file mode 100644 index 00000000..c7547ecb --- /dev/null +++ b/S1/wut0n_#34/run_code.py @@ -0,0 +1,84 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from focalloss_reduction_torchcode import Model, get_inputs, get_init_inputs +from focalloss_reduction_cudacode import ModelNew + +def run_benchmark(): + # 检查 CUDA 是否可用 + if not torch.cuda.is_available(): + print("CUDA 不可用,请确保您有可用的 NVIDIA GPU 并已正确安装 PyTorch CUDA 版本。") + return + else: + device = torch.device("cuda") + + # 初始化模型 + init_inputs = get_init_inputs() + init_inputs = [ + x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in init_inputs + ] + inputs = get_inputs() + inputs = [ + x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in inputs + ] + + torch_model = Model(*init_inputs).cuda() + cuda_model = ModelNew(*init_inputs).cuda() + + torch_model.eval() + cuda_model.eval() + + print("-------------------- 精度对齐验证 --------------------") + with torch.no_grad(): + output_torch = torch_model(*inputs) + output_cuda = cuda_model(*inputs) + + precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-03, atol=1e-05) + max_diff = torch.max(torch.abs(output_torch - output_cuda)).item() + mean_diff = torch.mean(torch.abs(output_torch - output_cuda)).item() + + if precision_flag: + print(f"✅ 精度对齐:两个模型的输出结果非常接近。") + print(f"最大误差: {max_diff:.8f}, 平均误差: {mean_diff:.8f}") + else: + print(f"❌ 精度不一致!最大误差: {max_diff:.8f}, 平均误差: {mean_diff:.8f}") + + print("\n-------------------- 性能加速比测试 --------------------") + num_iterations = 100 + + # GPU 预热 + for _ in range(10): + _ = torch_model(*inputs) + _ = cuda_model(*inputs) + + # PyTorch 模型计时 + torch.cuda.synchronize() + start_time = time.time() + for _ in range(num_iterations): + _ = torch_model(*inputs) + torch.cuda.synchronize() + torch_time = (time.time() - start_time) / num_iterations + + # 自定义 CUDA 内核计时 + torch.cuda.synchronize() + start_time = time.time() + for _ in range(num_iterations): + _ = cuda_model(*inputs) + torch.cuda.synchronize() + cuda_time = (time.time() - start_time) / num_iterations + + print(f"PyTorch focalloss_reduction 平均执行时间: {torch_time:.6f} 秒") + print(f"自定义 CUDA focalloss_reduction 平均执行时间: {cuda_time:.6f} 秒") + speedup = 0 + if cuda_time > 0: + speedup = torch_time / cuda_time + print(f"加速比 (Speedup): {speedup:.2f}x") + else: + print("CUDA 内核执行时间为0,无法计算加速比。") + return precision_flag, speedup + +if __name__ == "__main__": + precision_flag, speedup = run_benchmark()