diff --git a/S1/gsd123_#23/huberloss_cuda.py b/S1/gsd123_#23/huberloss_cuda.py new file mode 100644 index 00000000..79ea5eb7 --- /dev/null +++ b/S1/gsd123_#23/huberloss_cuda.py @@ -0,0 +1,142 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + + +class ModelNew(nn.Module): + def __init__(self, delta=1.0): + super().__init__() + self.delta = delta + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + torch::Tensor huber_cuda(torch::Tensor x, torch::Tensor y, float delta); + """ + + cuda_source = """ + #include + + __device__ __forceinline__ double warp_sum(double val) { + for (int offset = 16; offset > 0; offset /= 2) { + val += __shfl_down_sync(0xffffffff, val, offset); + } + return val; + } + + __device__ __forceinline__ double block_sum(double val) { + static __shared__ double shared[32]; + int lane = threadIdx.x % 32; + int wid = threadIdx.x / 32; + + val = warp_sum(val); + if (lane == 0) shared[wid] = val; + __syncthreads(); + + val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0; + if (wid == 0) val = warp_sum(val); + return val; + } + + __global__ void huber_kernel_vec4( + const float* __restrict__ x, + const float* __restrict__ y, + float* __restrict__ output, + int total_elements, + float delta) + { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + + double sum = 0.0; + float delta_sq_half = 0.5f * delta * delta; + + int vec_loops = total_elements / 4; + int vec_remainder = total_elements % 4; + + const float4* x_vec = reinterpret_cast(x); + const float4* y_vec = reinterpret_cast(y); + + for (int i = idx; i < vec_loops; i += gridDim.x * blockDim.x) { + float4 vx = x_vec[i]; + float4 vy = y_vec[i]; + + float d1 = vx.x - vy.x; + float d2 = vx.y - vy.y; + float d3 = vx.z - vy.z; + float d4 = vx.w - vy.w; + + float a1 = fabsf(d1); + float a2 = fabsf(d2); + float a3 = fabsf(d3); + float a4 = fabsf(d4); + + double l1 = (a1 < delta) ? (0.5f * d1 * d1) : (delta * (a1 - 0.5f * delta)); + double l2 = (a2 < delta) ? (0.5f * d2 * d2) : (delta * (a2 - 0.5f * delta)); + double l3 = (a3 < delta) ? (0.5f * d3 * d3) : (delta * (a3 - 0.5f * delta)); + double l4 = (a4 < delta) ? (0.5f * d4 * d4) : (delta * (a4 - 0.5f * delta)); + + sum += l1 + l2 + l3 + l4; + } + + int tail_start = vec_loops * 4; + int tail_end = total_elements; + + // Handle remaining elements (non-vectorized) + // Stride for tail is tricky with grid-stride loop, so we switch to linear check for tail + // Since tail is small (<4), simple check is fine, but proper grid stride needs care. + // Simplified: let one block handle tail or mask carefully. + // Here: Just use a standard linear tail check based on original idx logic for simplicity in stride + + // Re-calculate simple index for tail + for (int i = tail_start + idx; i < tail_end; i += gridDim.x * blockDim.x) { + float diff = x[i] - y[i]; + float abs_diff = fabsf(diff); + if (abs_diff < delta) { + sum += 0.5f * diff * diff; + } else { + sum += delta * (abs_diff - 0.5f * delta); + } + } + + sum = block_sum(sum); + + if (threadIdx.x == 0) { + output[blockIdx.x] = (float)sum; + } + } + + torch::Tensor huber_cuda(torch::Tensor x, torch::Tensor y, float delta) { + auto x_c = x.contiguous(); + auto y_c = y.contiguous(); + + int total_elements = x_c.numel(); + int threads = 256; + int blocks = (total_elements + threads * 4 - 1) / (threads * 4); + if (blocks > 1024) blocks = 1024; + + auto output = torch::empty({blocks}, x.options()); + + huber_kernel_vec4<<>>( + x_c.data_ptr(), + y_c.data_ptr(), + output.data_ptr(), + total_elements, + delta + ); + + return output.sum() / total_elements; + } + """ + + self.op = load_inline( + name="huber_opt_vec4", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["huber_cuda"], + extra_cuda_cflags=["-O3"], + verbose=False + ) + + def forward(self, x, y): + return self.op.huber_cuda(x, y, self.delta) \ No newline at end of file diff --git a/S1/gsd123_#23/huberloss_torch.py b/S1/gsd123_#23/huberloss_torch.py new file mode 100644 index 00000000..8c05bfbf --- /dev/null +++ b/S1/gsd123_#23/huberloss_torch.py @@ -0,0 +1,21 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self, delta=1.0): + super().__init__() + self.loss = nn.HuberLoss(reduction='mean', delta=delta) + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + return self.loss(x, y) + +batch_size = 512 +feature_dim = 4096 + +def get_inputs(): + x = torch.randn(batch_size, feature_dim, dtype=torch.float32) + y = torch.randn(batch_size, feature_dim, dtype=torch.float32) + return [x, y] + +def get_init_inputs(): + return [1.0] \ No newline at end of file diff --git a/S1/gsd123_#23/prompt.txt b/S1/gsd123_#23/prompt.txt new file mode 100644 index 00000000..2913b10d --- /dev/null +++ b/S1/gsd123_#23/prompt.txt @@ -0,0 +1,76 @@ +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 + +Grid-Stride Loop + +Processes elements with grid-stride pattern + +Handles arbitrary tensor sizes + +Better GPU occupancy + +Two-Level Reduction + +Warp shuffle operations for fast reduction + +Shared memory for block-level results + +Final reduction on PyTorch side + +Branch Optimization + +Precomputes delta_sq_half outside loop + +Efficient conditional for Huber loss + +Minimal branching in vectorized path + +Performance Tuning + +Fixed 256 threads per block + +Block count capped at 1024 + +Compiler flag: -O3 + +Tail Handling + +Separate non-vectorized path for remainder + +Maintains correctness for all sizes + +Minimal performance impact + +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, delta=1.0): + super().__init__() + self.loss = nn.HuberLoss(reduction='mean', delta=delta) + + def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + return self.loss(x, y) + +batch_size = 512 +feature_dim = 4096 + +def get_inputs(): + x = torch.randn(batch_size, feature_dim, dtype=torch.float32) + y = torch.randn(batch_size, feature_dim, dtype=torch.float32) + return [x, y] + +def get_init_inputs(): + return [1.0] \ No newline at end of file diff --git a/S1/gsd123_#23/run_code.py b/S1/gsd123_#23/run_code.py new file mode 100644 index 00000000..86bf7785 --- /dev/null +++ b/S1/gsd123_#23/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from huberloss_torch import Model, get_inputs, get_init_inputs +from huberloss_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