liger-kernel 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. liger_kernel-0.2.0/PKG-INFO +298 -0
  2. liger_kernel-0.2.0/README.md +275 -0
  3. liger_kernel-0.2.0/setup.py +45 -0
  4. liger_kernel-0.2.0/src/liger_kernel/env_report.py +46 -0
  5. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/ops/cross_entropy.py +5 -5
  6. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/ops/fused_linear_cross_entropy.py +50 -21
  7. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/ops/geglu.py +6 -1
  8. liger_kernel-0.2.0/src/liger_kernel/ops/rms_norm.py +307 -0
  9. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/ops/rope.py +3 -3
  10. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/__init__.py +6 -0
  11. liger_kernel-0.2.0/src/liger_kernel/transformers/auto_model.py +33 -0
  12. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/fused_linear_cross_entropy.py +2 -2
  13. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/geglu.py +4 -2
  14. liger_kernel-0.2.0/src/liger_kernel/transformers/model/gemma.py +138 -0
  15. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/model/llama.py +1 -1
  16. liger_kernel-0.2.0/src/liger_kernel/transformers/model/mistral.py +138 -0
  17. liger_kernel-0.2.0/src/liger_kernel/transformers/model/phi3.py +136 -0
  18. liger_kernel-0.2.0/src/liger_kernel/transformers/model/qwen2.py +135 -0
  19. liger_kernel-0.2.0/src/liger_kernel/transformers/monkey_patch.py +323 -0
  20. liger_kernel-0.2.0/src/liger_kernel/transformers/rms_norm.py +32 -0
  21. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/swiglu.py +24 -0
  22. liger_kernel-0.2.0/src/liger_kernel/transformers/trainer_integration.py +2 -0
  23. liger_kernel-0.2.0/src/liger_kernel.egg-info/PKG-INFO +298 -0
  24. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel.egg-info/SOURCES.txt +6 -0
  25. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel.egg-info/requires.txt +3 -3
  26. liger_kernel-0.1.0/PKG-INFO +0 -6
  27. liger_kernel-0.1.0/README.md +0 -205
  28. liger_kernel-0.1.0/setup.py +0 -26
  29. liger_kernel-0.1.0/src/liger_kernel/ops/rms_norm.py +0 -185
  30. liger_kernel-0.1.0/src/liger_kernel/transformers/monkey_patch.py +0 -130
  31. liger_kernel-0.1.0/src/liger_kernel/transformers/rms_norm.py +0 -16
  32. liger_kernel-0.1.0/src/liger_kernel/transformers/trainer_integration.py +0 -45
  33. liger_kernel-0.1.0/src/liger_kernel.egg-info/PKG-INFO +0 -6
  34. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/LICENSE +0 -0
  35. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/NOTICE +0 -0
  36. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/setup.cfg +0 -0
  37. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/ops/__init__.py +0 -0
  38. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/ops/swiglu.py +0 -0
  39. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/ops/utils.py +0 -0
  40. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/cross_entropy.py +0 -0
  41. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/model/__init__.py +0 -0
  42. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/transformers/rope.py +0 -0
  43. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/triton/__init__.py +0 -0
  44. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel/triton/monkey_patch.py +0 -0
  45. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel.egg-info/dependency_links.txt +0 -0
  46. {liger_kernel-0.1.0 → liger_kernel-0.2.0}/src/liger_kernel.egg-info/top_level.txt +0 -0
@@ -0,0 +1,298 @@
1
+ Metadata-Version: 2.1
2
+ Name: liger_kernel
3
+ Version: 0.2.0
4
+ Summary: Efficient Triton kernels for LLM Training
5
+ Home-page: https://github.com/linkedin/Liger-Kernel
6
+ License: BSD-2-Clause
7
+ Keywords: triton,kernels,LLM training,deep learning,Hugging Face,PyTorch,GPU optimization
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: License :: OSI Approved :: BSD License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Topic :: Software Development :: Libraries
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Description-Content-Type: text/markdown
20
+ Provides-Extra: dev
21
+ License-File: LICENSE
22
+ License-File: NOTICE
23
+
24
+ # Liger Kernel: Efficient Triton Kernels for LLM Training
25
+
26
+
27
+
28
+ [![Downloads](https://static.pepy.tech/badge/liger-kernel)](https://pepy.tech/project/liger-kernel) [![PyPI version](https://badge.fury.io/py/liger-kernel.svg)](https://badge.fury.io/py/liger-kernel) [![PyPI version](https://badge.fury.io/py/liger-kernel-nightly.svg)](https://badge.fury.io/py/liger-kernel-nightly)
29
+ [![](https://dcbadge.vercel.app/api/server/cudamode?style=flat)](https://discord.gg/CX2YmNmn)
30
+
31
+ <img src="https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/logo-banner.png">
32
+
33
+ [Installation](#installation) | [Getting Started](#getting-started) | [Examples](#examples) | [APIs](#apis) | [Structure](#structure) | [Contributing](#contributing)
34
+
35
+ <details>
36
+ <summary>Latest News 🔥</summary>
37
+
38
+ - [2024/8/31] CUDA MODE talk, [Liger-Kernel: Real-world Triton kernel for LLM Training](https://discord.gg/6CNeDAjq?event=1273323969788772455)
39
+ - [2024/8/23] Official release: check out our [X post](https://x.com/hsu_byron/status/1827072737673982056)
40
+
41
+ </details>
42
+
43
+
44
+ **Liger (Linkedin GPU Efficient Runtime) 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](https://github.com/Dao-AILab/flash-attention), [PyTorch FSDP](https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html), and [Microsoft DeepSpeed](https://github.com/microsoft/DeepSpeed). We welcome contributions from the community to gather the best kernels for LLM training.
45
+
46
+ ## Supercharge Your Model with Liger Kernel
47
+
48
+
49
+ ![Banner](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/banner.GIF)
50
+
51
+ 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.
52
+
53
+
54
+ | Speed Up | Memory Reduction |
55
+ |--------------------------|-------------------------|
56
+ | ![Speed up](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/e2e-tps.png) | ![Memory](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/e2e-memory.png) |
57
+
58
+ > **Note:**
59
+ > - Benchmark conditions: LLaMA 3-8B, Batch Size = 8, Data Type = `bf16`, Optimizer = AdamW, Gradient Checkpointing = True, Distributed Strategy = FSDP1 on 8 A100s.
60
+ > - Hugging Face models start to OOM at a 4K context length, whereas Hugging Face + Liger Kernel scales up to 16K.
61
+
62
+ ## Examples
63
+
64
+ ### Basic
65
+
66
+ | **Example** | **Description** | **Lightning Studio** |
67
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
68
+ | [**Hugging Face Trainer**](https://github.com/linkedin/Liger-Kernel/tree/main/examples/huggingface) | Train LLaMA 3-8B ~20% faster with over 40% memory reduction on Alpaca dataset using 4 A100s with FSDP | TBA |
69
+ | [**Lightning Trainer**](https://github.com/linkedin/Liger-Kernel/tree/main/examples/lightning) | Increase 15% throughput and reduce memory usage by 40% with LLaMA3-8B on MMLU dataset using 8 A100s with DeepSpeed ZeRO3 | TBA |
70
+
71
+ ### Advanced
72
+
73
+ | **Example** | **Description** | **Lightning Studio** |
74
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
75
+ | [**Medusa Multi-head LLM (Retraining Phase)**](https://github.com/linkedin/Liger-Kernel/tree/main/examples/medusa) | Reduce memory usage by 80% with 5 LM heads and improve throughput by 40% using 8 A100s with FSDP | TBA |
76
+
77
+ ## Key Features
78
+
79
+ - **Ease of use:** Simply patch your Hugging Face model with one line of code, or compose your own model using our Liger Kernel modules.
80
+ - **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.
81
+ - **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.
82
+ - **Lightweight:** Liger Kernel has minimal dependencies, requiring only Torch and Triton—no extra libraries needed! Say goodbye to dependency headaches!
83
+ - **Multi-GPU supported:** Compatible with multi-GPU setups (PyTorch FSDP, DeepSpeed, DDP, etc.).
84
+
85
+ ## Target Audiences
86
+
87
+ - **Researchers**: Looking to compose models using efficient and reliable kernels for frontier experiments.
88
+ - **ML Practitioners**: Focused on maximizing GPU training efficiency with optimal, high-performance kernels.
89
+ - **Curious Novices**: Eager to learn how to write reliable Triton kernels to enhance training efficiency.
90
+
91
+
92
+ ## Installation
93
+
94
+ ### Dependencies
95
+
96
+ - `torch >= 2.1.2`
97
+ - `triton >= 2.3.0`
98
+ - `transformers >= 4.42.0`
99
+
100
+ > **Note:**
101
+ > Our kernels inherit the full spectrum of hardware compatibility offered by [Triton](https://github.com/triton-lang/triton).
102
+
103
+ To install the stable version:
104
+
105
+ ```bash
106
+ $ pip install liger-kernel
107
+ ```
108
+
109
+ To install the nightly version:
110
+
111
+ ```bash
112
+ $ pip install liger-kernel-nightly
113
+ ```
114
+
115
+ To install from source:
116
+
117
+ ```bash
118
+ git clone https://github.com/linkedin/Liger-Kernel.git
119
+ cd Liger-Kernel
120
+ pip install -e .
121
+ ```
122
+ ## Getting Started
123
+
124
+ There are a couple ways to apply Liger kernels, depending on the level of customization required.
125
+
126
+ ### 1. Use AutoLigerKernelForCausalLM
127
+
128
+ 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.
129
+
130
+ ```python
131
+ from liger_kernel.transformers import AutoLigerKernelForCausalLM
132
+
133
+ # This AutoModel wrapper class automatically monkey-patches the
134
+ # model with the optimized Liger kernels if the model is supported.
135
+ model = AutoLigerKernelForCausalLM.from_pretrained("path/to/some/model")
136
+ ```
137
+
138
+ ### 2. Apply Model-Specific Patching APIs
139
+
140
+ Using the [patching APIs](#patching), you can swap Hugging Face models with optimized Liger Kernels.
141
+
142
+ ```python
143
+ import transformers
144
+ from liger_kernel.transformers import apply_liger_kernel_to_llama
145
+
146
+ model = transformers.AutoModelForCausalLM("path/to/llama/model")
147
+
148
+ # Adding this line automatically monkey-patches the model with the optimized Liger kernels
149
+ apply_liger_kernel_to_llama()
150
+
151
+ # You could alternatively specify exactly which kernels are applied
152
+ apply_liger_kernel_to_llama(
153
+ rope=True,
154
+ swiglu=True,
155
+ cross_entropy=True,
156
+ fused_linear_cross_entropy=False,
157
+ rms_norm=False
158
+ )
159
+ ```
160
+
161
+ ### 3. Compose Your Own Model
162
+
163
+ You can take individual [kernels](#kernels) to compose your models.
164
+
165
+ ```python
166
+ from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
167
+ import torch.nn as nn
168
+ import torch
169
+
170
+ model = nn.Linear(128, 256).cuda()
171
+
172
+ # fuses linear + cross entropy layers together and performs chunk-by-chunk computation to reduce memory
173
+ loss_fn = LigerFusedLinearCrossEntropyLoss()
174
+
175
+ input = torch.randn(4, 128, requires_grad=True, device="cuda")
176
+ target = torch.randint(256, (4, ), device="cuda")
177
+
178
+ loss = loss_fn(model.weight, input, target)
179
+ loss.backward()
180
+ ```
181
+
182
+
183
+ ## Structure
184
+
185
+ ### Source Code
186
+
187
+ - `ops/`: Core Triton operations.
188
+ - `transformers/`: PyTorch `nn.Module` implementations built on Triton operations, compliant with the `transformers` API.
189
+
190
+ ### Tests
191
+
192
+ - `transformers/`: Correctness tests for the Triton-based layers.
193
+ - `convergence/`: Patches Hugging Face models with all kernels, runs multiple iterations, and compares weights, logits, and loss layer-by-layer.
194
+
195
+ ### Benchmark
196
+
197
+ - `benchmark/`: Execution time and memory benchmarks compared to Hugging Face layers.
198
+
199
+ ## APIs
200
+
201
+ ### AutoModel
202
+
203
+ | **AutoModel Variant** | **API** |
204
+ |-----------|---------|
205
+ | AutoModelForCausalLM | `liger_kernel.transformers.AutoLigerKernelForCausalLM` |
206
+
207
+
208
+ ### Patching
209
+
210
+ | **Model** | **API** | **Supported Operations** |
211
+ |-------------|--------------------------------------------------------------|-------------------------------------------------------------------------|
212
+ | LLaMA 2 & 3 | `liger_kernel.transformers.apply_liger_kernel_to_llama` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
213
+ | Mistral | `liger_kernel.transformers.apply_liger_kernel_to_mistral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
214
+ | Mixtral | `liger_kernel.transformers.apply_liger_kernel_to_mixtral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss |
215
+ | Gemma1 | `liger_kernel.transformers.apply_liger_kernel_to_gemma` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
216
+ | Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss |
217
+ | Qwen2 | `liger_kernel.transformers.apply_liger_kernel_to_qwen2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
218
+ | Phi3 | `liger_kernel.transformers.apply_liger_kernel_to_phi3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
219
+
220
+
221
+
222
+ ### Kernels
223
+
224
+ | **Kernel** | **API** |
225
+ |---------------------------------|-------------------------------------------------------------|
226
+ | RMSNorm | `liger_kernel.transformers.LigerRMSNorm` |
227
+ | RoPE | `liger_kernel.transformers.liger_rotary_pos_emb` |
228
+ | SwiGLU | `liger_kernel.transformers.LigerSwiGLUMLP` |
229
+ | GeGLU | `liger_kernel.transformers.LigerGEGLUMLP` |
230
+ | CrossEntropy | `liger_kernel.transformers.LigerCrossEntropyLoss` |
231
+ | FusedLinearCrossEntropy | `liger_kernel.transformers.LigerFusedLinearCrossEntropyLoss`|
232
+
233
+ - **RMSNorm**: [RMSNorm](https://arxiv.org/pdf/1910.07467), which normalizes activations using their root mean square, is implemented by fusing the normalization and scaling steps into a single Triton kernel, and achieves ~3X speedup with ~3X peak memory reduction.
234
+ - **RoPE**: [Rotary Positional Embedding](https://arxiv.org/pdf/2104.09864) is implemented by fusing the query and key embedding rotary into a single kernel with inplace replacement, and achieves ~3X speedup with ~3X peak memory reduction.
235
+ - **SwiGLU**: [Swish Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
236
+ $$\text{SwiGLU}(x)=\text{Swish}_{\beta}(xW+b)\otimes(xV+c)$$
237
+ , is implemented by fusing the elementwise multiplication (denoted by $\otimes$) into a single kernel with inplace replacement, and achieves parity speed with ~1.5X peak memory reduction.
238
+ - **GeGLU**: [GELU Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
239
+ $$\text{GeGLU}(x)=\text{GELU}(xW+b)\otimes(xV+c)$$
240
+ , is implemented by fusing the elementwise multiplication into a single kernel with inplace replacement, and achieves parity speed with ~1.5X peak memory reduction. Note that the [tanh approximation form of GELU](https://pytorch.org/docs/stable/generated/torch.nn.GELU.html) is used.
241
+ - **CrossEntropy**: [Cross entropy loss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) is implemented by computing both the loss and gradient in the forward pass with inplace replacement of input to reduce the peak memory by avoiding simultaneous materialization of both input logits and gradient. It achieves >2X speedup and >4X memory reduction for common vocab sizes (e.g., 32K, 128K, etc.).
242
+ <!-- TODO: verify vocab sizes are accurate -->
243
+ - **FusedLinearCrossEntropy**: Peak memory usage of cross entropy loss is further improved by fusing the model head with the CE loss and chunking the input for block-wise loss and gradient calculation, a technique inspired by [Efficient Cross Entropy](https://github.com/mgmalek/efficient_cross_entropy). It achieves >4X memory reduction for 128k vocab size. **This is highly effective for large batch size, large sequence length, and large vocabulary sizes.** Please refer to the [Medusa example](https://github.com/linkedin/Liger-Kernel/tree/main/examples/medusa) for individual kernel usage.
244
+
245
+
246
+ <!-- TODO: be more specific about batch size -->
247
+ > **Note:**
248
+ > 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](./benchmark) folder.
249
+
250
+ ## Note on ML Compiler
251
+
252
+ ### Torch Compile
253
+
254
+ Since Liger Kernel is 100% Triton-based, it works seamlessly with [`torch.compile`](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html). In the following example, Liger Kernel can further optimize the model on top of Torch Compile, reducing the memory by more than half.
255
+
256
+ | Configuration | Throughput (tokens/sec) | Memory Reserved (GB) |
257
+ |--------------------------------|----------------------------|-------------------------|
258
+ | Torch Compile | 3780 | 66.4 |
259
+ | Torch Compile + Liger Kernel | 3702 | 31.0 |
260
+
261
+ > **Note:**
262
+ > 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.
263
+ > 2. Tested on torch `2.5.0.dev20240731+cu118`
264
+
265
+ ## Contributing
266
+
267
+ [CONTRIBUTING GUIDE](https://github.com/linkedin/Liger-Kernel/blob/main/CONTRIBUTING.md)
268
+
269
+ ## Acknowledgement
270
+
271
+ - [@claire_yishan](https://twitter.com/claire_yishan) for the LOGO design
272
+ - [flash-attn](https://github.com/Dao-AILab/flash-attention) and [Unsloth](https://github.com/unslothai/unsloth) for inspiration in Triton kernels for training
273
+ - [tiny shakespeare dataset](https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt) by Andrej Karpathy for convergence testing
274
+ - [Efficient Cross Entropy](https://github.com/mgmalek/efficient_cross_entropy) for lm_head + cross entropy inspiration
275
+
276
+
277
+ ## License
278
+
279
+ [BSD 2-CLAUSE](https://github.com/linkedin/Liger-Kernel/blob/main/LICENSE)
280
+
281
+ ## Contact
282
+
283
+ - For collaboration, please send email to byhsu@linkedin.com
284
+
285
+ ## Cite this work
286
+
287
+ Biblatex entry:
288
+ ```bib
289
+ @software{liger2024,
290
+ title = {Liger-Kernel: Efficient Triton Kernels for LLM Training},
291
+ author = {Hsu, Pin-Lun and Dai, Yun and Kothapalli, Vignesh and Song, Qingquan and Tang, Shao and Zhu, Siyu},
292
+ url = {https://github.com/linkedin/Liger-Kernel},
293
+ year = {2024}
294
+ }
295
+ ```
296
+
297
+ ## Star History
298
+ [![Star History Chart](https://api.star-history.com/svg?repos=linkedin/Liger-Kernel&type=Date)](https://star-history.com/#linkedin/Liger-Kernel&Date)
@@ -0,0 +1,275 @@
1
+ # Liger Kernel: Efficient Triton Kernels for LLM Training
2
+
3
+
4
+
5
+ [![Downloads](https://static.pepy.tech/badge/liger-kernel)](https://pepy.tech/project/liger-kernel) [![PyPI version](https://badge.fury.io/py/liger-kernel.svg)](https://badge.fury.io/py/liger-kernel) [![PyPI version](https://badge.fury.io/py/liger-kernel-nightly.svg)](https://badge.fury.io/py/liger-kernel-nightly)
6
+ [![](https://dcbadge.vercel.app/api/server/cudamode?style=flat)](https://discord.gg/CX2YmNmn)
7
+
8
+ <img src="https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/logo-banner.png">
9
+
10
+ [Installation](#installation) | [Getting Started](#getting-started) | [Examples](#examples) | [APIs](#apis) | [Structure](#structure) | [Contributing](#contributing)
11
+
12
+ <details>
13
+ <summary>Latest News 🔥</summary>
14
+
15
+ - [2024/8/31] CUDA MODE talk, [Liger-Kernel: Real-world Triton kernel for LLM Training](https://discord.gg/6CNeDAjq?event=1273323969788772455)
16
+ - [2024/8/23] Official release: check out our [X post](https://x.com/hsu_byron/status/1827072737673982056)
17
+
18
+ </details>
19
+
20
+
21
+ **Liger (Linkedin GPU Efficient Runtime) 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](https://github.com/Dao-AILab/flash-attention), [PyTorch FSDP](https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html), and [Microsoft DeepSpeed](https://github.com/microsoft/DeepSpeed). We welcome contributions from the community to gather the best kernels for LLM training.
22
+
23
+ ## Supercharge Your Model with Liger Kernel
24
+
25
+
26
+ ![Banner](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/banner.GIF)
27
+
28
+ 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.
29
+
30
+
31
+ | Speed Up | Memory Reduction |
32
+ |--------------------------|-------------------------|
33
+ | ![Speed up](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/e2e-tps.png) | ![Memory](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/e2e-memory.png) |
34
+
35
+ > **Note:**
36
+ > - Benchmark conditions: LLaMA 3-8B, Batch Size = 8, Data Type = `bf16`, Optimizer = AdamW, Gradient Checkpointing = True, Distributed Strategy = FSDP1 on 8 A100s.
37
+ > - Hugging Face models start to OOM at a 4K context length, whereas Hugging Face + Liger Kernel scales up to 16K.
38
+
39
+ ## Examples
40
+
41
+ ### Basic
42
+
43
+ | **Example** | **Description** | **Lightning Studio** |
44
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
45
+ | [**Hugging Face Trainer**](https://github.com/linkedin/Liger-Kernel/tree/main/examples/huggingface) | Train LLaMA 3-8B ~20% faster with over 40% memory reduction on Alpaca dataset using 4 A100s with FSDP | TBA |
46
+ | [**Lightning Trainer**](https://github.com/linkedin/Liger-Kernel/tree/main/examples/lightning) | Increase 15% throughput and reduce memory usage by 40% with LLaMA3-8B on MMLU dataset using 8 A100s with DeepSpeed ZeRO3 | TBA |
47
+
48
+ ### Advanced
49
+
50
+ | **Example** | **Description** | **Lightning Studio** |
51
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
52
+ | [**Medusa Multi-head LLM (Retraining Phase)**](https://github.com/linkedin/Liger-Kernel/tree/main/examples/medusa) | Reduce memory usage by 80% with 5 LM heads and improve throughput by 40% using 8 A100s with FSDP | TBA |
53
+
54
+ ## Key Features
55
+
56
+ - **Ease of use:** Simply patch your Hugging Face model with one line of code, or compose your own model using our Liger Kernel modules.
57
+ - **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.
58
+ - **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.
59
+ - **Lightweight:** Liger Kernel has minimal dependencies, requiring only Torch and Triton—no extra libraries needed! Say goodbye to dependency headaches!
60
+ - **Multi-GPU supported:** Compatible with multi-GPU setups (PyTorch FSDP, DeepSpeed, DDP, etc.).
61
+
62
+ ## Target Audiences
63
+
64
+ - **Researchers**: Looking to compose models using efficient and reliable kernels for frontier experiments.
65
+ - **ML Practitioners**: Focused on maximizing GPU training efficiency with optimal, high-performance kernels.
66
+ - **Curious Novices**: Eager to learn how to write reliable Triton kernels to enhance training efficiency.
67
+
68
+
69
+ ## Installation
70
+
71
+ ### Dependencies
72
+
73
+ - `torch >= 2.1.2`
74
+ - `triton >= 2.3.0`
75
+ - `transformers >= 4.42.0`
76
+
77
+ > **Note:**
78
+ > Our kernels inherit the full spectrum of hardware compatibility offered by [Triton](https://github.com/triton-lang/triton).
79
+
80
+ To install the stable version:
81
+
82
+ ```bash
83
+ $ pip install liger-kernel
84
+ ```
85
+
86
+ To install the nightly version:
87
+
88
+ ```bash
89
+ $ pip install liger-kernel-nightly
90
+ ```
91
+
92
+ To install from source:
93
+
94
+ ```bash
95
+ git clone https://github.com/linkedin/Liger-Kernel.git
96
+ cd Liger-Kernel
97
+ pip install -e .
98
+ ```
99
+ ## Getting Started
100
+
101
+ There are a couple ways to apply Liger kernels, depending on the level of customization required.
102
+
103
+ ### 1. Use AutoLigerKernelForCausalLM
104
+
105
+ 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.
106
+
107
+ ```python
108
+ from liger_kernel.transformers import AutoLigerKernelForCausalLM
109
+
110
+ # This AutoModel wrapper class automatically monkey-patches the
111
+ # model with the optimized Liger kernels if the model is supported.
112
+ model = AutoLigerKernelForCausalLM.from_pretrained("path/to/some/model")
113
+ ```
114
+
115
+ ### 2. Apply Model-Specific Patching APIs
116
+
117
+ Using the [patching APIs](#patching), you can swap Hugging Face models with optimized Liger Kernels.
118
+
119
+ ```python
120
+ import transformers
121
+ from liger_kernel.transformers import apply_liger_kernel_to_llama
122
+
123
+ model = transformers.AutoModelForCausalLM("path/to/llama/model")
124
+
125
+ # Adding this line automatically monkey-patches the model with the optimized Liger kernels
126
+ apply_liger_kernel_to_llama()
127
+
128
+ # You could alternatively specify exactly which kernels are applied
129
+ apply_liger_kernel_to_llama(
130
+ rope=True,
131
+ swiglu=True,
132
+ cross_entropy=True,
133
+ fused_linear_cross_entropy=False,
134
+ rms_norm=False
135
+ )
136
+ ```
137
+
138
+ ### 3. Compose Your Own Model
139
+
140
+ You can take individual [kernels](#kernels) to compose your models.
141
+
142
+ ```python
143
+ from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
144
+ import torch.nn as nn
145
+ import torch
146
+
147
+ model = nn.Linear(128, 256).cuda()
148
+
149
+ # fuses linear + cross entropy layers together and performs chunk-by-chunk computation to reduce memory
150
+ loss_fn = LigerFusedLinearCrossEntropyLoss()
151
+
152
+ input = torch.randn(4, 128, requires_grad=True, device="cuda")
153
+ target = torch.randint(256, (4, ), device="cuda")
154
+
155
+ loss = loss_fn(model.weight, input, target)
156
+ loss.backward()
157
+ ```
158
+
159
+
160
+ ## Structure
161
+
162
+ ### Source Code
163
+
164
+ - `ops/`: Core Triton operations.
165
+ - `transformers/`: PyTorch `nn.Module` implementations built on Triton operations, compliant with the `transformers` API.
166
+
167
+ ### Tests
168
+
169
+ - `transformers/`: Correctness tests for the Triton-based layers.
170
+ - `convergence/`: Patches Hugging Face models with all kernels, runs multiple iterations, and compares weights, logits, and loss layer-by-layer.
171
+
172
+ ### Benchmark
173
+
174
+ - `benchmark/`: Execution time and memory benchmarks compared to Hugging Face layers.
175
+
176
+ ## APIs
177
+
178
+ ### AutoModel
179
+
180
+ | **AutoModel Variant** | **API** |
181
+ |-----------|---------|
182
+ | AutoModelForCausalLM | `liger_kernel.transformers.AutoLigerKernelForCausalLM` |
183
+
184
+
185
+ ### Patching
186
+
187
+ | **Model** | **API** | **Supported Operations** |
188
+ |-------------|--------------------------------------------------------------|-------------------------------------------------------------------------|
189
+ | LLaMA 2 & 3 | `liger_kernel.transformers.apply_liger_kernel_to_llama` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
190
+ | Mistral | `liger_kernel.transformers.apply_liger_kernel_to_mistral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
191
+ | Mixtral | `liger_kernel.transformers.apply_liger_kernel_to_mixtral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss |
192
+ | Gemma1 | `liger_kernel.transformers.apply_liger_kernel_to_gemma` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
193
+ | Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss |
194
+ | Qwen2 | `liger_kernel.transformers.apply_liger_kernel_to_qwen2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
195
+ | Phi3 | `liger_kernel.transformers.apply_liger_kernel_to_phi3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
196
+
197
+
198
+
199
+ ### Kernels
200
+
201
+ | **Kernel** | **API** |
202
+ |---------------------------------|-------------------------------------------------------------|
203
+ | RMSNorm | `liger_kernel.transformers.LigerRMSNorm` |
204
+ | RoPE | `liger_kernel.transformers.liger_rotary_pos_emb` |
205
+ | SwiGLU | `liger_kernel.transformers.LigerSwiGLUMLP` |
206
+ | GeGLU | `liger_kernel.transformers.LigerGEGLUMLP` |
207
+ | CrossEntropy | `liger_kernel.transformers.LigerCrossEntropyLoss` |
208
+ | FusedLinearCrossEntropy | `liger_kernel.transformers.LigerFusedLinearCrossEntropyLoss`|
209
+
210
+ - **RMSNorm**: [RMSNorm](https://arxiv.org/pdf/1910.07467), which normalizes activations using their root mean square, is implemented by fusing the normalization and scaling steps into a single Triton kernel, and achieves ~3X speedup with ~3X peak memory reduction.
211
+ - **RoPE**: [Rotary Positional Embedding](https://arxiv.org/pdf/2104.09864) is implemented by fusing the query and key embedding rotary into a single kernel with inplace replacement, and achieves ~3X speedup with ~3X peak memory reduction.
212
+ - **SwiGLU**: [Swish Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
213
+ $$\text{SwiGLU}(x)=\text{Swish}_{\beta}(xW+b)\otimes(xV+c)$$
214
+ , is implemented by fusing the elementwise multiplication (denoted by $\otimes$) into a single kernel with inplace replacement, and achieves parity speed with ~1.5X peak memory reduction.
215
+ - **GeGLU**: [GELU Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
216
+ $$\text{GeGLU}(x)=\text{GELU}(xW+b)\otimes(xV+c)$$
217
+ , is implemented by fusing the elementwise multiplication into a single kernel with inplace replacement, and achieves parity speed with ~1.5X peak memory reduction. Note that the [tanh approximation form of GELU](https://pytorch.org/docs/stable/generated/torch.nn.GELU.html) is used.
218
+ - **CrossEntropy**: [Cross entropy loss](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) is implemented by computing both the loss and gradient in the forward pass with inplace replacement of input to reduce the peak memory by avoiding simultaneous materialization of both input logits and gradient. It achieves >2X speedup and >4X memory reduction for common vocab sizes (e.g., 32K, 128K, etc.).
219
+ <!-- TODO: verify vocab sizes are accurate -->
220
+ - **FusedLinearCrossEntropy**: Peak memory usage of cross entropy loss is further improved by fusing the model head with the CE loss and chunking the input for block-wise loss and gradient calculation, a technique inspired by [Efficient Cross Entropy](https://github.com/mgmalek/efficient_cross_entropy). It achieves >4X memory reduction for 128k vocab size. **This is highly effective for large batch size, large sequence length, and large vocabulary sizes.** Please refer to the [Medusa example](https://github.com/linkedin/Liger-Kernel/tree/main/examples/medusa) for individual kernel usage.
221
+
222
+
223
+ <!-- TODO: be more specific about batch size -->
224
+ > **Note:**
225
+ > 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](./benchmark) folder.
226
+
227
+ ## Note on ML Compiler
228
+
229
+ ### Torch Compile
230
+
231
+ Since Liger Kernel is 100% Triton-based, it works seamlessly with [`torch.compile`](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html). In the following example, Liger Kernel can further optimize the model on top of Torch Compile, reducing the memory by more than half.
232
+
233
+ | Configuration | Throughput (tokens/sec) | Memory Reserved (GB) |
234
+ |--------------------------------|----------------------------|-------------------------|
235
+ | Torch Compile | 3780 | 66.4 |
236
+ | Torch Compile + Liger Kernel | 3702 | 31.0 |
237
+
238
+ > **Note:**
239
+ > 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.
240
+ > 2. Tested on torch `2.5.0.dev20240731+cu118`
241
+
242
+ ## Contributing
243
+
244
+ [CONTRIBUTING GUIDE](https://github.com/linkedin/Liger-Kernel/blob/main/CONTRIBUTING.md)
245
+
246
+ ## Acknowledgement
247
+
248
+ - [@claire_yishan](https://twitter.com/claire_yishan) for the LOGO design
249
+ - [flash-attn](https://github.com/Dao-AILab/flash-attention) and [Unsloth](https://github.com/unslothai/unsloth) for inspiration in Triton kernels for training
250
+ - [tiny shakespeare dataset](https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt) by Andrej Karpathy for convergence testing
251
+ - [Efficient Cross Entropy](https://github.com/mgmalek/efficient_cross_entropy) for lm_head + cross entropy inspiration
252
+
253
+
254
+ ## License
255
+
256
+ [BSD 2-CLAUSE](https://github.com/linkedin/Liger-Kernel/blob/main/LICENSE)
257
+
258
+ ## Contact
259
+
260
+ - For collaboration, please send email to byhsu@linkedin.com
261
+
262
+ ## Cite this work
263
+
264
+ Biblatex entry:
265
+ ```bib
266
+ @software{liger2024,
267
+ title = {Liger-Kernel: Efficient Triton Kernels for LLM Training},
268
+ author = {Hsu, Pin-Lun and Dai, Yun and Kothapalli, Vignesh and Song, Qingquan and Tang, Shao and Zhu, Siyu},
269
+ url = {https://github.com/linkedin/Liger-Kernel},
270
+ year = {2024}
271
+ }
272
+ ```
273
+
274
+ ## Star History
275
+ [![Star History Chart](https://api.star-history.com/svg?repos=linkedin/Liger-Kernel&type=Date)](https://star-history.com/#linkedin/Liger-Kernel&Date)
@@ -0,0 +1,45 @@
1
+ from setuptools import find_namespace_packages, setup
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ setup(
6
+ name="liger_kernel",
7
+ version=__version__,
8
+ description="Efficient Triton kernels for LLM Training",
9
+ long_description=open("README.md").read(),
10
+ long_description_content_type="text/markdown",
11
+ license="BSD-2-Clause",
12
+ url="https://github.com/linkedin/Liger-Kernel",
13
+ package_dir={"": "src"},
14
+ packages=find_namespace_packages(where="src"),
15
+ classifiers=[
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Science/Research",
19
+ "Intended Audience :: Education",
20
+ "License :: OSI Approved :: BSD License",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.8",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Topic :: Software Development :: Libraries",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ ],
28
+ keywords="triton,kernels,LLM training,deep learning,Hugging Face,PyTorch,GPU optimization",
29
+ include_package_data=True,
30
+ install_requires=[
31
+ "torch>=2.1.2",
32
+ "triton>=2.3.0",
33
+ "transformers>=4.42.0",
34
+ ],
35
+ extras_require={
36
+ "dev": [
37
+ "matplotlib>=3.7.2",
38
+ "flake8>=4.0.1.1",
39
+ "black>=24.4.2",
40
+ "isort>=5.13.2",
41
+ "pytest>=7.1.2",
42
+ "datasets>=2.19.2",
43
+ ]
44
+ },
45
+ )
@@ -0,0 +1,46 @@
1
+ import platform
2
+ import sys
3
+
4
+
5
+ def print_env_report():
6
+ """
7
+ Prints a report of the environment. Useful for debugging and reproducibility.
8
+ Usage:
9
+ ```
10
+ python -m liger_kernel.env_report
11
+ ```
12
+ """
13
+ print("Environment Report:")
14
+ print("-------------------")
15
+ print(f"Operating System: {platform.platform()}")
16
+ print(f"Python version: {sys.version.split()[0]}")
17
+
18
+ try:
19
+ import torch
20
+
21
+ print(f"PyTorch version: {torch.__version__}")
22
+ cuda_version = (
23
+ torch.version.cuda if torch.cuda.is_available() else "Not available"
24
+ )
25
+ print(f"CUDA version: {cuda_version}")
26
+ except ImportError:
27
+ print("PyTorch: Not installed")
28
+ print("CUDA version: Unable to query")
29
+
30
+ try:
31
+ import triton
32
+
33
+ print(f"Triton version: {triton.__version__}")
34
+ except ImportError:
35
+ print("Triton: Not installed")
36
+
37
+ try:
38
+ import transformers
39
+
40
+ print(f"Transformers version: {transformers.__version__}")
41
+ except ImportError:
42
+ print("Transformers: Not installed")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ print_env_report()