openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / controls / attention_nomax / triton_kernel.py
| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # CONTROL attention_nomax: exp(s_j) without subtracting the row max. |
| 3 | import triton |
| 4 | import triton.language as tl |
| 5 | |
| 6 | |
| 7 | @triton.jit |
| 8 | def _attention(q, k, v, o, D: tl.constexpr, BJ: tl.constexpr): |
| 9 | i = tl.program_id(0) |
| 10 | j = tl.arange(0, BJ) |
| 11 | c = tl.arange(0, D) |
| 12 | live = j <= i |
| 13 | qv = tl.load(q + i * D + c) |
| 14 | kv = tl.load(k + j[:, None] * D + c[None, :], mask=live[:, None], other=0.0) |
| 15 | s = tl.where(live, tl.sum(kv * qv[None, :], axis=1) * 0.125, -1e30) |
| 16 | e = tl.where(live, tl.exp(s), 0.0) |
| 17 | pw = e / tl.sum(e, axis=0) |
| 18 | vv = tl.load(v + j[:, None] * D + c[None, :], mask=live[:, None], other=0.0) |
| 19 | tl.store(o + i * D + c, tl.sum(pw[:, None] * vv, axis=0)) |
| 20 | |
| 21 | |
| 22 | def launch(p, t): |
| 23 | n = p["T"] |
| 24 | _attention[(n,)](t["q"], t["k"], t["v"], t["o"], D=p["Dh"], BJ=triton.next_power_of_2(n)) |