openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / layernorm / kernel.cl
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // one work-group per row; get_local_size(0) must be a power of two |
| 3 | __kernel void layernorm(__global const float *x, __global const float *g, __global const float *b, |
| 4 | __global float *y, const int D, __local float *red) |
| 5 | { |
| 6 | int t = get_local_id(0), nt = get_local_size(0); |
| 7 | __global const float *xr = x + (long)get_group_id(0) * D; |
| 8 | __global float *yr = y + (long)get_group_id(0) * D; |
| 9 | float acc = 0.0f; |
| 10 | for (int k = t; k < D; k += nt) |
| 11 | acc += xr[k]; |
| 12 | red[t] = acc; |
| 13 | barrier(CLK_LOCAL_MEM_FENCE); |
| 14 | for (int h = nt / 2; h > 0; h >>= 1) { |
| 15 | if (t < h) |
| 16 | red[t] += red[t + h]; |
| 17 | barrier(CLK_LOCAL_MEM_FENCE); |
| 18 | } |
| 19 | float mu = red[0] / (float)D; |
| 20 | barrier(CLK_LOCAL_MEM_FENCE); |
| 21 | acc = 0.0f; |
| 22 | for (int k = t; k < D; k += nt) { |
| 23 | float c = xr[k] - mu; |
| 24 | acc += c * c; |
| 25 | } |
| 26 | red[t] = acc; |
| 27 | barrier(CLK_LOCAL_MEM_FENCE); |
| 28 | for (int h = nt / 2; h > 0; h >>= 1) { |
| 29 | if (t < h) |
| 30 | red[t] += red[t + h]; |
| 31 | barrier(CLK_LOCAL_MEM_FENCE); |
| 32 | } |
| 33 | float rs = rsqrt(red[0] / (float)D + 1e-5f); |
| 34 | for (int k = t; k < D; k += nt) |
| 35 | yr[k] = (xr[k] - mu) * rs * g[k] + b[k]; |
| 36 | } |