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

[Bug] LigerFusedGateUpSiLUMulFunction.backward crashes with shape mismatch on any 3D (B, T, 2*H) input tensor

Open ttyang57 opened this issue 2 weeks ago • 1 comments

Description

Calling LigerFusedGateUpSiLUMulFunction.apply(y) on any standard 3D LLM hidden-state tensor (B, T, 2*H) succeeds in forward, then always crashes PyTorch autograd during .backward() with a shape mismatch (got [B*T, 2*H] expected [B, T, 2*H]).

  • Affected Version: liger-kernel==0.8.3 (torch==2.15.0+cu132, triton==3.9.0; also reproduced on Colab L4 sm_89 with torch==2.14.1)
  • Component: liger_kernel/ops/swiglu.py:364-417 (swiglu_fused_gate_up_forward, swiglu_fused_gate_up_backward, LigerFusedGateUpSiLUMulFunction)

Minimal Reproducer

import torch
from liger_kernel.ops import LigerFusedGateUpSiLUMulFunction

y = torch.randn((2, 32, 256), device="cuda", dtype=torch.bfloat16, requires_grad=True)
out = LigerFusedGateUpSiLUMulFunction.apply(y, False)
print(f"Forward PASS: input={tuple(y.shape)} -> output={tuple(out.shape)}")

# Crashes autograd with shape mismatch [64, 256] vs [2, 32, 256]
out.sum().backward()

Observed Error

RuntimeError: Function LigerFusedGateUpSiLUMulFunctionBackward returned an invalid gradient at index 0 - got [64, 256] but expected shape compatible with [2, 32, 256]

Root Cause & Suggested Fix

swiglu_fused_gate_up_forward (swiglu.py:372,386) flattens y = y.view(-1, fused_size) and returns the 2D y (discarding ori_shape), which LigerFusedGateUpSiLUMulFunction.forward saves via ctx.save_for_backward(y). Then swiglu_fused_gate_up_backward (swiglu.py:401-417) returns 2D dy of shape [B*T, 2*H] without reshaping back to ori_shape. Saving ctx.ori_shape = y.shape in forward and returning dy.view(ctx.ori_shape) in backward fixes the crash.

ttyang57 avatar Nov 20 '26 12:11 ttyang57

#take @Tcc0403 I'd like to work on this. I have a local patch that restores the input shape in backward for both in-place and out-of-place calls.

galleonli avatar Nov 20 '26 22:11 galleonli