#198581·pytorch

LayerNorm returns non-zero on constant input: cuWelfordCombine uses a weighted average of means instead of Welford's increment

Author: demandal25Created Sep 25, 2026Updated Sep 25, 2026
Labelstriage reviewmodule: cudamodule: rocmmodule: correctness (silent)module: norms and normalizationbot-triaged

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_norm on a constant input returns a non-zero result. The input has zero variance, so every output element must be exactly zero.

python
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] returns 0x3F7FFFFF, i.e. nextafter(1.0f, 0), instead of 1.0f. The saved rstd is bit-exactly rsqrt(eps) at every width, so sigma2 is exactly 0 and only the mean is wrong. x - mean is then one ulp instead of zero, and rstd = rsqrt(1e-5) = 316.23 amplifies 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:

c
      auto nA = dataA.count * coef;
      auto nB = dataB.count * coef;
      mean = nA*dataA.mean + nB*dataB.mean;        // line 193

This combines two partial means as a weighted average, not as Welford's increment. It is exact only if nA + nB == 1 exactly, which is not guaranteed for any coef, correctly rounded or not. The canonical in-tree Welford combine, WelfordOps::combine in aten/src/ATen/native/SharedReduceOps.h:106-124, instead uses a.mean + delta * nb_over_n, which is exactly mean-preserving whenever both partials agree. That is why torch.mean and torch.var are exact on the very same tensors, and why widths with N % 4 != 0 are clean - they miss the vectorized dispatch predicate and fall back to RowwiseMomentsCUDAKernel, which uses WelfordOps.

On ROCm, coef additionally comes from the hardware approximate reciprocal (line 187), which makes nA + nB != 1 far more often:

c
#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_RECIPROCAL defaults 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_f32 is 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 why 3 * 2^k widths 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_f32

Left alone the compiler emits the IEEE correctly-rounded divide sequence.

Which widths fail

Replicating compute_stats exactly 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_rcpf weighted average (current) 691 / 1024
1.0f / count (IEEE) weighted average (current) 131 / 1024
__builtin_amdgcn_rcpf Welford 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_size 4) in correctly-rounded fp32 predicts 6 failing widths there - 244, 328, 332, 372, 460, 488 - with the mean coming back as 0.9999999403953552 at 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:

python
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.compile is clean because inductor generates its own kernel.

Proposed fix

Use Welford's increment in the combine, keeping whatever reciprocal the platform uses:

c
      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 delta is exactly zero, so the mean cannot move regardless of how accurate coef is. This is architecture-independent by construction and brings cuWelfordCombine into agreement with SharedReduceOps.h. The select covers the idle-lane merge, where dataA.count == 0 would otherwise rescale dataB.mean by count * coef; the mirrored case needs no guard because nB is then exactly zero. sigma2 is unchanged - it already uses nB and is Chan's M2 term, independent of how mean is formed.

__builtin_amdgcn_rcpf(1.0f) is bit-exact, so cuWelfordOnlineSum (line 161), which uses the same intrinsic, is not implicated: on constant input its delta is 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: sigma2 still multiplies by nB, which on ROCm is still formed from the approximate reciprocal, so the variance - and hence rstd - 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 0x3F800000 throughout. Reverting the kernel hunk and rebuilding reproduces the failures at exactly the predicted widths. test_nn.py -k LayerNorm (44), -k rmsnorm (12) and test_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_backward does not recompute the mean; it consumes the saved mean/rstd, and its own 1/N is 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_kernel below M=32768 and cuComputeGradInput at 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 by rstd dominates, 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=0 removes 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=24 7.539457147e-05, W=48 9.424321615e-05, W=192 1.319404982e-04, W=384 1.884864287e-05, W=1536 3.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