finish ELUGLU#46

This commit is contained in:
uucoco 2025-12-09 17:41:49 +08:00
parent 04c0492b9d
commit 977dbb0665
5 changed files with 151 additions and 112 deletions

View File

@ -0,0 +1,96 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self, alpha=1.0):
super().__init__()
self.alpha = alpha
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor eluglu_cuda(torch::Tensor input, float alpha);
"""
cuda_source = """
#include <cuda_runtime.h>
__device__ __forceinline__ float elu_f(float x, float alpha) {
return (x > 0.0f) ? x : alpha * (expf(x) - 1.0f);
}
__global__ void eluglu_vec4_kernel(
const float4* __restrict__ x,
float4* __restrict__ y,
int vec_dim_out,
int n_vec_out,
float alpha)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
for (int i = idx; i < n_vec_out; i += stride) {
int row = i / vec_dim_out;
int col = i % vec_dim_out;
int gate_idx = row * (2 * vec_dim_out) + col;
int act_idx = gate_idx + vec_dim_out;
float4 g = x[gate_idx];
float4 a = x[act_idx];
float4 out;
out.x = elu_f(g.x, alpha) * a.x;
out.y = elu_f(g.y, alpha) * a.y;
out.z = elu_f(g.z, alpha) * a.z;
out.w = elu_f(g.w, alpha) * a.w;
y[i] = out;
}
}
torch::Tensor eluglu_cuda(torch::Tensor input, float alpha) {
auto x_c = input.contiguous();
int last_dim = x_c.size(-1);
TORCH_CHECK(last_dim % 8 == 0, "Feature dim must be divisible by 8 for float4 optimization");
auto out_sizes = x_c.sizes().vec();
out_sizes.back() /= 2;
auto output = torch::empty(out_sizes, x_c.options());
int numel_out = output.numel();
int n_vec_out = numel_out / 4;
int vec_dim_out = out_sizes.back() / 4;
int threads = 256;
int blocks = (n_vec_out + threads - 1) / threads;
if (blocks > 65535) blocks = 65535;
if (blocks == 0) blocks = 1;
eluglu_vec4_kernel<<<blocks, threads>>>(
reinterpret_cast<const float4*>(x_c.data_ptr<float>()),
reinterpret_cast<float4*>(output.data_ptr<float>()),
vec_dim_out,
n_vec_out,
alpha
);
return output;
}
"""
self.op = load_inline(
name="eluglu_opt_vec4",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["eluglu_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False
)
def forward(self, x):
return self.op.eluglu_cuda(x, self.alpha)

View File

@ -2,23 +2,21 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
def __init__(self, alpha=1.0):
super().__init__()
self.alpha = alpha
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * x + x
gate, act = x.chunk(2, dim=-1)
return F.elu(gate, alpha=self.alpha) * act
batch_size = 128
feature_dim = 512
feature_dim = 1024
def get_inputs():
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
return [x]
def get_init_inputs():
return []
return [1.0]

View File

@ -1,85 +0,0 @@
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 = """
torch::Tensor squ_cuda(torch::Tensor x);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
__device__ __forceinline__ float squ_op(float x) {
return x * x + x;
}
__global__ void squ_kernel(
const float* __restrict__ x,
float* __restrict__ output,
const int n_elements)
{
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int stride = blockDim.x * gridDim.x;
const int vec_loops = n_elements >> 2;
const float4* x_vec = reinterpret_cast<const float4*>(x);
float4* out_vec = reinterpret_cast<float4*>(output);
for (int i = tid; i < vec_loops; i += stride) {
float4 v = x_vec[i];
float4 r;
r.x = squ_op(v.x);
r.y = squ_op(v.y);
r.z = squ_op(v.z);
r.w = squ_op(v.w);
out_vec[i] = r;
}
// 处理尾部剩余的不能被 4 整除的元素
const int tail_start = vec_loops << 2;
for (int i = tail_start + tid; i < n_elements; i += stride) {
output[i] = squ_op(x[i]);
}
}
torch::Tensor squ_cuda(torch::Tensor x) {
auto x_c = x.contiguous();
const int n_elements = x_c.numel();
auto output = torch::empty_like(x_c);
const int threads = 256;
const int max_blocks = 65535;
const int blocks = std::min((n_elements + threads * 4 - 1) / (threads * 4), max_blocks);
squ_kernel<<<blocks, threads>>>(
x_c.data_ptr<float>(),
output.data_ptr<float>(),
n_elements
);
return output;
}
"""
self.op = load_inline(
name="squ_v1",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["squ_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False
)
def forward(self, x):
return self.op.squ_cuda(x)

View File

@ -2,15 +2,47 @@ You write custom CUDA kernels to replace the pytorch operators in the given GeGL
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 CUDA kernel implements a custom activation function (SQU - x² + x) with the following optimizations:
Vectorization: Uses float4memory operations to process 4 elements per thread, significantly increasing memory throughput by leveraging vector loads/stores.
Memory Coalescing: Accesses contiguous memory blocks through vector operations, optimizing GPU memory bandwidth utilization and reducing memory transactions.
Grid-Stride Loop: Handles arbitrary-sized tensors efficiently by having threads process multiple elements with strided indexing, ensuring good GPU utilization.
Tail Processing: Separately handles non-multiple-of-4 elements after vectorized operations to ensure complete data processing.
Fast Math Optimization: Uses --use_fast_mathcompiler flag for optimized mathematical operations with relaxed precision requirements.
Occupancy Optimization: Configures 256 threads per block and dynamically calculates grid size based on vectorized element count (threads × 4) to maximize GPU occupancy.
Compiler Optimizations: Enabled with -O3flag for aggressive performance optimization of the generated code.
Inlined Device Function: The core mathematical operation is marked with __forceinline__to eliminate function call overhead within the kernel.
This CUDA kernel implements optimized ELU Gated Linear Unit (GLU) with:
Memory Optimization:
Vectorized memory access using float4 for 4x bandwidth
Contiguous tensor inputs for coalesced memory access
Direct element-wise computation without temporary storage
Parallelization Strategy:
Grid-stride loop for efficient workload distribution
256 threads per block optimal configuration
Automatic grid size calculation with 65535 block limit
Computational Optimization:
ELU GLU: elu(gate, alpha) * activation
Configurable alpha parameter for ELU
Fast math compilation flags for optimized expf()
Branching ELU: x > 0 ? x : alpha * (exp(x) - 1)
Work Distribution:
Each thread processes 4 elements via float4
Automatic indexing for gate and activation components
Direct multiplication of ELU-activated gate with activation
The implementation provides maximum throughput through vectorization and fast math optimizations, requiring input feature dimension to be divisible by 8 for optimal performance with configurable ELU alpha parameter.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
@ -18,23 +50,21 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
def __init__(self, alpha=1.0):
super().__init__()
self.alpha = alpha
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * x + x
gate, act = x.chunk(2, dim=-1)
return F.elu(gate, alpha=self.alpha) * act
batch_size = 128
feature_dim = 512
feature_dim = 1024
def get_inputs():
x = torch.randn(batch_size, feature_dim, dtype=torch.float32)
return [x]
def get_init_inputs():
return []
return [1.0]

View File

@ -4,8 +4,8 @@
import torch
import torch.nn as nn
import time
from ShiftedQuadraticUnit_torch import Model, get_inputs, get_init_inputs
from ShiftedQuadraticUnit_cuda import ModelNew
from ELUGLU_torch import Model, get_inputs, get_init_inputs
from ELUGLU_cuda import ModelNew
def run_benchmark():