Liger-Kernel
Liger-Kernel copied to clipboard
Fused KL and JSD backward scale the wrong elements when a gradient has a non-unit column stride
#1500 added an X_col_stride argument to element_mul_kernel and passed it from fused linear cross entropy, because zeros_like keeps the layout of a transposed tensor. fused_linear_kl_div_backward and fused_linear_jsd_backward call the same kernel without that argument, so when the loss is scaled and a cached gradient has a non-unit column stride, the kernel scales the wrong addresses. With a transposed weight, (0.0 * loss).backward() leaves non-zero gradients.
import torch
from liger_kernel.ops.fused_linear_jsd import LigerFusedLinearJSDFunction
from liger_kernel.ops.fused_linear_kl_div import LigerFusedLinearKLDivFunction
torch.manual_seed(0)
x = torch.randn(2, 4, device="cuda", requires_grad=True)
w = torch.randn(4, 3, device="cuda").t().requires_grad_(True) # (V=3, H=4) with stride (1, 3)
target = torch.softmax(torch.randn(2, 3, device="cuda"), -1)
loss = LigerFusedLinearKLDivFunction.apply(x, w, target, None, "batchmean", -100, 1.0, 1e-10, None)
(0.0 * loss).backward()
print("KL: max |dW| =", w.grad.abs().max().item(), " nonzero:", (w.grad != 0).sum().item(), "/", w.grad.numel())
x = torch.randn(2, 4, device="cuda", requires_grad=True)
w = torch.randn(4, 3, device="cuda").t().requires_grad_(True)
teacher_x = torch.randn(2, 4, device="cuda")
teacher_w = torch.randn(3, 4, device="cuda")
loss = LigerFusedLinearJSDFunction.apply(x, w, teacher_x, teacher_w, None, 0.5, -100, 1.0, None, "nvidia-triton", None)
(0.0 * loss).backward()
print("JSD: max |dW| =", w.grad.abs().max().item(), " nonzero:", (w.grad != 0).sum().item(), "/", w.grad.numel())
KL: max |dW| = 1.1799956560134888 nonzero: 6 / 12
JSD: max |dW| = 0.03832436725497246 nonzero: 6 / 12
Every element should be zero. Run on main (e44de705) with an NVIDIA B200, torch 2.15.0a0 and Triton 3.8.0.