interplane.Get Omega
Read in your language

openaccel-lab

aien-dev/openaccel-lab

Brought by drakestapleton

branch main Branches Tags History

openaccel-lab / workloads / softmax / kernel.cu

47 lines · 1219 bytes Raw Blame History
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__global__ void softmax(const float *x, float *y, long long D)
9{
10 __shared__ float red[NT];
11 int t = threadIdx.x;
12 const float *xr = x + (long long)blockIdx.x * D;
13 float *yr = y + (long long)blockIdx.x * D;
14 float acc = -INFINITY;
15 for (long long k = t; k < D; k += NT)
16 acc = fmaxf(acc, xr[k]);
17 red[t] = acc;
18 __syncthreads();
19 for (int h = NT / 2; h > 0; h >>= 1) {
20 if (t < h)
21 red[t] = fmaxf(red[t], red[t + h]);
22 __syncthreads();
23 }
24 float m = red[0];
25 __syncthreads();
26 acc = 0.0f;
27 for (long long k = t; k < D; k += NT) {
28 float e = expf(xr[k] - m);
29 yr[k] = e;
30 acc += e;
31 }
32 red[t] = acc;
33 __syncthreads();
34 for (int h = NT / 2; h > 0; h >>= 1) {
35 if (t < h)
36 red[t] += red[t + h];
37 __syncthreads();
38 }
39 float s = red[0];
40 for (long long k = t; k < D; k += NT)
41 yr[k] = yr[k] / s;
42}
43
44void oal_launch(const long long *p, void *const *buf)
45{
46 softmax<<<(unsigned)p[0], NT>>>((const float *)buf[0], (float *)buf[1], p[1]);
47}