|
| 1 | +#ifndef __GELUTANH_CUDA_H__ |
| 2 | +#define __GELUTANH_CUDA_H__ |
| 3 | + |
| 4 | +#include "../../../elementwise/nvidia/elementwise_nvidia.cuh" |
| 5 | +#include <cmath> |
| 6 | +#include <cuda_bf16.h> |
| 7 | +#include <cuda_fp16.h> |
| 8 | + |
| 9 | +namespace op::gelutanh::cuda { |
| 10 | + |
| 11 | +typedef struct GeluTanhOp { |
| 12 | +public: |
| 13 | + static constexpr size_t num_inputs = 1; |
| 14 | + |
| 15 | + // GELU-Tanh constants |
| 16 | + // static constexpr float alpha = std::sqrt(2.0 / M_PI); |
| 17 | + // static constexpr float beta = 0.044715f; |
| 18 | + static constexpr float alpha = 0.7978845608f; // sqrt(2/pi) |
| 19 | + static constexpr float beta = 0.044715f; |
| 20 | + // f32 tanh helper |
| 21 | + __device__ __forceinline__ float tanh_f32_func(float x) const { |
| 22 | + return tanhf(x); |
| 23 | + } |
| 24 | + |
| 25 | + template <typename T> |
| 26 | + __device__ __forceinline__ T operator()(const T &x) const { |
| 27 | + if constexpr (std::is_same_v<T, half2>) { |
| 28 | + // half2 -> float2 |
| 29 | + float2 vf = __half22float2(x); |
| 30 | + float inner_x0 = alpha * (vf.x + beta * vf.x * vf.x * vf.x); |
| 31 | + float inner_x1 = alpha * (vf.y + beta * vf.y * vf.y * vf.y); |
| 32 | + float2 vr = make_float2(tanh_f32_func(inner_x0) * 0.5f + 0.5f, |
| 33 | + tanh_f32_func(inner_x1) * 0.5f + 0.5f); |
| 34 | + return __hmul2(x, __float22half2_rn(vr)); // y = x * 0.5 * (1 + tanh(...)) |
| 35 | + } else if constexpr (std::is_same_v<T, half>) { |
| 36 | + float xf = __half2float(x); |
| 37 | + float inner = alpha * (xf + beta * xf * xf * xf); |
| 38 | + float yf = xf * 0.5f * (1.0f + tanh_f32_func(inner)); |
| 39 | + return __float2half_rn(yf); |
| 40 | + } else if constexpr (std::is_same_v<T, __nv_bfloat16>) { |
| 41 | + float xf = __bfloat162float(x); |
| 42 | + float inner = alpha * (xf + beta * xf * xf * xf); |
| 43 | + float yf = xf * 0.5f * (1.0f + tanh_f32_func(inner)); |
| 44 | + return __float2bfloat16(yf); |
| 45 | + } else if constexpr (std::is_same_v<T, float>) { |
| 46 | + float inner = alpha * (x + beta * x * x * x); |
| 47 | + return x * 0.5f * (1.0f + tanh_f32_func(inner)); |
| 48 | + } else { // double |
| 49 | + double inner = alpha * (x + beta * x * x * x); |
| 50 | + return x * 0.5 * (1.0 + std::tanh(inner)); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | +} GeluTanhOp; |
| 55 | + |
| 56 | +} // namespace op::gelutanh::cuda |
| 57 | + |
| 58 | +#endif // __GELUTANH_CUDA_H__ |
0 commit comments