Text Generation
PEFT
Safetensors
lora
reinforcement-learning
code
hip
rocm
gpu-kernels
ik6626's picture
HIP kernel RL LoRA: step 75 (root) and step 125
35564ed verified
Raw History Blame Contribute Delete
1.7 kB
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <hip/hip_runtime.h>
#define BLOCK_SIZE 256
__global__ void fused_mse_eq_kernel(const float* __restrict__ x,
const float* __restrict__ target,
float* __restrict__ output,
int n) {
__shared__ float sdata[BLOCK_SIZE];
int tid = threadIdx.x;
int global_id = blockIdx.x * blockDim.x + threadIdx.x;
int stride = gridDim.x * blockDim.x;
float local_sum = 0.0f;
for (int i = global_id; i < n; i += stride) {
float eq_val = (x[i] == target[i]) ? 1.0f : 0.0f;
float diff = eq_val - target[i];
local_sum += diff * diff;
}
sdata[tid] = local_sum;
__syncthreads();
for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
if (tid < s) {
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
if (tid == 0) {
atomicAdd(output, sdata[0]);
}
}
torch::Tensor forward(torch::Tensor x, torch::Tensor target) {
auto stream = at::cuda::getCurrentCUDAStream();
int n = x.numel();
auto output = torch::zeros({1}, x.options());
int num_blocks = (n + BLOCK_SIZE - 1) / BLOCK_SIZE;
if (num_blocks > 4096) num_blocks = 4096;
fused_mse_eq_kernel<<<num_blocks, BLOCK_SIZE, 0, stream>>>(
x.data_ptr<float>(),
target.data_ptr<float>(),
output.data_ptr<float>(),
n
);
auto result = output / static_cast<double>(n);
return result.squeeze();
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &forward, "Fused MSE of element-wise equality");
}