diff --git a/S1/gsd123_#69/KulczynskiIndex_cuda.py b/S1/gsd123_#69/KulczynskiIndex_cuda.py new file mode 100644 index 0000000..d1546d3 --- /dev/null +++ b/S1/gsd123_#69/KulczynskiIndex_cuda.py @@ -0,0 +1,158 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self, eps=1e-6): + super().__init__() + self.eps = eps + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor kulczynski_cuda(torch::Tensor x, torch::Tensor y, float eps); + """ + + cuda_source = """ + #include + + struct Acc { + double min_v; + double sum_x; + double sum_y; + }; + + __device__ __forceinline__ Acc warp_reduce(Acc val) { + #pragma unroll + for (int offset = 16; offset > 0; offset /= 2) { + val.min_v += __shfl_down_sync(0xffffffff, val.min_v, offset); + val.sum_x += __shfl_down_sync(0xffffffff, val.sum_x, offset); + val.sum_y += __shfl_down_sync(0xffffffff, val.sum_y, offset); + } + return val; + } + + __device__ __forceinline__ Acc block_reduce(Acc val) { + static __shared__ double s_min[32]; + static __shared__ double s_x[32]; + static __shared__ double s_y[32]; + + int lane = threadIdx.x % 32; + int wid = threadIdx.x / 32; + + val = warp_reduce(val); + + if (lane == 0) { + s_min[wid] = val.min_v; + s_x[wid] = val.sum_x; + s_y[wid] = val.sum_y; + } + __syncthreads(); + + Acc final_val = {0.0, 0.0, 0.0}; + if (threadIdx.x < blockDim.x / 32) { + final_val.min_v = s_min[threadIdx.x]; + final_val.sum_x = s_x[threadIdx.x]; + final_val.sum_y = s_y[threadIdx.x]; + } + + if (wid == 0) final_val = warp_reduce(final_val); + + return final_val; + } + + __global__ void kulczynski_kernel( + const float* __restrict__ x, + const float* __restrict__ y, + float* __restrict__ output, + int feature_dim, + int batch_size, + float eps) + { + int bid = blockIdx.x; + if (bid >= batch_size) return; + + const float* x_row = x + bid * feature_dim; + const float* y_row = y + bid * feature_dim; + + Acc sum = {0.0, 0.0, 0.0}; + + int vec_loops = feature_dim / 4; + int vec_remainder = feature_dim % 4; + + const float4* x_vec = reinterpret_cast(x_row); + const float4* y_vec = reinterpret_cast(y_row); + + for (int i = threadIdx.x; i < vec_loops; i += blockDim.x) { + float4 vx = x_vec[i]; + float4 vy = y_vec[i]; + + sum.min_v += (double)fminf(vx.x, vy.x); + sum.min_v += (double)fminf(vx.y, vy.y); + sum.min_v += (double)fminf(vx.z, vy.z); + sum.min_v += (double)fminf(vx.w, vy.w); + + sum.sum_x += (double)(vx.x + vx.y + vx.z + vx.w); + sum.sum_y += (double)(vy.x + vy.y + vy.z + vy.w); + } + + if (threadIdx.x == 0 && vec_remainder > 0) { + int tail_start = vec_loops * 4; + for (int i = 0; i < vec_remainder; ++i) { + int idx = tail_start + i; + float val_x = x_row[idx]; + float val_y = y_row[idx]; + + sum.min_v += (double)fminf(val_x, val_y); + sum.sum_x += (double)val_x; + sum.sum_y += (double)val_y; + } + } + + sum = block_reduce(sum); + + if (threadIdx.x == 0) { + double term1 = sum.min_v / (sum.sum_x + (double)eps); + double term2 = sum.min_v / (sum.sum_y + (double)eps); + output[bid] = (float)(0.5 * (term1 + term2)); + } + } + + torch::Tensor kulczynski_cuda(torch::Tensor x, torch::Tensor y, float eps) { + auto x_c = x.contiguous(); + auto y_c = y.contiguous(); + + int batch_size = x_c.size(0); + int feature_dim = x_c.size(1); + + auto output = torch::empty({batch_size}, x.options()); + + int threads = 256; + int blocks = batch_size; + + kulczynski_kernel<<>>( + x_c.data_ptr(), + y_c.data_ptr(), + output.data_ptr(), + feature_dim, + batch_size, + eps + ); + + return output; + } + """ + + self.op = load_inline( + name="kulczynski_opt_v1", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["kulczynski_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, x, y): + return self.op.kulczynski_cuda(x, y, self.eps) \ No newline at end of file diff --git a/S1/gsd123_#69/KulczynskiIndex_torch.py b/S1/gsd123_#69/KulczynskiIndex_torch.py new file mode 100644 index 0000000..d9d32ee --- /dev/null +++ b/S1/gsd123_#69/KulczynskiIndex_torch.py @@ -0,0 +1,24 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self, eps=1e-6): + super().__init__() + self.eps = eps + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + intersection = torch.min(x, y).sum(dim=1) + sum_x = x.sum(dim=1) + sum_y = y.sum(dim=1) + return 0.5 * (intersection / (sum_x + self.eps) + intersection / (sum_y + self.eps)) + +batch_size = 128 +feature_dim = 512 + +def get_inputs(): + x = torch.rand(batch_size, feature_dim, dtype=torch.float32) + y = torch.rand(batch_size, feature_dim, dtype=torch.float32) + return [x, y] + +def get_init_inputs(): + return [1e-6] \ No newline at end of file diff --git a/S1/gsd123_#69/prompt.txt b/S1/gsd123_#69/prompt.txt new file mode 100644 index 0000000..e2e64d4 --- /dev/null +++ b/S1/gsd123_#69/prompt.txt @@ -0,0 +1,83 @@ +You write custom CUDA kernels to replace the pytorch operators in the given GeGLU architecture to get speedups. + +You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination. + + +CUDA Optimization Strategies: + +Vectorized Memory Access + +Uses float4 for 4-element vector loads + +Reduces memory instructions by 4x + +Better memory bandwidth utilization + +Multi-Value Reduction + +Custom Acc struct for min_v, sum_x, sum_y + +Simultaneous reduction of three values + +Warp shuffle and shared memory reduction + +Parallel Computation + +One block per batch sample + +256 threads per block for feature processing + +Vectorized main loop + scalar tail handling + +Numerical Stability + +Adds eps to denominators to prevent division by zero + +Uses fminf for element-wise minimum + +Double precision accumulation + +Memory Access + +contiguous() tensors for coalescing + +__restrict__ pointers + +Row-based sequential access pattern + +Performance Optimization + +Compiler flag: -O3 + +Single thread handles remainder elements + +Efficient Kulczynski index calculation + + + + +Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self, eps=1e-6): + super().__init__() + self.eps = eps + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + intersection = torch.min(x, y).sum(dim=1) + sum_x = x.sum(dim=1) + sum_y = y.sum(dim=1) + return 0.5 * (intersection / (sum_x + self.eps) + intersection / (sum_y + self.eps)) + +batch_size = 128 +feature_dim = 512 + +def get_inputs(): + x = torch.rand(batch_size, feature_dim, dtype=torch.float32) + y = torch.rand(batch_size, feature_dim, dtype=torch.float32) + return [x, y] + +def get_init_inputs(): + return [1e-6] \ No newline at end of file diff --git a/S1/gsd123_#69/run_code.py b/S1/gsd123_#69/run_code.py new file mode 100644 index 0000000..d7de126 --- /dev/null +++ b/S1/gsd123_#69/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from KulczynskiIndex_torch import Model, get_inputs, get_init_inputs +from KulczynskiIndex_cuda 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) + if precision_flag: + print("✅ 精度对齐:两个模型的输出结果非常接近。") + else: + print("❌ 精度不一致!") + + print("\n-------------------- 性能加速比测试 --------------------") + num_iterations = 100 + + # 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 torch.relu 平均执行时间: {torch_time:.6f} 秒") + print(f"自定义 CUDA 内核 平均执行时间: {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() \ No newline at end of file