Vaibhav JindalandClaude Opus 4.6 b7025a7027 Improve bwd kernel for fused_add_rms_norm (#1187)
## Summary
This has been generated using the `liger-kernel-perf` skill introduced
in #1185 .

Restructure the backward kernel of `fused_add_rms_norm` to reduce peak
register liveness, dropping register count from **115 → 95 per thread**
on H100. This eliminates a performance cliff at large hidden sizes and
yields up to **70% backward speedup** at H=16384.

## Root Cause Analysis

NCU profiling on H100 revealed the backward kernel was severely
underutilizing the GPU:

| Metric | Forward Kernel | Backward Kernel |
|--------|---------------|-----------------|
| Registers/Thread | 40 | **115** |
| Theoretical Occupancy | 75% | **25%** |
| Achieved Occupancy | 67.87% | **12.49%** |
| Blocks/SM (register-limited) | 6 | **2** |
| Waves/SM | 5.17 | **0.50** |
| Memory Throughput (% peak) | 78.24% | 60.88% |
| Compute Throughput (% peak) | 27.64% | 19.87% |

The H100 has 65,536 registers per SM. With 256 threads/block (8 warps x
32 threads), each thread using 115 registers consumes 115 x 256 = 29,440
registers per block. This means only `floor(65536 / 29440) = 2` blocks
can run concurrently per SM, yielding just 12.5% occupancy. With so few
active warps, the GPU cannot overlap memory accesses with computation —
stalling 77.5% of scheduler slots.

### Why so many registers?

The backward kernel processes one row per loop iteration, maintaining
several BLOCK_SIZE-wide vectors simultaneously in registers. With
BLOCK_SIZE=4096 and 256 threads, each thread handles 16 elements per
vector, requiring 16 registers per vector. The original code had up to
**~8 vectors live simultaneously** at peak:

| Vector | Lifetime | Purpose |
|--------|----------|---------|
| `W_row` | Persistent (loop-invariant) | Weight + offset |
| `dW_row` | Persistent (accumulator) | Weight gradient |
| `col_offsets` | Persistent | Column indices |
| `mask` | Persistent | Bounds mask |
| `dY_row` | Per-iteration | Upstream gradient |
| `X_row` | Per-iteration | Saved residual (fp32) |
| `m` | Per-iteration | `dY * W` intermediate |
| `dX_row` | Per-iteration | Output gradient |
| `dS_out_row` | Per-iteration (conditional) | Residual stream gradient
|

At 16 registers per vector x 8 vectors = 128 registers, plus
scalars/pointers/loop vars, this matches the observed 115 registers
(compiler optimizes some away).

## Changes

### 1. Reorder: compute dW before dX

**Before:** The original code computed `m -> dX -> dW -> store dX`. This
meant `dY_row`, `m`, `X_row`, `dX_row`, and `dW_row` were all live
simultaneously during the dW accumulation.

**After:** By computing `dW` first (`dW -> m -> dX -> store dX`), the
compiler can reuse `dY_row`'s registers when computing `m = dY_row *
W_row`, since `dY_row` is no longer needed independently after the dW
step. This is safe because both `dW` and `m` read `dY_row` — they don't
modify it (except in GEMMA mode where the cast happens after dW).

### 2. Factor the dX formula with a precomputed scalar

**Before:**
```python
dX_row = rstd_row * m
dX_row += (rstd_row) * (-(1 / n_cols) * rstd_row * rstd_row * tl.sum(m * X_row, axis=0) * X_row)
```

This expression keeps `m`, `X_row`, and the intermediate `rstd * (... *
X_row)` vector all live while computing the compound expression.

**After:**
```python
dot = tl.sum(m * X_row, axis=0)                              # scalar reduction
c = -(1.0 / n_cols) * rstd_row * rstd_row * rstd_row * dot   # scalar
dX_row = rstd_row * m + c * X_row                             # single fused expression
```

By precomputing `c` as a scalar, the final `dX_row` expression is a
simple element-wise combination of two vectors (`m` and `X_row`) scaled
by scalars. The compiler doesn't need to keep intermediate vector
results alive — it can compute each element of `dX_row` independently,
allowing better register reuse.

### 3. Defer dS_out load

**Before:** `dS_out_row` was loaded and added to `dX_row` inside the
compound correction expression, contributing to peak liveness.

**After:** `dS_out_row` is loaded only after the `dX_row = rstd * m + c
* X` computation is complete. By this point, `m` registers are freed, so
`dS_out_row` reuses them rather than competing for register space.

### 4. Add `num_stages=2` for Hopper software pipelining

**Rationale:** The current code never sets `num_stages`, so Triton
defaults to `num_stages=1` (no software pipelining). On H100 (Hopper
architecture), setting `num_stages >= 2` enables the compiler to overlap
memory loads for the next iteration with computation for the current
iteration using Hopper's async copy engine (TMA).

A parameter sweep confirmed `num_stages=2` is safe across all hidden
sizes with no regressions. Higher values (3-4) showed no additional
benefit for this kernel because the backward kernel's low occupancy
limits the pipeline depth that can be effectively utilized.
`num_stages=2` was chosen as the conservative optimal: it enables basic
pipelining without increasing register pressure (higher stages require
more pipeline buffer registers).

The `num_stages` value is passed through `ctx` from forward to backward,
following the same pattern as `BLOCK_SIZE` and `num_warps`.

### Combined effect

After these changes, the peak register liveness drops to ~5-6 vectors:

| Vector | Still live? |
|--------|------------|
| `W_row` | Yes (persistent) |
| `dW_row` | Yes (persistent) |
| `col_offsets` | Yes (persistent) |
| `mask` | Yes (persistent) |
| `dY_row` / `m` | **Shared** (compiler reuses registers) |
| `X_row` / `dX_row` | **Shared** (compiler reuses after dot product) |
| `dS_out_row` | Loaded late, **reuses freed `m` registers** |

NCU confirmed registers dropped from **115 → 95 per thread** (17%
reduction). While this doesn't cross the 85-register threshold needed
for 3 blocks/SM, the reduced pressure gives the compiler more freedom
for instruction scheduling and ILP (instruction-level parallelism),
which explains the dramatic speedup especially at H=16384 where the
original had extreme register spilling.

## Benchmark Results

**NVIDIA H100 80GB HBM3, M=2048, dtype=float32**

### Speed

| Mode | H | Before (ms) | After (ms) | Improvement |
|------|---|------------|-----------|-------------|
| Backward | 2048 | 0.124 | 0.096 | **23% faster** |
| Backward | 4096 | 0.124 | 0.101 | **18% faster** |
| Backward | 8192 | 0.153 | 0.154 | ~same |
| Backward | 16384 | 1.006 | 0.300 | **70% faster (3.35x)** |
| Backward | 32768 | 1.390 | 1.119 | **20% faster** |
| Full | 16384 | 1.186 | 0.482 | **59% faster** |
| Full | 32768 | 1.819 | 1.550 | **15% faster** |
| Forward | all sizes | - | - | unchanged |

### Memory

No change at any size (~30% savings vs HuggingFace maintained).

### Plots

**Backward Speed** (before / after / HuggingFace):

<!-- Paste backward speed plot here -->

**Full Pass Speed**:

<!-- Paste full pass speed plot here -->

**Forward Speed** (unchanged):

<!-- Paste forward speed plot here -->

**Memory** (unchanged):

<!-- Paste memory plot here -->

## Test plan

- [x] Full test suite passed: `python -m pytest
test/transformers/test_fused_add_rms_norm.py -xvs` (40/40 tests, all
casting modes + dtypes + shapes)
- [x] Checkstyle passed (ruff)
- [x] No memory regression at any hidden size
- [x] No forward pass regression
- [x] Benchmarked on NVIDIA H100 80GB HBM3
- [x] NCU profiling confirmed register reduction (115 → 95)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-04-08 19:41:01 +00:00
2024-08-13 11:09:50 -07:00
2025-08-30 08:33:05 -07:00
2024-10-01 21:10:42 +00:00
2026-02-12 00:01:06 +00:00

Liger Kernel: Efficient Triton Kernels for LLM Training

Stable Nightly Discord
Downloads (Stable) PyPI - Version Downloads (Nightly) PyPI - Version Join Our Discord

Installation | Getting Started | Examples | High-level APIs | Low-level APIs | Cite our work

Latest News 🔥

Liger Kernel is a collection of Triton kernels designed specifically for LLM training. It can effectively increase multi-GPU training throughput by 20% and reduces memory usage by 60%. We have implemented Hugging Face Compatible RMSNorm, RoPE, SwiGLU, CrossEntropy, FusedLinearCrossEntropy, and more to come. The kernel works out of the box with Flash Attention, PyTorch FSDP, and Microsoft DeepSpeed. We welcome contributions from the community to gather the best kernels for LLM training.

We've also added optimized Post-Training kernels that deliver up to 80% memory savings for alignment and distillation tasks. We support losses like DPO, CPO, ORPO, SimPO, KTO, JSD, and many more. Check out how we optimize the memory.

You can view the documentation site for additional installation, usage examples, and API references:https://linkedin.github.io/Liger-Kernel/

You can view the Liger Kernel Technical Report: https://openreview.net/forum?id=36SjAIT42G

Supercharge Your Model with Liger Kernel

Banner

With one line of code, Liger Kernel can increase throughput by more than 20% and reduce memory usage by 60%, thereby enabling longer context lengths, larger batch sizes, and massive vocabularies.

Speed Up Memory Reduction
Speed up Memory

Note:

  • Benchmark conditions: LLaMA 3-8B, Batch Size = 8, Data Type = bf16, Optimizer = AdamW, Gradient Checkpointing = True, Distributed Strategy = FSDP1 on 8 A100s.
  • Hugging Face models start to OOM at a 4K context length, whereas Hugging Face + Liger Kernel scales up to 16K.

Optimize Post Training with Liger Kernel

Post Training

We provide optimized post training kernels like DPO, ORPO, SimPO, and more which can reduce memory usage by up to 80%. You can easily use them as python modules.

from liger_kernel.chunked_loss import LigerFusedLinearORPOLoss
orpo_loss = LigerFusedLinearORPOLoss()
y = orpo_loss(lm_head.weight, x, target)

Examples

Use Case Description
Hugging Face Trainer Train LLaMA 3-8B ~20% faster with over 40% memory reduction on Alpaca dataset using 4 A100s with FSDP
Lightning Trainer Increase 15% throughput and reduce memory usage by 40% with LLaMA3-8B on MMLU dataset using 8 A100s with DeepSpeed ZeRO3
Medusa Multi-head LLM (Retraining Phase) Reduce memory usage by 80% with 5 LM heads and improve throughput by 40% using 8 A100s with FSDP
Vision-Language Model SFT Finetune Qwen2-VL on image-text data using 4 A100s with FSDP
Liger ORPO Trainer Align Llama 3.2 using Liger ORPO Trainer with FSDP with 50% memory reduction

Key Features

  • Ease of use: Simply patch your Hugging Face model with one line of code, or compose your own model using our Liger Kernel modules.
  • Time and memory efficient: In the same spirit as Flash-Attn, but for layers like RMSNorm, RoPE, SwiGLU, and CrossEntropy! Increases multi-GPU training throughput by 20% and reduces memory usage by 60% with kernel fusion, in-place replacement, and chunking techniques.
  • Exact: Computation is exact—no approximations! Both forward and backward passes are implemented with rigorous unit tests and undergo convergence testing against training runs without Liger Kernel to ensure accuracy.
  • Lightweight: Liger Kernel has minimal dependencies, requiring only Torch and Triton—no extra libraries needed! Say goodbye to dependency headaches!
  • Multi-GPU supported: Compatible with multi-GPU setups (PyTorch FSDP, DeepSpeed, DDP, etc.).
  • Trainer Framework Integration: Axolotl, LLaMa-Factory, SFTTrainer, Hugging Face Trainer, SWIFT, oumi

Installation

Dependencies

CUDA

  • torch >= 2.1.2
  • triton >= 2.3.0

ROCm

  • torch >= 2.5.0 Install according to the instruction in Pytorch official webpage.
  • triton >= 3.0.0 Install from pypi. (e.g. pip install triton==3.0.0)
pip install -e .[dev]
pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.3/

Optional Dependencies

  • transformers >= 4.x: Required if you plan to use the transformers models patching APIs. The specific model you are working will dictate the minimum version of transformers.

Note: Our kernels inherit the full spectrum of hardware compatibility offered by Triton.

To install the stable version:

$ pip install liger-kernel

To install the nightly version:

$ pip install liger-kernel-nightly

To install from source:

git clone https://github.com/linkedin/Liger-Kernel.git
cd Liger-Kernel

# Install Default Dependencies
# Setup.py will detect whether you are using AMD or NVIDIA
pip install -e .

# Setup Development Dependencies
pip install -e ".[dev]"

# NOTE -> For AMD users only
pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.3/

Getting Started

There are a couple of ways to apply Liger kernels, depending on the level of customization required.

1. Use AutoLigerKernelForCausalLM

Using the AutoLigerKernelForCausalLM is the simplest approach, as you don't have to import a model-specific patching API. If the model type is supported, the modeling code will be automatically patched using the default settings.

from liger_kernel.transformers import AutoLigerKernelForCausalLM

# This AutoModel wrapper class automatically monkey-patches the
# model with the optimized Liger kernels if the model is supported.
model = AutoLigerKernelForCausalLM.from_pretrained("path/to/some/model")

2. Apply Model-Specific Patching APIs

Using the patching APIs, you can swap Hugging Face models with optimized Liger Kernels.

import transformers
from liger_kernel.transformers import apply_liger_kernel_to_llama

# 1a. Adding this line automatically monkey-patches the model with the optimized Liger kernels
apply_liger_kernel_to_llama()

# 1b. You could alternatively specify exactly which kernels are applied
apply_liger_kernel_to_llama(
  rope=True,
  swiglu=True,
  cross_entropy=True,
  fused_linear_cross_entropy=False,
  rms_norm=False
)

# 2. Instantiate patched model
model = transformers.AutoModelForCausalLM("path/to/llama/model")

3. Compose Your Own Model

You can take individual kernels to compose your models.

from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
import torch.nn as nn
import torch

model = nn.Linear(128, 256).cuda()

# fuses linear + cross entropy layers together and performs chunk-by-chunk computation to reduce memory
loss_fn = LigerFusedLinearCrossEntropyLoss()

input = torch.randn(4, 128, requires_grad=True, device="cuda")
target = torch.randint(256, (4, ), device="cuda")

loss = loss_fn(model.weight, input, target)
loss.backward()

High-level APIs

AutoModel

AutoModel Variant API
AutoModelForCausalLM liger_kernel.transformers.AutoLigerKernelForCausalLM

Patching

Model API Supported Operations
Llama4 (Text) & (Multimodal) liger_kernel.transformers.apply_liger_kernel_to_llama4 RMSNorm, LayerNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy
LLaMA 2 & 3 liger_kernel.transformers.apply_liger_kernel_to_llama RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
LLaMA 3.2-Vision liger_kernel.transformers.apply_liger_kernel_to_mllama RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Ministral liger_kernel.transformers.apply_liger_kernel_to_ministral RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Mistral liger_kernel.transformers.apply_liger_kernel_to_mistral RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Mixtral liger_kernel.transformers.apply_liger_kernel_to_mixtral RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Nemotron liger_kernel.transformers.apply_liger_kernel_to_nemotron ReLUSquared, CrossEntropyLoss, FusedLinearCrossEntropy
Pixtral liger_kernel.transformers.apply_liger_kernel_to_pixtral RoPE, RMSNorm, SwiGLU
Gemma1 liger_kernel.transformers.apply_liger_kernel_to_gemma RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Gemma2 liger_kernel.transformers.apply_liger_kernel_to_gemma2 RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Gemma3 (Text) liger_kernel.transformers.apply_liger_kernel_to_gemma3_text RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Gemma3 (Multimodal) liger_kernel.transformers.apply_liger_kernel_to_gemma3 LayerNorm, RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Paligemma, Paligemma2, & Paligemma2 Mix liger_kernel.transformers.apply_liger_kernel_to_paligemma LayerNorm, RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Qwen2, Qwen2.5, & QwQ liger_kernel.transformers.apply_liger_kernel_to_qwen2 RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Qwen2-VL, & QVQ liger_kernel.transformers.apply_liger_kernel_to_qwen2_vl RMSNorm, LayerNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Qwen2.5-VL liger_kernel.transformers.apply_liger_kernel_to_qwen2_5_vl RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Qwen3 liger_kernel.transformers.apply_liger_kernel_to_qwen3 RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Qwen3 MoE liger_kernel.transformers.apply_liger_kernel_to_qwen3_moe RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Qwen3.5 liger_kernel.transformers.apply_liger_kernel_to_qwen3_5 RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Phi3 & Phi3.5 liger_kernel.transformers.apply_liger_kernel_to_phi3 RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Granite 3.0 & 3.1 liger_kernel.transformers.apply_liger_kernel_to_granite RoPE, RMSNorm, SwiGLU, CrossEntropyLoss
OLMo2 liger_kernel.transformers.apply_liger_kernel_to_olmo2 RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Olmo3 liger_kernel.transformers.apply_liger_kernel_to_olmo3 RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
GLM-4 liger_kernel.transformers.apply_liger_kernel_to_glm4 RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
GPT-OSS liger_kernel.transformers.apply_liger_kernel_to_gpt_oss RoPE, RMSNorm, CrossEntropyLoss, FusedLinearCrossEntropy
InternVL3 liger_kernel.transformers.apply_liger_kernel_to_internvl RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
HunyuanV1 liger_kernel.transformers.apply_liger_kernel_to_hunyuan_v1_dense RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
HunyuanV1 MoE liger_kernel.transformers.apply_liger_kernel_to_hunyuan_v1_moe RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy

Low-level APIs

  • Fused Linear kernels combine linear layers with losses, reducing memory usage by up to 80% - ideal for HBM-constrained workloads.
  • Other kernels use fusion and in-place techniques for memory and performance optimization.

Model Kernels

Kernel API
RMSNorm liger_kernel.transformers.LigerRMSNorm
LayerNorm liger_kernel.transformers.LigerLayerNorm
RoPE liger_kernel.transformers.liger_rotary_pos_emb
SwiGLU liger_kernel.transformers.LigerSwiGLUMLP
GeGLU liger_kernel.transformers.LigerGEGLUMLP
CrossEntropy liger_kernel.transformers.LigerCrossEntropyLoss
Fused Linear CrossEntropy liger_kernel.transformers.LigerFusedLinearCrossEntropyLoss
Multi Token Attention liger_kernel.transformers.LigerMultiTokenAttention
Softmax liger_kernel.transformers.LigerSoftmax
Sparsemax liger_kernel.transformers.LigerSparsemax
mHC (Hyper-Connections) liger_kernel.transformers.LigerMHC

Alignment Kernels

Kernel API
Fused Linear CPO Loss liger_kernel.chunked_loss.LigerFusedLinearCPOLoss
Fused Linear DPO Loss liger_kernel.chunked_loss.LigerFusedLinearDPOLoss
Fused Linear ORPO Loss liger_kernel.chunked_loss.LigerFusedLinearORPOLoss
Fused Linear SimPO Loss liger_kernel.chunked_loss.LigerFusedLinearSimPOLoss
Fused Linear KTO Loss liger_kernel.chunked_loss.LigerFusedLinearKTOLoss

Distillation Kernels

Kernel API
KLDivergence liger_kernel.transformers.LigerKLDIVLoss
JSD liger_kernel.transformers.LigerJSD
Fused Linear JSD liger_kernel.transformers.LigerFusedLinearJSD
TVD liger_kernel.transformers.LigerTVDLoss

Experimental Kernels

Kernel API
Embedding liger_kernel.transformers.experimental.LigerEmbedding
Matmul int2xint8 liger_kernel.transformers.experimental.matmul

Contributing, Acknowledgements, and License

Sponsorship and Collaboration

  • Glows.ai: Sponsoring NVIDIA GPUs for our open source developers.
  • AMD: Providing AMD GPUs for our AMD CI.
  • Intel: Providing Intel GPUs for our Intel CI.
  • Modal: Free 3000 credits from GPU MODE IRL for our NVIDIA CI.
  • EmbeddedLLM: Making Liger Kernel run fast and stable on AMD.
  • HuggingFace: Integrating Liger Kernel into Hugging Face Transformers and TRL.
  • Lightning AI: Integrating Liger Kernel into Lightning Thunder.
  • Axolotl: Integrating Liger Kernel into Axolotl.
  • Llama-Factory: Integrating Liger Kernel into Llama-Factory.

CI status

Build

Contact

Cite this work

Biblatex entry:

@inproceedings{
hsu2025ligerkernel,
title={Liger-Kernel: Efficient Triton Kernels for {LLM} Training},
author={Pin-Lun Hsu and Yun Dai and Vignesh Kothapalli and Qingquan Song and Shao Tang and Siyu Zhu and Steven Shimizu and Shivam Sahni and Haowen Ning and Yanning Chen and Zhipeng Wang},
booktitle={Championing Open-source DEvelopment in ML Workshop @ ICML25},
year={2025},
url={https://openreview.net/forum?id=36SjAIT42G}
}

Star History

Star History Chart

↑ Back to Top ↑

Languages
Python 62.4%
Cuda 31.7%
NASL 3.9%
C++ 1.3%
CMake 0.6%
Other 0.1%