Liger-Kernel
Liger-Kernel copied to clipboard
[Bug] Silent backward gradient corruption in LigerCrossEntropy on non-contiguous logits (returns raw input logits as dL/dlogits)
Description
Passing a valid non-contiguous logits tensor with stride(-1) != 1 (for example, a transposed tensor (V, N).t() of shape (N, V)) into LigerCrossEntropyFunction computes an accurate forward loss (fwd_err ~ 5e-7) with zero warnings or errors, and then on .backward() silently returns the unmodified raw input logits as dL/dlogits (max_diff > 1.0, completely corrupting gradients).
- Affected Version:
liger-kernel==0.8.3(torch==2.15.0+cu132,triton==3.9.0; reproduced on both RTX 3090sm_86and Colab L4sm_89withtorch==2.14.1) - Component:
liger_kernel/ops/cross_entropy.py:407-408,:458,:545,:563-564
Minimal Reproducer
import torch
import torch.nn.functional as F
from liger_kernel.ops import LigerCrossEntropyFunction
torch.manual_seed(0)
N, V = 37, 257
logits_base = torch.randn((V, N), device="cuda", dtype=torch.float32)
target = torch.randint(0, V, (N,), device="cuda", dtype=torch.int64)
# Non-contiguous view of shape (N, V) with stride(-1) == N != 1
leaf_liger = logits_base.clone().requires_grad_(True)
x_liger = leaf_liger.t()
assert x_liger.shape == (N, V) and x_liger.stride(-1) != 1
loss_liger, *_ = LigerCrossEntropyFunction.apply(x_liger, target, None, -100, 0.0, 0.0, "mean", None, False)
loss_liger.backward()
grad_liger = leaf_liger.grad.t()
# PyTorch reference
leaf_ref = logits_base.clone().requires_grad_(True)
x_ref = leaf_ref.t()
loss_ref = F.cross_entropy(x_ref, target, ignore_index=-100, reduction="mean")
loss_ref.backward()
grad_ref = leaf_ref.grad.t()
fwd_diff = (loss_liger - loss_ref).abs().item()
bwd_diff = (grad_liger - grad_ref).abs().max().item()
raw_eq = torch.equal(grad_liger, logits_base.t())
print(f"Forward loss diff : {fwd_diff:.3e}")
print(f"Backward grad diff: {bwd_diff:.6f}")
print(f"grad_liger == RAW INPUT LOGITS?: {raw_eq}")
assert bwd_diff < 1e-4
Observed Output
Forward loss diff : 4.768e-07
Backward grad diff: 4.234517
grad_liger == RAW INPUT LOGITS?: True
Root Cause
LigerCrossEntropyFunction.forward(cross_entropy.py:545) capturesinput_requires_grad = _input.requires_grad(True) inside PyTorch's implicittorch.no_grad()autograd forward context.- Inside
cross_entropy_forward(cross_entropy.py:407-408), when_input.stride(-1) != 1,_input = _input.contiguous()allocates a contiguous copy whose.requires_gradisFalse(becauseautograd.Function.forwardruns undertorch.no_grad()). - Line 458 passes
HAS_GRADIENTS=_input.requires_grad(nowFalse!) toliger_cross_entropy_kernel, causing the Triton kernel to skip all in-place gradient computation and leave the raw input logits untouched in_input. - Back in
LigerCrossEntropyFunction.forward(line 563),if input_requires_grad:is stillTrue, so it saves the raw-logit_inputbuffer for backward and returns it verbatim asdL/dlogits.
Suggested Fix
Preserve requires_grad across .contiguous() (or pass input_requires_grad explicitly into cross_entropy_forward for HAS_GRADIENTS), e.g.:
# In cross_entropy_forward (liger_kernel/ops/cross_entropy.py:407-408):
input_requires_grad = _input.requires_grad
if _input.stride(-1) != 1:
_input = _input.contiguous()
...
# At line 458:
HAS_GRADIENTS=input_requires_grad,