GPUCodeForces/S1/4/geglu_cude.py

96 lines
3.3 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 geglu_dynamic_parallel(torch::Tensor input);
"""
cuda_source = """
#include <cuda_runtime.h>
__device__ float gelu_exact(float x) {
return 0.5f * x * (1.0f + erff(x * 0.7071067811865475f));
}
__global__ void geglu_dynamic_kernel(
const float* __restrict__ input,
float* __restrict__ output,
int feature_dim, int total_elements) {
extern __shared__ float shared_data[];
int tid = threadIdx.x;
int bid = blockIdx.x;
int bdim = blockDim.x;
// 动态确定每个block处理的元素数量
int elements_per_block = min(bdim * 4, total_elements - bid * bdim * 4);
elements_per_block = max(elements_per_block, 0);
float* gate_shared = shared_data;
float* act_shared = shared_data + elements_per_block;
// 协作加载
for (int i = tid; i < elements_per_block; i += bdim) {
int global_idx = bid * bdim * 4 + i;
if (global_idx < total_elements) {
int row = global_idx / (feature_dim / 2);
int col = global_idx % (feature_dim / 2);
gate_shared[i] = input[row * feature_dim + col];
act_shared[i] = input[row * feature_dim + col + (feature_dim / 2)];
}
}
__syncthreads();
// 处理
for (int i = tid; i < elements_per_block; i += bdim) {
int global_idx = bid * bdim * 4 + i;
if (global_idx < total_elements) {
float gate_val = gate_shared[i];
float act_val = act_shared[i];
output[global_idx] = gelu_exact(gate_val) * act_val;
}
}
}
torch::Tensor geglu_dynamic_parallel(torch::Tensor input) {
input = input.contiguous();
auto sizes = input.sizes().vec();
int feature_dim = sizes.back();
sizes.back() /= 2;
auto output = torch::empty(sizes, input.options());
int total_elements = output.numel();
int threads = 128;
int blocks = (total_elements + threads * 4 - 1) / (threads * 4);
int shared_mem = threads * 4 * 2 * sizeof(float);
geglu_dynamic_kernel<<<blocks, threads, shared_mem>>>(
input.data_ptr<float>(), output.data_ptr<float>(),
feature_dim, total_elements);
return output;
}
"""
self.op = load_inline(
name="geglu_dynamic",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["geglu_dynamic_parallel"],
extra_cuda_cflags=["-O3"],
verbose=True
)
def forward(self, x):
return self.op.geglu_dynamic_parallel(x)