Writing Fused LLM Kernels in Triton (Liger-Kernel): Eliminating the 128k-Vocab Logits VRAM Cliff
When fine-tuning or post-training a modern LLM with a massive vocabulary (e.g., Llama-3's $V = 128{,}256$ or Qwen's $V = 151{,}936$) at sequence length $T = 8192$ and batch size $B = 4$, you will often hit an unexpected CUDA Out-of-Memory crash at the very last line of the forward pass – even when FlashAttention-2 and gradient checkpointing are enabled. Why?
Because standard PyTorch F.cross_entropy(lm_head(H), targets) materializes the entire dense FP32 logits tensor $Z = H W_{\text{lm}}^\top \in \mathbb{R}^{B \times T \times V}$ in HBM ($4 \times 8192 \times 128256 \times 4\text{ bytes} \approx \mathbf{16.8\,\text{GB}}$), plus another $16.8\,\text{GB}$ for its backward gradient $\nabla_Z \mathcal{L}$! Liger-Kernel (Hsu et al., 2024, arXiv:2410.10989; GitHub) eliminates this $33.6\,\text{GB}$ logits cliff by fusing the linear lm_head projection, online log-sum-exp softmax, and backward gradient accumulation inside a chunked Triton kernel so the full $[BT, V]$ logits matrix never exists in HBM.
0. Chunked Fused Linear Cross-Entropy & In-Place Gradient Overwriting
Partition the flattened hidden states $H \in \mathbb{R}^{N \times d}$ ($N = B \cdot T$) into small chunks $H^{(c)} \in \mathbb{R}^{N_c \times d}$ where $N_c = \lceil N / \text{chunks} \rceil$ (typically $N_c = 1024$ or $2048$ tokens). Inside each chunk $c$, we project $Z^{(c)} = H^{(c)} W_{\text{lm}}^\top \in \mathbb{R}^{N_c \times V}$, invoke a Triton online-softmax kernel that computes both the scalar loss $\mathcal{L}^{(c)}$ and overwrites $Z^{(c)}$ in-place with its own gradient $\frac{\partial \mathcal{L}}{\partial Z^{(c)}} = \frac{1}{N}(\mathrm{softmax}(Z^{(c)}) - \mathbf{e}_{y^{(c)}})$, and immediately backpropagate into $H^{(c)}$ and $W_{\text{lm}}$ before freeing the chunk:
Peak HBM drops from $O(2 N V)$ down to $O(N_c V)$ – shrinking $33.6\,\text{GB}$ down to $\sim 0.5\text{–}1.0\,\text{GB}$ ($N_c \in \lbrace 1024, 2048 \rbrace$) with mathematically identical gradients and zero activation recomputation overhead!
tl.sum and Online LogSumExp in tl.float32: Even when input hidden states $H$ and weights $W_{\text{lm}}$ are bfloat16, running tl.exp and tl.sum in bfloat16 loses mantissa precision across $V = 128{,}256$ vocabulary entries and produces NaN gradients on rare tokens.
(2) Handling ignore_index = -100 in SFT Prompt Masking: When computing N_valid = (targets != -100).sum() across chunks, never divide each chunk by its local N_valid_c – precompute global N_valid once before the chunk loop so masked prompt chunks don't distort gradient scaling!
1. Runnable PyTorch Reference: Exact Chunked FusedLinearCrossEntropy Autograd Function
The self-contained custom torch.autograd.Function below implements chunked fused linear cross-entropy with in-place gradient overwriting (the exact host-side driver pattern used by Liger-Kernel), verifying machine-precision gradient equality against full-logits PyTorch autograd:
💻 Python: Chunked FusedLinearCrossEntropy Autograd Function (Zero Full-Logits Materialization)PyTorch / Triton
import torch
import torch.nn.functional as F
class ChunkedFusedLinearCrossEntropy(torch.autograd.Function):
"""Chunked fused linear + cross-entropy (Liger-Kernel pattern, Hsu et al., arXiv:2410.10989)."""
@staticmethod
def forward(ctx, H: torch.Tensor, W: torch.Tensor, targets: torch.Tensor, chunk_size: int = 16) -> torch.Tensor:
# H: [N, D], W: [V, D], targets: [N] (supports ignore_index = -100)
N, _ = H.shape
acc_dtype = torch.float64 if H.dtype == torch.float64 else torch.float32
valid_mask = (targets != -100)
n_valid = valid_mask.sum().clamp(min=1)
total_loss = torch.zeros((), device=H.device, dtype=acc_dtype)
dH = torch.zeros_like(H)
dW = torch.zeros_like(W)
for start in range(0, N, chunk_size):
end = min(start + chunk_size, N)
hc, tc = H[start:end], targets[start:end]
# Project only [chunk_size, V] logits (in Triton, fused with online log-sum-exp)
logits_c = (hc @ W.T).to(acc_dtype)
lse = torch.logsumexp(logits_c, dim=-1, keepdim=True)
probs = torch.exp(logits_c - lse)
vc = (tc != -100).to(acc_dtype)
safe_t = tc.clamp(min=0)
row_idx = torch.arange(end - start, device=H.device)
chunk_nll = -(logits_c[row_idx, safe_t] - lse.squeeze(-1)) * vc
total_loss += chunk_nll.sum() / n_valid
# Overwrite probs in-place to form dZ = (softmax(Z) - one_hot(y)) / n_valid
probs[row_idx, safe_t] -= 1.0
probs.mul_(vc.unsqueeze(-1) / n_valid)
dZ = probs.to(H.dtype)
dH[start:end] = dZ @ W
dW.add_(dZ.T @ hc)
ctx.save_for_backward(dH, dW)
return total_loss
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
dH, dW = ctx.saved_tensors
g = grad_output.to(dH.dtype)
return dH * g, dW * g, None, None
if __name__ == "__main__":
torch.manual_seed(42)
N, D, V = 64, 16, 256
H1 = torch.randn(N, D, dtype=torch.float64, requires_grad=True)
W1 = torch.randn(V, D, dtype=torch.float64, requires_grad=True)
targets = torch.randint(0, V, (N,))
targets[:12] = -100 # SFT prompt masking check
H2, W2 = H1.detach().clone().requires_grad_(True), W1.detach().clone().requires_grad_(True)
loss_ref = F.cross_entropy(H1 @ W1.T, targets, ignore_index=-100)
loss_ref.backward()
loss_fused = ChunkedFusedLinearCrossEntropy.apply(H2, W2, targets, 16)
loss_fused.backward()
print(f"[PASS] Chunked Fused CE Loss Diff : {(loss_ref - loss_fused).abs().item():.2e}")
print(f"[PASS] dH Gradient Max Abs Diff : {(H1.grad - H2.grad).abs().max().item():.2e}")
print(f"[PASS] dW Gradient Max Abs Diff : {(W1.grad - W2.grad).abs().max().item():.2e}")
# Output:
# [PASS] Chunked Fused CE Loss Diff : 1.78e-15
# [PASS] dH Gradient Max Abs Diff : 7.63e-17
# [PASS] dW Gradient Max Abs Diff : 9.71e-17
2. LLM Kernel Fusion Targets: HBM Savings Breakdown
| Operation | Unfused PyTorch Eager | Fused Triton Kernel (Liger-Kernel) |
|---|---|---|
| Linear + Cross-Entropy (128k Vocab) | Materializes $[BT, V]$ logits + grad ($33.6\,\text{GB}$) | Chunked online LSE + in-place dZ ($\sim 0.5\text{–}1.0\,\text{GB}$, up to $80\%$ VRAM cut) |
| RMSNorm + Residual | 4 HBM round-trips (square, mean, rsqrt, scale) | 1 single SRAM load/store pass per token row |
| SwiGLU MLP Gate | Materializes separate silu(gate) and up activations |
Fused elementwise silu(a) * b in SRAM registers |