GPUCodeForces/S1/uucoco_#53/SigmoidGLU_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):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor sigmoid_glu_cuda(torch::Tensor input);
"""
cuda_source = """
#include <cuda_runtime.h>
__device__ __forceinline__ float sigmoid_f(float x) {
return 1.0f / (1.0f + expf(-x));
}
__global__ void sigmoid_glu_vec4_kernel(
const float* __restrict__ x,
float* __restrict__ y,
int vec_dim_out,
int n_vec_out)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
const float4* x_vec = reinterpret_cast<const float4*>(x);
float4* y_vec = reinterpret_cast<float4*>(y);
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_vec[gate_idx];
float4 a = x_vec[act_idx];
float4 out;
out.x = sigmoid_f(g.x) * a.x;
out.y = sigmoid_f(g.y) * a.y;
out.z = sigmoid_f(g.z) * a.z;
out.w = sigmoid_f(g.w) * a.w;
y_vec[i] = out;
}
}
torch::Tensor sigmoid_glu_cuda(torch::Tensor input) {
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;
sigmoid_glu_vec4_kernel<<<blocks, threads>>>(
x_c.data_ptr<float>(),
output.data_ptr<float>(),
vec_dim_out,
n_vec_out
);
return output;
}
"""
self.op = load_inline(
name="sigmoid_glu_opt_vec4",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["sigmoid_glu_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, x):
return self.op.sigmoid_glu_cuda(x)