openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / controls / softmax_unstable / kernel.cu
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | #include <cuda_runtime.h> |
| 3 | #include <math.h> |
| 4 | |
| 5 | #define NT 128 |
| 6 | |
| 7 | // one block of NT threads per row |
| 8 | // CONTROL: the max subtraction is deliberately omitted |
| 9 | __global__ void softmax(const float *x, float *y, long long D) |
| 10 | { |
| 11 | __shared__ float red[NT]; |
| 12 | int t = threadIdx.x; |
| 13 | const float *xr = x + (long long)blockIdx.x * D; |
| 14 | float *yr = y + (long long)blockIdx.x * D; |
| 15 | float acc = 0.0f; |
| 16 | for (long long k = t; k < D; k += NT) { |
| 17 | float e = expf(xr[k]); |
| 18 | yr[k] = e; |
| 19 | acc += e; |
| 20 | } |
| 21 | red[t] = acc; |
| 22 | __syncthreads(); |
| 23 | for (int h = NT / 2; h > 0; h >>= 1) { |
| 24 | if (t < h) |
| 25 | red[t] += red[t + h]; |
| 26 | __syncthreads(); |
| 27 | } |
| 28 | float s = red[0]; |
| 29 | for (long long k = t; k < D; k += NT) |
| 30 | yr[k] = yr[k] / s; |
| 31 | } |
| 32 | |
| 33 | void oal_launch(const long long *p, void *const *buf) |
| 34 | { |
| 35 | softmax<<<(unsigned)p[0], NT>>>((const float *)buf[0], (float *)buf[1], p[1]); |
| 36 | } |