diff --git a/src/liger_kernel/ops/group_norm.py b/src/liger_kernel/ops/group_norm.py index 154a97e3d..fe690c6aa 100644 --- a/src/liger_kernel/ops/group_norm.py +++ b/src/liger_kernel/ops/group_norm.py @@ -6,6 +6,7 @@ from liger_kernel.ops.utils import compare_version from liger_kernel.ops.utils import ensure_contiguous +from liger_kernel.ops.utils import torch_to_triton_dtype from liger_kernel.utils import infer_device from liger_kernel.utils import is_npu_available @@ -255,7 +256,7 @@ def group_norm_backward(dY, X, W, B, Mean, RSTD, num_channels, num_groups): ) DW = torch.zeros((num_channels), dtype=W.dtype, device=W.device) DB = torch.zeros((num_channels), dtype=B.dtype, device=B.device) - triton_dtype = tl.float32 if X.dtype == torch.float32 else tl.bfloat16 + triton_dtype = torch_to_triton_dtype.get(W.dtype, tl.bfloat16) BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(hidden_size)) _group_norm_backward_kernel[(batch_size, num_groups)]( diff --git a/test/transformers/test_group_norm.py b/test/transformers/test_group_norm.py index 467c66e61..1a6311551 100644 --- a/test/transformers/test_group_norm.py +++ b/test/transformers/test_group_norm.py @@ -109,3 +109,27 @@ def test_liger_group_norm_low_precision_statistics(shape, num_groups, offset, dt assert torch.isfinite(liger_output).all() assert torch.allclose(liger_output.float(), torch_output, atol=atol, rtol=rtol) + + +@pytest.mark.parametrize( + "shape, num_channels, num_groups", + [ + ((2, 16, 8, 8), 16, 4), + ((2, 8, 16), 8, 4), + ], +) +@pytest.mark.parametrize( + "dtype, atol, rtol", + [ + (torch.float16, 2e-2, 2e-2), + pytest.param( + torch.bfloat16, + 2e-1, + 5e-2, + marks=pytest.mark.skipif(not supports_bfloat16(), reason="bfloat16 not supported on this GPU"), + ), + ], +) +def test_liger_group_norm_low_precision_backward(shape, num_channels, num_groups, dtype, atol, rtol): + """Verify that weight/bias gradients in float16 preserve precision and match PyTorch (#1676).""" + _test_liger_group_norm(shape, num_channels, num_groups, dtype, atol, rtol)