Files
gpt-2-inference-engine/kernels_base/softmax.cuh
T
2026-06-07 13:43:20 -05:00

36 lines
935 B
Plaintext

#ifndef __SOFTMAX_KERNEL_CUH__
#define __SOFTMAX_KERNEL_CUH__
#include <cuda_runtime.h>
#include <math.h>
#include <float.h>
#include "../utils/cuda_utils.cuh"
__global__ void softmax_forward_kernel(float* out, float inv_temperature, const float* inp, int N, int T) {
// Implement this
int x = blockDim.x * blockIdx.x + threadIdx.x;
if(x < N*T){
int own_pos = x % T;
const float* a = inp + x * T;
float maxval = -FLT_MAX;
for (int i = 0; i <= own_pos; i++) {
maxval = fmaxf(maxval,a[i]);
}
float sumval = 0.0f;
for (int i = 0; i <= own_pos; ++i) {
float ev = expf(inv_temperature * (a[i] - maxval));
sumval += ev;
out[x * T + i] = ev;
}
float norm = 1.0f / sumval;
for (int i = 0; i <= own_pos; ++i) {
out[x * T + i] *= norm;
}
}
}
#endif // __SOFTMAX_KERNEL_CUH__