openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / attention / triton_kernel.py
| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | import triton |
| 3 | import triton.language as tl |
| 4 | |
| 5 | |
| 6 | @triton.jit |
| 7 | def _attention(q, k, v, o, D: tl.constexpr, BJ: tl.constexpr): |
| 8 | i = tl.program_id(0) |
| 9 | j = tl.arange(0, BJ) |
| 10 | c = tl.arange(0, D) |
| 11 | live = j <= i |
| 12 | qv = tl.load(q + i * D + c) |
| 13 | kv = tl.load(k + j[:, None] * D + c[None, :], mask=live[:, None], other=0.0) |
| 14 | s = tl.where(live, tl.sum(kv * qv[None, :], axis=1) * 0.125, -1e30) |
| 15 | m = tl.max(s, axis=0) |
| 16 | e = tl.where(live, tl.exp(s - m), 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)) |