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
8.14 kB

Let me analyze the PyTorch code:

  1. x and target are both random tensors of shape (256, 512, 1024) with float32 dtype.
  2. torch.eq(x, target) - element-wise equality check, returns a bool tensor
  3. .to(target.dtype) - cast to float32 (so 0.0 or 1.0)
  4. F.mse_loss(x_eq, target) - Mean Squared Error loss between x_eq and target

The MSE loss is: mean((x_eq - target)^2)

So the computation is:

  • For each element i: diff_i = (float(x[i] == target[i]) - target[i])^2
  • The result is the mean of all diff_i values

Total elements: 256 * 512 * 1024 = 134,217,728

I need to implement this as a HIP kernel. The approach:

  1. A kernel that computes (float(x[i] == target[i]) - target[i])^2 for each element
  2. Then sum all values and divide by total count

I can do this with a two-stage reduction:

  • Stage 1: Each thread computes the squared difference for its element(s) and accumulates into a local sum, then uses atomicAdd or a shared memory reduction to write partial sums
  • Stage 2: Reduce the partial sums and divide by N

Let me think about the optimal approach for MI300X (gfx942):

  • 134M elements is a lot
  • I'll use a grid-stride loop pattern
  • Each thread block does a shared memory reduction
  • Write partial sums to a global buffer
  • A second kernel or a single thread computes the final mean

Actually, let me think more carefully. The simplest efficient approach:

  1. First kernel: grid-stride loop, each thread computes (float(x==target) - target)^2 and accumulates into a local sum. Use shared memory reduction per block, atomicAdd to a global scalar.
  2. Second kernel (or just a host read): divide by total N.

Or even simpler: use a single kernel with atomicAdd to a global float, then read back and divide.

Let me write this:

#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <hip/hip_runtime.h>

__global__ void mse_eq_kernel(const float* x, const float* target, float* output, int n) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx >= n) return;
    
    float eq_val = (x[idx] == target[idx]) ? 1.0f : 0.0f;
    float diff = eq_val - target[idx];
    output[idx] = diff * diff;
}

__global__ void reduce_kernel(const float* input, float* output, int n) {
    // shared memory reduction
    __shared__ float sdata[256];
    int tid = threadIdx.x;
    int idx = blockIdx.x * blockDim.x + tid;
    
    float val = 0.0f;
    for (int i = idx; i < n; i += blockDim.x * gridDim.x) {
        val += input[i];
    }
    
    sdata[tid] = val;
    __syncthreads();
    
    for (int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (tid < s) {
            sdata[tid] += sdata[tid + s];
        }
        __syncthreads();
    }
    
    if (tid == 0) {
        atomicAdd(output, sdata[0]);
    }
}

Wait, but the total sum could be large. Let me think about numerical precision. With 134M elements, using float atomicAdd might lose precision. But since the reference uses float32, I'll stick with float32.

Actually, let me reconsider. I can fuse this into a single kernel more efficiently. Let me use a grid-stride approach where each thread handles multiple elements and accumulates locally, then does a block-level reduction with atomicAdd.

Let me also consider: the output is a scalar (0-d tensor). So I need to return a tensor with shape ().

Let me write the complete solution:

#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 = min((n + BLOCK_SIZE - 1) / BLOCK_SIZE, 1024);
    
    fused_mse_eq_kernel<<<num_blocks, BLOCK_SIZE, 0, stream>>>(
        x.data_ptr<float>(), 
        target.data_ptr<float>(), 
        output.data_ptr<float>(), 
        n
    );
    
    // Divide by n
    auto result = output / static_cast<double>(n);
    
    return result.squeeze();
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Fused MSE of equality");
}

Hmm, but doing output / n on GPU creates an extra kernel. Let me think of a better way. I could either:

  1. Do the division in the kernel itself (but that's tricky with atomics)
  2. Use a second tiny kernel
  3. Just do it on the host after reading back (but we need to return a tensor)

Actually, the simplest approach is to just do the division as a tensor operation. It's a scalar so it's basically free. Or I can use a separate reduce kernel that divides.

Actually, let me just keep it simple. The division of a 1-element tensor is negligible. Let me finalize.

Wait, I should also consider: should I use double for accumulation? The reference uses float32, so I'll stick with float32 to match.

Let me also make sure the output shape matches. F.mse_loss returns a scalar tensor (shape {}). Let me return result.squeeze() which should give shape {}.

Actually, looking more carefully at the PyTorch code:

  • torch.eq(x, target) returns a bool tensor
  • .to(target.dtype) converts to float32
  • F.mse_loss(x_eq, target) computes mean((x_eq - target)^2) which returns a 0-d tensor

So my output should be a 0-d float tensor. Let me adjust.

Let me also think about whether I should use at::zeros with dtype matching. Since both inputs are float32, the output should be float32.

Final solution:

#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");
}
```<|im_end|>