Liger-Kernel icon indicating copy to clipboard operation
Liger-Kernel copied to clipboard

GroupNorm backward: fp16 gradients become NaN and bf16 gradients are wrong

Open bhargavchintam opened this issue 3 weeks ago • 0 comments

#1538 fixed the GroupNorm forward for fp16 and bf16, but the backward kernel still does its tl.sum reductions in the input dtype, and Mean and RSTD are stored in the input dtype (luca-888 pointed at those two in the review of #1538). With 65536 elements in a channel, fp16 tl.sum(wdy) goes past 65504 and through c2 the overflow reaches every element of the input gradient. In the bf16 case below the gradient should be zero, because the normalized values of a group sum to zero.

import torch
from liger_kernel.transformers.group_norm import LigerGroupNorm

torch.manual_seed(0)
x = torch.randn(1, 16, 256, 256, device="cuda", dtype=torch.float16, requires_grad=True)
gn = LigerGroupNorm(16, 4, eps=1e-6).to("cuda", dtype=torch.float16)
y = gn(x)
y.backward(torch.ones_like(y))
print("finite x.grad:", torch.isfinite(x.grad).sum().item(), "/", x.grad.numel())

x = torch.ones(2, 8, 16, device="cuda", dtype=torch.bfloat16)
x[:, :, 8:] = 1.0078125
x.requires_grad_(True)
gn = LigerGroupNorm(8, 4, eps=1e-6).to("cuda", dtype=torch.bfloat16)
y = gn(x)
y.backward(torch.ones_like(y))
print("max |x.grad| (expected 0):", x.grad.abs().max().item())
finite x.grad: 0 / 1048576
max |x.grad| (expected 0): 466.0

Run on main (e44de705) with an NVIDIA B200, torch 2.15.0a0, Triton 3.8.0 and CUDA 13.4. I have not run it on other GPUs.

bhargavchintam avatar Nov 09 '26 09:11 bhargavchintam