GPUCodeForces/S1/uucoco_#46/ELUGLU_cuda.py

96 lines
2.9 KiB
Python

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)