LayerNorm returns non-zero on constant input: cuWelfordCombine uses a weighted average of means instead of Welford's increment
A customer reported it, I reproduced it locally, and the possible solution seems to fix the issue locally. The detailed analysis below was produced with Claude Code.
Summary
F.layer_normon a constant input returns a non-zero result. The input has zero variance, so every output element must be exactly zero.import torch, torch.nn.functional as F x = torch.ones(4, 384, dtype=torch.float32, device='cuda') print(F.layer_norm(x, (384,), eps=1e-5).abs().max()) # ROCm/gfx950: tensor(1.8849e-05, device='cuda:0') expected: tensor(0.)The saved mean is the culprit:
torch.native_layer_norm(x, (384,), None, None, 1e-5)[1]returns0x3F7FFFFF, i.e.nextafter(1.0f, 0), instead of1.0f. The savedrstdis bit-exactlyrsqrt(eps)at every width, sosigma2is exactly 0 and only the mean is wrong.x - meanis then one ulp instead of zero, andrstd = rsqrt(1e-5) = 316.23amplifies it.This is not ROCm-specific. ROCm is much worse, but the underlying formula is wrong on CUDA too - see "Which widths fail" below.
Root cause
aten/src/ATen/native/cuda/layer_norm_kernel.cu,cuWelfordCombine:auto nA = dataA.count * coef; auto nB = dataB.count * coef; mean = nA*dataA.mean + nB*dataB.mean; // line 193This combines two partial means as a weighted average, not as Welford's increment. It is exact only if
nA + nB == 1exactly, which is not guaranteed for anycoef, correctly rounded or not. The canonical in-tree Welford combine,WelfordOps::combineinaten/src/ATen/native/SharedReduceOps.h:106-124, instead usesa.mean + delta * nb_over_n, which is exactly mean-preserving whenever both partials agree. That is whytorch.meanandtorch.varare exact on the very same tensors, and why widths withN % 4 != 0are clean - they miss the vectorized dispatch predicate and fall back toRowwiseMomentsCUDAKernel, which usesWelfordOps.On ROCm,
coefadditionally comes from the hardware approximate reciprocal (line 187), which makesnA + nB != 1far more often:#if defined(USE_ROCM) && defined(USE_LAYERNORM_FAST_RECIPROCAL) auto coef = __builtin_amdgcn_processor_is("gfx90a") ? fn_rcp(count): __builtin_amdgcn_rcpf(count); #else auto coef = fn_rcp(count); #endif
USE_LAYERNORM_FAST_RECIPROCALdefaults ON for every ROCm build (cmake/Dependencies.cmake:1125-1134), and the carve-out names only gfx90a, so gfx942 and gfx950 both take it. Measured on gfx950,v_rcp_f32is exact at every power of two and at 5, 9, 10, 20, 36, 40, 80, but 1 ulp low at 3, 6, 12, 24, 48, 96, 192, 384, 768 and 1536 - which is why3 * 2^kwidths are the ones that stand out in ROCm bug reports.The ROCm reciprocal is a source-level choice, not a compiler lowering. Compiling one translation unit twice for gfx950, changing only that macro:
WITH -DUSE_LAYERNORM_FAST_RECIPROCAL : v_rcp_f32_e32 v0, v2 WITHOUT : v_div_scale_f32 / v_rcp_f32_e32 / v_div_fmas_f32 / v_div_fixup_f32Left alone the compiler emits the IEEE correctly-rounded divide sequence.
Which widths fail
Replicating
compute_statsexactly in a standalone kernel, so that the reciprocal and the formula can be switched independently in one binary, and sweeping every width from 4 to 4096 in steps of 4 (1024 widths) on an MI355X:
reciprocal mean formula failing widths __builtin_amdgcn_rcpfweighted average (current) 691 / 1024 1.0f / count(IEEE)weighted average (current) 131 / 1024 __builtin_amdgcn_rcpfWelford increment (proposed) 0 / 1024 1.0f / count(IEEE)Welford increment (proposed) 0 / 1024 The second row is the important one: with a correctly-rounded reciprocal the current formula still fails at 131 widths, the smallest being 164, 188, 220, 244, 460, 488, 564, 636. Only the formula change fixes it; reciprocal accuracy alone does not.
Those figures are for a wave64 / 256-thread block. A simulation of the CUDA block shape (warp 32, 128 threads,
vec_size4) in correctly-rounded fp32 predicts 6 failing widths there - 244, 328, 332, 372, 460, 488 - with the mean coming back as0.9999999403953552at width 244. The same simulator reproduces the measured wave64 failure list exactly, which is the basis for trusting it, but I had no NVIDIA device and this half is unverified on hardware. Someone with an A100 or similar should run:x = torch.ones(4, 244, dtype=torch.float32, device='cuda') F.layer_norm(x, (244,), eps=1e-5).abs().max() # expected 0.Row count is irrelevant. fp32, bf16 and fp16 all fail identically; fp64 is clean because it does not take the vectorized path.
torch.compileis clean because inductor generates its own kernel.Proposed fix
Use Welford's increment in the combine, keeping whatever reciprocal the platform uses:
auto nB = dataB.count * coef; mean = (dataA.count == U(0)) ? dataB.mean : dataA.mean + delta * nB; sigma2 = dataA.sigma2 + dataB.sigma2 + delta * delta * dataA.count * nB;On constant input
deltais exactly zero, so the mean cannot move regardless of how accuratecoefis. This is architecture-independent by construction and bringscuWelfordCombineinto agreement withSharedReduceOps.h. The select covers the idle-lane merge, wheredataA.count == 0would otherwise rescaledataB.meanbycount * coef; the mirrored case needs no guard becausenBis then exactly zero.sigma2is unchanged - it already usesnBand is Chan'sM2term, independent of howmeanis formed.
__builtin_amdgcn_rcpf(1.0f)is bit-exact, socuWelfordOnlineSum(line 161), which uses the same intrinsic, is not implicated: on constant input itsdeltais exactly zero from the second element onward, and the first element divides by a count of exactly 1.Out of scope, stated so it is not mistaken for an oversight:
sigma2still multiplies bynB, which on ROCm is still formed from the approximate reciprocal, so the variance - and hencerstd- remains inexact for non-constant input. That is ordinary floating-point accuracy rather than the exactness bug reported here.Verification
With the patch applied, all 1024 widths return exactly zero in fp32, bf16 and fp16, and the saved mean is bit-exactly
0x3F800000throughout. Reverting the kernel hunk and rebuilding reproduces the failures at exactly the predicted widths.test_nn.py -k LayerNorm(44),-k rmsnorm(12) andtest_ops.py -k layer_norm(164) all pass with the patch.Throughput, fp32 forward, MI355X, same tree and flags, best of 5 medians per run, ~256 MB of input at each width:
W unpatched patched 384 228.55 us, 2349.0 GB/s 225.12 us, 2384.8 GB/s 4096 123.56 us, 4345.1 GB/s 123.20 us, 4357.7 GB/s Run-to-run spread across four repeats of the patched build was 0.34% at W=384 and 0.08% at W=4096, so there is no throughput regression. The patched build measured marginally faster, but the unpatched column is a single sample and no speedup is claimed.
Backward
native_layer_norm_backwarddoes not recompute the mean; it consumes the savedmean/rstd, and its own1/Nis a hoisted true divide. It has no Welford reduction, so it inherits the forward error rather than adding one. Both ROCm paths were exercised -layer_norm_grad_input_kernelbelow M=32768 andcuComputeGradInputat or above it.Worth stating plainly, because it bounds what this bug explains: on a near-constant input (
ones + 1e-6 * randn) the max abs dX error against an fp64 reference is unchanged by the fix - 2.14e-04 at W=384 both before and after, and likewise at every other width tested. Once the input is not exactly constant the per-lane means differ, ordinary reduction rounding amplified byrstddominates, and the one-ulp mean bias is no longer the leading term. What the fix closes exactly is the exactly-constant case.Workaround for existing ROCm builds
Rebuilding with
USE_LAYERNORM_FAST_RECIPROCAL=0removes the 691-width ROCm case but leaves the 131-width IEEE case, so it is a mitigation, not a fix.Environment
torch : 2.11.0+rocm7.14.1 (reproduction) / built from source at HIP 7.14.60850 (fix) HIP : 7.14.60850 device : AMD Instinct MI355X, gfx950:sramecc+:xnack-Update: gfx942 measured. On an MI300X the failure is bit-identical to gfx950 at every width tried - W=12
5.654592678e-05, W=247.539457147e-05, W=489.424321615e-05, W=1921.319404982e-04, W=3841.884864287e-05, W=15363.769728573e-05, with the same saved-mean bit patterns, and 16/20/36/40/80/256/4096 exactly zero. That run used torch 2.7.1+rocm6.4.1, so this is long-standing rather than a recent regression. W=244 also fails there (7.539457147e-05), which is one of the widths predicted above for the CUDA block shape.
cc @ptrblck @msaroufim @eqy @tinglvv @nWEIdia @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang
Source: pytorch/pytorch