openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / layernorm / 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 _layernorm(x, g, b, y, D, BLOCK: tl.constexpr): |
| 8 | r = tl.program_id(0) |
| 9 | k = tl.arange(0, BLOCK) |
| 10 | m = k < D |
| 11 | v = tl.load(x + r * D + k, mask=m, other=0.0) |
| 12 | mu = tl.sum(v, axis=0) / D |
| 13 | c = tl.where(m, v - mu, 0.0) |
| 14 | var = tl.sum(c * c, axis=0) / D |
| 15 | rs = 1.0 / tl.sqrt(var + 1e-5) |
| 16 | out = c * rs * tl.load(g + k, mask=m, other=0.0) + tl.load(b + k, mask=m, other=0.0) |
| 17 | tl.store(y + r * D + k, out, mask=m) |
| 18 | |
| 19 | |
| 20 | def launch(p, t): |
| 21 | _layernorm[(p["R"],)](t["x"], t["gamma"], t["beta"], t["y"], p["D"], BLOCK=triton.next_power_of_2(p["D"])) |