Home

Awesome

Liger Kernel: Efficient Triton Kernels for LLM Training

<table style="width: 100%; text-align: center; border-collapse: collapse;"> <tr> <th style="padding: 10px;" colspan="2">Stable</th> <th style="padding: 10px;" colspan="2">Nightly</th> <th style="padding: 10px;">Discord</th> </tr> <tr> <td style="padding: 10px;"> <a href="https://pepy.tech/project/liger-kernel"> <img src="https://static.pepy.tech/badge/liger-kernel" alt="Downloads (Stable)"> </a> </td> <td style="padding: 10px;"> <a href="https://pypi.org/project/liger-kernel"> <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel?color=green"> </a> </td> <td style="padding: 10px;"> <a href="https://pepy.tech/project/liger-kernel-nightly"> <img src="https://static.pepy.tech/badge/liger-kernel-nightly" alt="Downloads (Nightly)"> </a> </td> <td style="padding: 10px;"> <a href="https://pypi.org/project/liger-kernel-nightly"> <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel-nightly?color=green"> </a> </td> <td style="padding: 10px;"> <a href="https://discord.gg/CX2YmNmn"> <img src="https://dcbadge.vercel.app/api/server/cudamode?style=flat" alt="Join Our Discord"> </a> </td> </tr> </table> <img src="https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/logo-banner.png">

Installation | Getting Started | Examples | APIs | Structure | Contributing | Acknowledgement

<details> <summary>Latest News 🔥</summary> </details>

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.

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 UpMemory Reduction
Speed upMemory

Note:

Examples

Basic

ExampleDescriptionLightning Studio
Hugging Face TrainerTrain LLaMA 3-8B ~20% faster with over 40% memory reduction on Alpaca dataset using 4 A100s with FSDPTBA
Lightning TrainerIncrease 15% throughput and reduce memory usage by 40% with LLaMA3-8B on MMLU dataset using 8 A100s with DeepSpeed ZeRO3TBA

Advanced

ExampleDescriptionLightning Studio
Medusa Multi-head LLM (Retraining Phase)Reduce memory usage by 80% with 5 LM heads and improve throughput by 40% using 8 A100s with FSDPTBA

Key Features

Target Audiences

Installation

Dependencies

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
pip install -e .

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()

Structure

Source Code

Tests

Benchmark

APIs

AutoModel

AutoModel VariantAPI
AutoModelForCausalLMliger_kernel.transformers.AutoLigerKernelForCausalLM

Patching

ModelAPISupported Operations
LLaMA 2 & 3liger_kernel.transformers.apply_liger_kernel_to_llamaRoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Mistralliger_kernel.transformers.apply_liger_kernel_to_mistralRoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Mixtralliger_kernel.transformers.apply_liger_kernel_to_mixtralRoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Gemma1liger_kernel.transformers.apply_liger_kernel_to_gemmaRoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Gemma2liger_kernel.transformers.apply_liger_kernel_to_gemma2RoPE, RMSNorm, GeGLU, CrossEntropyLoss
Qwen2liger_kernel.transformers.apply_liger_kernel_to_qwen2RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Qwen2-VLliger_kernel.transformers.apply_liger_kernel_to_qwen2_vlRMSNorm, LayerNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy
Phi3liger_kernel.transformers.apply_liger_kernel_to_phi3RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy

Kernels

KernelAPI
RMSNormliger_kernel.transformers.LigerRMSNorm
LayerNormliger_kernel.transformers.LigerLayerNorm
RoPEliger_kernel.transformers.liger_rotary_pos_emb
SwiGLUliger_kernel.transformers.LigerSwiGLUMLP
GeGLUliger_kernel.transformers.LigerGEGLUMLP
CrossEntropyliger_kernel.transformers.LigerCrossEntropyLoss
FusedLinearCrossEntropyliger_kernel.transformers.LigerFusedLinearCrossEntropyLoss
KLDivergenceliger_kernel.transformers.LigerKLDIVLoss
<!-- TODO: verify vocab sizes are accurate -->

Experimental Kernels

KernelAPI
Embeddingliger_kernel.transformers.experimental.LigerEmbedding
<!-- TODO: be more specific about batch size -->

Note: Reported speedups and memory reductions are with respect to the LLaMA 3-8B Hugging Face layer implementations. All models use 4K hidden size and 4K sequence length and are evaluated based on memory usage and wall time for the forward+backward pass on a single NVIDIA A100 80G GPU using small batch sizes. Liger kernels exhibit more efficient scaling to larger batch sizes, detailed further in the Benchmark folder.

Note on ML Compiler

Torch Compile

Since Liger Kernel is 100% Triton-based, it works seamlessly with torch.compile. In the following example, Liger Kernel can further optimize the model on top of Torch Compile, reducing the memory by more than half.

ConfigurationThroughput (tokens/sec)Memory Reserved (GB)
Torch Compile378066.4
Torch Compile + Liger Kernel370231.0

Note:

  1. Benchmark conditions: LLaMA 3-8B, Batch Size = 8, Seq Len = 4096, Data Type = bf16, Optimizer = AdamW, Gradient Checkpointing = True, Distributed Strategy = FSDP1 on 8 A100s.
  2. Tested on torch 2.5.0.dev20240731+cu118

Contributing

CONTRIBUTING GUIDE

Acknowledgement

Design

Code

We referenced or used the following projects:

#ProjectDescriptionLocationLicense
1Unslothcalculate_settings to determine block size and warp; We reuse it for Norm and MLPLiger Kernel UtilsApache
2UnslothWe modified and added dW calculation on top of Unsloth implementationLiger Kernel RMS NormApache
3Triton tutorialWe modified on top of triton tutorialsLiger Kernel RMS NormMIT
4tiny shakespeare datasetWe use tiny shakespeare dataset to conduct convergence test on mini modelLiger Kernel ConvergenceN/A
5Efficient Cross EntropyWe use the idea of gradient-in-forward and chunkingLiger Kernel Linear Cross EntropyMIT
6Flash attnWe take many optimization ideas from the work, such as tiling and recomputationBSD
7AutoAWQWe reference the design of automodelLiger Kernel Auto ModelMIT
8llm.cWe reference the design of end-to-end testingLiger Kernel Convergence TestsMIT

Many thanks to the contributors to these projects for their invaluable work that helped make Liger possible.

License

BSD 2-CLAUSE

Contact

Cite this work

Biblatex entry:

@software{liger2024,
  title  = {Liger-Kernel: Efficient Triton Kernels for LLM Training},
  author = {Hsu, Pin-Lun and Dai, Yun and Kothapalli, Vignesh and Song, Qingquan and Tang, Shao and Zhu, Siyu},
  url    = {https://github.com/linkedin/Liger-Kernel},
  year   = {2024}
}

Star History

Star History Chart