GPUCodeForces/S1/uucoco_#39/MishGLU_cuda.py

97 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 mish_glu_cuda(torch::Tensor input);
"""
cuda_source = """
#include <cuda_runtime.h>
__device__ __forceinline__ float mish_fast(float x) {
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_glu_vec4_kernel(
const float4* __restrict__ x,
float4* __restrict__ y,
int vec_dim_out,
int n_vec_out)
{
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 = mish_fast(g.x) * a.x;
out.y = mish_fast(g.y) * a.y;
out.z = mish_fast(g.z) * a.z;
out.w = mish_fast(g.w) * a.w;
y[i] = out;
}
}
torch::Tensor mish_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;
mish_glu_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
);
return output;
}
"""
self.op = load_inline(
name="mish_glu_opt_vec4",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["mish_glu_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False
)
def forward(self, x):
return self.op.mish_glu_cuda(x)