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

CE+TVD and GRPO: return NaN gradients when the first vocabulary block is fully masked

Open jeffchen006 opened this issue 2 weeks ago • 1 comments

Describe the bug

The combined cross-entropy and total variation distance (CE+TVD) loss and group relative policy optimization (GRPO) loss produce NaN gradients when their first vocabulary block contains only negative infinity, even if a later class is finite. Negative infinity is a standard logit mask. The script leaves one finite selected class, so the reference gradient is exactly zero.

The public calls are LigerFusedCETVDLoss and triton_grpo_loss. The script calls their underlying autograd functions.

Both normalizers start with a maximum of negative infinity and a sum of zero. The first update subtracts negative infinity from itself. That produces NaN and contaminates the denominator. The affected updates are ops/fused_ce_tvd.py:82 and ops/grpo_loss.py:153. Later finite blocks cannot repair the denominator.

Related: #1518 reports and fixes this recurrence in standalone cross-entropy. This issue covers the two sibling implementations left outside that change. The scripts use vocabulary widths 16385 and 2049, respectively.

The cited lines are unchanged on main as of 2026-11-17.

Reproduce

import torch
import torch.nn.functional as F
from liger_kernel.ops.fused_ce_tvd import LigerFusedCETVDFunction as CETVD
from liger_kernel.ops.grpo_loss import GrpoLossFunction as GRPO

dev = "cuda" if torch.cuda.is_available() else "cpu"
torch.set_default_device(dev)
results = []
for name, block in (("CE+TVD", 16384), ("GRPO", 2048)):
    data = torch.full((1, block + 1), -torch.inf)
    data[0, -1] = 0.0
    target = torch.tensor([block])
    if name == "GRPO":
        x = data.repeat(2, 1).reshape(1, 2, block + 1).requires_grad_()
        x_ref = x.detach().clone().requires_grad_()
        loss = GRPO.apply(x, None, None, target.reshape(1, 1), torch.ones(1), None, 1.0, 0.0, 0.2, 0.2, False)[0]
        logp = x_ref[:, :-1].log_softmax(-1)[..., block]
        reference = -torch.exp(logp - logp.detach()).mean()
    else:
        x = data.clone().requires_grad_()
        x_ref = data.clone().requires_grad_()
        loss = CETVD.apply(x, torch.zeros_like(x), target)[0].sum()
        reference = F.cross_entropy(x_ref, target)
    loss.backward()
    reference.backward()
    print(name, "loss:", loss.item(), "expected:", reference.item())
    print(name, "NaN gradient elements:", int(x.grad.isnan().sum()), "expected:", int(x_ref.grad.isnan().sum()))
    results.append(torch.allclose(x.grad, x_ref.grad, atol=1e-6, rtol=1e-6))
assert all(results), "Leading masked blocks make finite-reference gradients NaN"

Output:

CE+TVD loss: nan expected: 0.0
CE+TVD NaN gradient elements: 16385 expected: 0
GRPO loss: -0.800000011920929 expected: -1.0
GRPO NaN gradient elements: 2049 expected: 0
AssertionError: Leading masked blocks make finite-reference gradients NaN

Expected behavior

The cross-entropy component must be zero and the GRPO loss must be -1 for the supplied unit advantage. Both input gradients must be finite and zero, as in the PyTorch references.

Suggested fix

When the updated maximum is still negative infinity, use a finite temporary exponent base so the masked block contributes zero. Keep the true maximum for later finite blocks, as in #1518.

Versions / environment

Liger-Kernel 83746f4 (commit date: 2026-11-14; checked 2026-11-17). torch 2.14.1, triton 3.8.0. Reproduced with Triton's interpreter mode (TRITON_INTERPRET=1). CUDA evaluates negative infinity minus itself as NaN. It uses the same recurrence. The report relies on the NaN gradients; exact GRPO loss clipping of NaN can differ by execution backend.

jeffchen006 avatar Nov 17 '26 23:11 jeffchen006

I'd like to take this. I'll apply the same guard as #1518 to the online normalizers in fused_ce_tvd.py and grpo_loss.py (finite temporary base while the running max is still -inf, true max kept for later blocks) and add regression tests with a fully masked leading block. PR coming shortly.

ankitgala007 avatar Nov 18 '26 03:11 ankitgala007