Triton LayerNorm Forward Kernel
Problem Statement
Implement the forward pass of LayerNorm over the last dimension of a (M, N) tensor: subtract the row mean, divide by the row standard deviation, then scale by weight and shift by bias.
Background
Per row: mean = sum(x)/N, var = sum((x-mean)^2)/N, rstd = 1/sqrt(var + eps), out = (x-mean)rstdweight + bias. Mask invalid columns to 0 before the variance sum.
Your Task
Implement layernorm_kernel and run(M=64, N=256, eps=1e-5) comparing to torch.nn.functional.layer_norm.
How it is tested
Your solution must define a top-level function run(...) that allocates inputs on the GPU, launches your Triton kernel, and returns a boolean from torch.allclose(triton_out, torch_reference, ...). The grader prints run(...); the expected output is True.
Example
M = 64, N = 256, eps = 1e-5
True
- The input values are used to launch the
layernorm_kernelfunction on a GPU, which implements the forward pass of LayerNorm over the last dimension of a(M, N)tensor. - For each row, the
meanis calculated as , and thevaris calculated as , masking invalid columns to 0 before the variance sum. - The row standard deviation
rstdis then calculated as , and the outputoutis computed as . - The output of the
layernorm_kernelfunction is compared to the output oftorch.nn.functional.layer_normusingtorch.allclose, which returnsTrueif the two outputs are close enough, indicating that the implementation is correct.
Constraints
- Compute mean and variance per row using tl.sum
- rstd = 1 / tl.sqrt(var + eps)
- out = (x - mean) * rstd * weight + bias