|
| 1 | +#include <ATen/cuda/CUDAContext.h> |
| 2 | +#include <c10/cuda/CUDAGuard.h> |
| 3 | +#include <torch/all.h> |
| 4 | + |
| 5 | +#include <cmath> |
| 6 | + |
| 7 | +__global__ void relu_kernel(float *__restrict__ out, |
| 8 | + float const *__restrict__ input, const int d) { |
| 9 | + const int64_t token_idx = blockIdx.x; |
| 10 | + for (int64_t idx = threadIdx.x; idx < d; idx += blockDim.x) { |
| 11 | + auto x = input[token_idx * d + idx]; |
| 12 | + out[token_idx * d + idx] = x > 0.0f ? x : 0.0f; |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +void relu(torch::Tensor &out, torch::Tensor const &input) { |
| 17 | + TORCH_CHECK(input.device().is_cuda(), "input must be a CUDA tensor"); |
| 18 | + TORCH_CHECK(input.is_contiguous(), "input must be contiguous"); |
| 19 | + TORCH_CHECK(input.scalar_type() == at::ScalarType::Float && |
| 20 | + input.scalar_type() == at::ScalarType::Float, |
| 21 | + "relu_kernel only supports float32"); |
| 22 | + |
| 23 | + TORCH_CHECK(input.sizes() == out.sizes(), |
| 24 | + "Tensors must have the same shape. Got input shape: ", |
| 25 | + input.sizes(), " and output shape: ", out.sizes()); |
| 26 | + |
| 27 | + TORCH_CHECK(input.scalar_type() == out.scalar_type(), |
| 28 | + "Tensors must have the same data type. Got input dtype: ", |
| 29 | + input.scalar_type(), " and output dtype: ", out.scalar_type()); |
| 30 | + |
| 31 | + TORCH_CHECK(input.device() == out.device(), |
| 32 | + "Tensors must be on the same device. Got input device: ", |
| 33 | + input.device(), " and output device: ", out.device()); |
| 34 | + |
| 35 | + if (input.numel() == 0) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + int d = input.size(-1); |
| 40 | + int64_t num_tokens = input.numel() / d; |
| 41 | + dim3 grid(num_tokens); |
| 42 | + dim3 block(std::min(d, 1024)); |
| 43 | + const at::cuda::OptionalCUDAGuard device_guard(device_of(input)); |
| 44 | + const cudaStream_t stream = at::cuda::getCurrentCUDAStream(); |
| 45 | + relu_kernel<<<grid, block, 0, stream>>>(out.data_ptr<float>(), |
| 46 | + input.data_ptr<float>(), d); |
| 47 | +} |
0 commit comments