finish structural_similarity_softplus #136

This commit is contained in:
uucoco 2025-12-10 20:14:30 +08:00
parent 10eed82956
commit a73db3cc9d
4 changed files with 367 additions and 0 deletions

69
S1/uucoco_#136/prompt.txt Normal file
View File

@ -0,0 +1,69 @@
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.
This code implements total correlation + ELU activation with CUDA optimizations:
Shared memory staging - Loads x and target into shared memory for reuse across multiple reduction phases.
Two-stage computation - First computes means, then uses them for covariance and variance calculations.
Triple parallel reduction - Warp shuffle for three sums: covariance, var_x, var_t.
Three shared memory buffers - Separate buffers for covariance, var_x, and var_t to avoid bank conflicts.
Broadcast means - Stores computed means in shared memory for all threads to access.
Numerical stability - Adds 1e-6 to denominator for safe division in correlation calculation.
ELU activation - Computes Exponential Linear Unit: max(0,x) + min(0,exp(x)-1).
Grid-stride loop - Threads process multiple elements for load balancing.
CUDA math functions - Uses sqrtf() and expf() for hardware acceleration.
Memory coalescing - Contiguous tensor access patterns.
Batch parallelism - One CUDA block per input row with dynamic shared memory allocation.
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, target):
super(Model, self).__init__()
self.target = nn.Parameter(target)
def forward(self, x: torch.Tensor) -> torch.Tensor:
mean_x = x.mean(dim=-1, keepdim=True)
mean_t = self.target.mean(dim=-1, keepdim=True)
xm = x - mean_x
tm = self.target - mean_t
cov = torch.sum(xm * tm, dim=-1)
sx = torch.sqrt(torch.sum(xm * xm, dim=-1))
st = torch.sqrt(torch.sum(tm * tm, dim=-1))
correlation = cov / (sx * st + 1e-6)
return F.elu(correlation)
batch_size = 128
input_dim = 1024
def get_inputs():
x = torch.randn(batch_size, input_dim)
return [x]
def get_init_inputs():
target = torch.randn(input_dim)
return [target]

View File

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

View File

@ -0,0 +1,183 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
__inline__ __device__ float warp_reduce(float val) {
for (int offset = 16; offset > 0; offset /= 2)
val += __shfl_down_sync(0xffffffff, val, offset);
return val;
}
__global__ void total_correlation_elu_kernel(
const float* __restrict__ x,
const float* __restrict__ target,
float* __restrict__ y,
int batch_size,
int width)
{
int row = blockIdx.x;
int tid = threadIdx.x;
if (row >= batch_size) return;
extern __shared__ float s_mem[];
float* s_x = s_mem;
float* s_t = s_mem + width;
for (int i = tid; i < width; i += blockDim.x) {
s_x[i] = x[row * width + i];
s_t[i] = target[i];
}
__syncthreads();
float sum_x = 0.0f;
float sum_t = 0.0f;
for (int i = tid; i < width; i += blockDim.x) {
sum_x += s_x[i];
sum_t += s_t[i];
}
sum_x = warp_reduce(sum_x);
sum_t = warp_reduce(sum_t);
static __shared__ float shared_sum_x[32];
static __shared__ float shared_sum_t[32];
int lane = tid % 32;
int wid = tid / 32;
if (lane == 0) {
shared_sum_x[wid] = sum_x;
shared_sum_t[wid] = sum_t;
}
__syncthreads();
sum_x = (tid < blockDim.x / 32) ? shared_sum_x[lane] : 0.0f;
sum_t = (tid < blockDim.x / 32) ? shared_sum_t[lane] : 0.0f;
if (wid == 0) {
sum_x = warp_reduce(sum_x);
sum_t = warp_reduce(sum_t);
}
__syncthreads();
// Broadcast means
if (tid == 0) {
shared_sum_x[0] = sum_x / width;
shared_sum_t[0] = sum_t / width;
}
__syncthreads();
float mean_x = shared_sum_x[0];
float mean_t = shared_sum_t[0];
float sum_cov = 0.0f;
float sum_var_x = 0.0f;
float sum_var_t = 0.0f;
for (int i = tid; i < width; i += blockDim.x) {
float dx = s_x[i] - mean_x;
float dt = s_t[i] - mean_t;
sum_cov += dx * dt;
sum_var_x += dx * dx;
sum_var_t += dt * dt;
}
sum_cov = warp_reduce(sum_cov);
sum_var_x = warp_reduce(sum_var_x);
sum_var_t = warp_reduce(sum_var_t);
if (lane == 0) {
shared_sum_x[wid] = sum_cov;
shared_sum_t[wid] = sum_var_x;
// reuse shared memory slot
// store sum_var_t in s_x buffer temporarily or add another shared array?
// simple: use float* s_var_t = (float*)&shared_sum_x[0] + 32? No.
// Let's assume blockDim <= 1024, max 32 warps.
}
__syncthreads();
// Need 3 values reduced.
// Just use atomic or simpler serial reduction for the last 32 values if precision allows,
// or allocate 3 shared arrays.
// Let's use 3 dedicated shared arrays for reduction to avoid conflict.
static __shared__ float s_r_cov[32];
static __shared__ float s_r_vx[32];
static __shared__ float s_r_vt[32];
if (lane == 0) {
s_r_cov[wid] = sum_cov;
s_r_vx[wid] = sum_var_x;
s_r_vt[wid] = sum_var_t;
}
__syncthreads();
sum_cov = (tid < blockDim.x / 32) ? s_r_cov[lane] : 0.0f;
sum_var_x = (tid < blockDim.x / 32) ? s_r_vx[lane] : 0.0f;
sum_var_t = (tid < blockDim.x / 32) ? s_r_vt[lane] : 0.0f;
if (wid == 0) {
sum_cov = warp_reduce(sum_cov);
sum_var_x = warp_reduce(sum_var_x);
sum_var_t = warp_reduce(sum_var_t);
}
if (tid == 0) {
float corr = sum_cov / (sqrtf(sum_var_x) * sqrtf(sum_var_t) + 1e-6f);
// ELU: x > 0 ? x : exp(x) - 1
float val = corr;
if (val > 0.0f) {
y[row] = val;
} else {
y[row] = expf(val) - 1.0f;
}
}
}
torch::Tensor launch_total_correlation_elu(torch::Tensor x, torch::Tensor target) {
auto batch_size = x.size(0);
auto width = x.size(1);
auto y = torch::empty({batch_size}, x.options());
const int threads = 256;
const int blocks = batch_size;
int shared_mem = 2 * width * sizeof(float);
total_correlation_elu_kernel<<<blocks, threads, shared_mem>>>(
x.data_ptr<float>(),
target.data_ptr<float>(),
y.data_ptr<float>(),
batch_size,
width
);
return y;
}
"""
cpp_source = """
torch::Tensor launch_total_correlation_elu(torch::Tensor x, torch::Tensor target);
"""
total_correlation_elu_module = load_inline(
name='total_correlation_elu_op',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['launch_total_correlation_elu'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, target):
super(ModelNew, self).__init__()
self.target = nn.Parameter(target)
self.op = total_correlation_elu_module
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.op.launch_total_correlation_elu(x.contiguous(), self.target.contiguous())

View File

@ -0,0 +1,38 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, target):
super(Model, self).__init__()
self.target = nn.Parameter(target)
def forward(self, x: torch.Tensor) -> torch.Tensor:
mean_x = x.mean(dim=-1, keepdim=True)
mean_t = self.target.mean(dim=-1, keepdim=True)
xm = x - mean_x
tm = self.target - mean_t
cov = torch.sum(xm * tm, dim=-1)
sx = torch.sqrt(torch.sum(xm * xm, dim=-1))
st = torch.sqrt(torch.sum(tm * tm, dim=-1))
correlation = cov / (sx * st + 1e-6)
return F.elu(correlation)
batch_size = 128
input_dim = 1024
def get_inputs():
x = torch.randn(batch_size, input_dim)
return [x]
def get_init_inputs():
target = torch.randn(input_dim)
return [target]