interplane.Get Omega
Read in your language

openaccel-lab

aien-dev/openaccel-lab

Brought by drakestapleton

branch main Branches Tags History

openaccel-lab / controls / attention_nomax / kernel.cu

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