openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / attention / kernel.cl
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // attn_p: one work-item per row i writes the softmax weights pw[i][j], j <= i. |
| 3 | __kernel void attn_p(__global const float *q, __global const float *k, __global float *pw, |
| 4 | const int T, const int D) |
| 5 | { |
| 6 | int i = get_global_id(0); |
| 7 | if (i >= T) |
| 8 | return; |
| 9 | float m = -1e30f; |
| 10 | for (int j = 0; j <= i; j++) { |
| 11 | float acc = 0.0f; |
| 12 | for (int c = 0; c < D; c++) |
| 13 | acc += q[i * D + c] * k[j * D + c]; |
| 14 | float s = acc * 0.125f; |
| 15 | pw[i * T + j] = s; |
| 16 | m = fmax(m, s); |
| 17 | } |
| 18 | float z = 0.0f; |
| 19 | for (int j = 0; j <= i; j++) { |
| 20 | float e = exp(pw[i * T + j] - m); |
| 21 | pw[i * T + j] = e; |
| 22 | z += e; |
| 23 | } |
| 24 | for (int j = 0; j <= i; j++) |
| 25 | pw[i * T + j] = pw[i * T + j] / z; |
| 26 | } |
| 27 | |
| 28 | // attn_o: o[i][c] = sum_{j <= i} pw[i][j] v[j][c]. |
| 29 | __kernel void attn_o(__global const float *pw, __global const float *v, __global float *o, |
| 30 | const int T, const int D) |
| 31 | { |
| 32 | int i = get_global_id(0); |
| 33 | int c = get_global_id(1); |
| 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 | } |