Merge pull request 'finish Mish #31' (#282) from gsd123/GPUCodeForces:gsd31 into main

This commit is contained in:
Kuohais 2025-12-04 14:55:26 +08:00
commit c01bbab562
4 changed files with 294 additions and 0 deletions

116
S1/gsd123_#31/Mish_cuda.py Normal file
View File

@ -0,0 +1,116 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor mish_cuda(torch::Tensor x);
"""
cuda_source = """
#include <cuda_runtime.h>
__device__ __forceinline__ float mish_op_fast(float x) {
// 阈值保护x > 20 Softplus(x) x, Tanh(x) 1, Mish x
// 同时也防止 e^(2x) float32 下溢出 (e^88 溢出)
if (x > 20.0f) return x;
float e = expf(x);
float n = e * (2.0f + e);
float d = 2.0f + 2.0f * e + e * e;
return x * (n / d);
}
__global__ void mish_kernel_alg(
const float* __restrict__ x,
float* __restrict__ y,
int n)
{
int tid = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
int vec_n = n / 4;
const float4* x_vec = reinterpret_cast<const float4*>(x);
float4* y_vec = reinterpret_cast<float4*>(y);
int i = tid;
for (; i < vec_n - 1; i += stride) {
float4 v1 = x_vec[i];
float4 v2 = x_vec[i + 1];
float4 o1, o2;
o1.x = mish_op_fast(v1.x);
o1.y = mish_op_fast(v1.y);
o1.z = mish_op_fast(v1.z);
o1.w = mish_op_fast(v1.w);
o2.x = mish_op_fast(v2.x);
o2.y = mish_op_fast(v2.y);
o2.z = mish_op_fast(v2.z);
o2.w = mish_op_fast(v2.w);
y_vec[i] = o1;
y_vec[i + 1] = o2;
i++; // Skip next
}
for (; i < vec_n; i += stride) {
float4 v = x_vec[i];
float4 o;
o.x = mish_op_fast(v.x);
o.y = mish_op_fast(v.y);
o.z = mish_op_fast(v.z);
o.w = mish_op_fast(v.w);
y_vec[i] = o;
}
int tail_start = vec_n * 4;
for (int j = tail_start + tid; j < n; j += stride) {
y[j] = mish_op_fast(x[j]);
}
}
torch::Tensor mish_cuda(torch::Tensor x) {
auto x_c = x.contiguous();
auto output = torch::empty_like(x_c);
int total_elements = x_c.numel();
int threads = 256;
int vec_elements = total_elements / 4;
int blocks = (vec_elements + threads - 1) / threads;
if (blocks > 65535) blocks = 65535;
if (blocks == 0) blocks = 1;
mish_kernel_alg<<<blocks, threads>>>(
x_c.data_ptr<float>(),
output.data_ptr<float>(),
total_elements
);
return output;
}
"""
self.op = load_inline(
name="mish_opt_alg",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["mish_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False
)
def forward(self, x):
return self.op.mish_cuda(x)

View File

@ -0,0 +1,20 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.tanh(F.softplus(x))
batch_size = 1024
feature_dim = 4096
def get_inputs():
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
return [x]
def get_init_inputs():
return []

81
S1/gsd123_#31/prompt.txt Normal file
View File

@ -0,0 +1,81 @@
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:
Numerical Stability Optimization
Threshold protection: Returns x directly when x > 20.0f
Prevents expf(2*x) overflow in float32 (avoids e^88 overflow)
Algebraic reformulation for better numerical behavior
Vectorized Memory Access + ILP
Uses float4 for 4-element vector loads/stores
Instruction-Level Parallelism (ILP): Processes 2 vectors (8 elements) per loop iteration
Increases computational density and hides memory latency
Algebraic Reformulation
Optimized Mish computation: x * (e*(2+e)) / (2 + 2*e + e*e)
Avoids separate tanh and softplus computations
Reduces mathematical operations
Grid-Stride Loop
Processes elements with grid-stride pattern
Handles arbitrary tensor sizes efficiently
Better GPU utilization
Memory Access
contiguous() tensors for coalescing
__restrict__ pointers
Coalesced memory access patterns
Performance Tuning
Fixed 256 threads per block
Block count capped at 65535
Compiler flags: -O3, --use_fast_math
Key Innovation: Algebraic reformulation with numerical stability protection prevents overflow while maintaining mathematical equivalence, combined with ILP for performance.
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
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.tanh(F.softplus(x))
batch_size = 1024
feature_dim = 4096
def get_inputs():
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
return [x]
def get_init_inputs():
return []

77
S1/gsd123_#31/run_code.py Normal file
View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from Mish_torch import Model, get_inputs, get_init_inputs
from Mish_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()