openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / attention / kernel.cu
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | #include <cuda_runtime.h> |
| 3 | |
| 4 | // attn_p: one thread per row i writes the softmax weights pw[i][j], j <= i. |
| 5 | __global__ void attn_p(const float *q, const float *k, float *pw, int T, int D) |
| 6 | { |
| 7 | int i = blockIdx.x * blockDim.x + threadIdx.x; |
| 8 | if (i >= T) |
| 9 | return; |
| 10 | float m = -1e30f; |
| 11 | for (int j = 0; j <= i; j++) { |
| 12 | float acc = 0.0f; |
| 13 | for (int c = 0; c < D; c++) |
| 14 | acc += q[i * D + c] * k[j * D + c]; |
| 15 | float s = acc * 0.125f; |
| 16 | pw[i * T + j] = s; |
| 17 | m = fmaxf(m, s); |
| 18 | } |
| 19 | float z = 0.0f; |
| 20 | for (int j = 0; j <= i; j++) { |
| 21 | float e = expf(pw[i * T + j] - m); |
| 22 | pw[i * T + j] = e; |
| 23 | z += e; |
| 24 | } |
| 25 | for (int j = 0; j <= i; j++) |
| 26 | pw[i * T + j] = pw[i * T + j] / z; |
| 27 | } |
| 28 | |
| 29 | // attn_o: o[i][c] = sum_{j <= i} pw[i][j] v[j][c]. |
| 30 | __global__ void attn_o(const float *pw, const float *v, float *o, int T, int D) |
| 31 | { |
| 32 | int c = blockIdx.x * blockDim.x + threadIdx.x; |
| 33 | int i = blockIdx.y; |
| 34 | if (i >= T || c >= D) |
| 35 | return; |
| 36 | float acc = 0.0f; |
| 37 | for (int j = 0; j <= i; j++) |
| 38 | acc += pw[i * T + j] * v[j * D + c]; |
| 39 | o[i * D + c] = acc; |
| 40 | } |
| 41 | |
| 42 | void oal_launch(const long long *p, void *const *buf) |
| 43 | { |
| 44 | int T = (int)p[0]; |
| 45 | int D = (int)p[1]; |
| 46 | float *pw = (float *)buf[4]; |
| 47 | attn_p<<<(T + 63) / 64, 64>>>((const float *)buf[0], (const float *)buf[1], pw, T, D); |
| 48 | dim3 grid((D + 63) / 64, T); |
| 49 | attn_o<<<grid, 64>>>(pw, (const float *)buf[2], (float *)buf[3], T, D); |
| 50 | } |