liger-kernel 0.1.0__tar.gz → 0.3.1__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 (58) hide show
  1. liger_kernel-0.3.1/PKG-INFO +395 -0
  2. liger_kernel-0.3.1/README.md +349 -0
  3. liger_kernel-0.3.1/pyproject.toml +44 -0
  4. liger_kernel-0.3.1/src/liger_kernel/env_report.py +46 -0
  5. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/ops/cross_entropy.py +130 -63
  6. liger_kernel-0.3.1/src/liger_kernel/ops/experimental/embedding.py +143 -0
  7. liger_kernel-0.3.1/src/liger_kernel/ops/fused_linear_cross_entropy.py +238 -0
  8. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/ops/geglu.py +56 -44
  9. liger_kernel-0.3.1/src/liger_kernel/ops/kl_div.py +258 -0
  10. liger_kernel-0.3.1/src/liger_kernel/ops/layer_norm.py +236 -0
  11. liger_kernel-0.3.1/src/liger_kernel/ops/rms_norm.py +321 -0
  12. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/ops/rope.py +91 -84
  13. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/ops/swiglu.py +50 -43
  14. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/ops/utils.py +12 -0
  15. liger_kernel-0.3.1/src/liger_kernel/transformers/__init__.py +28 -0
  16. liger_kernel-0.3.1/src/liger_kernel/transformers/auto_model.py +45 -0
  17. liger_kernel-0.3.1/src/liger_kernel/transformers/cross_entropy.py +21 -0
  18. liger_kernel-0.3.1/src/liger_kernel/transformers/experimental/embedding.py +28 -0
  19. liger_kernel-0.3.1/src/liger_kernel/transformers/functional.py +19 -0
  20. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/transformers/fused_linear_cross_entropy.py +8 -2
  21. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/transformers/geglu.py +4 -2
  22. liger_kernel-0.3.1/src/liger_kernel/transformers/kl_div.py +14 -0
  23. liger_kernel-0.3.1/src/liger_kernel/transformers/layer_norm.py +30 -0
  24. liger_kernel-0.3.1/src/liger_kernel/transformers/model/gemma.py +138 -0
  25. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/transformers/model/llama.py +1 -1
  26. liger_kernel-0.3.1/src/liger_kernel/transformers/model/mistral.py +138 -0
  27. liger_kernel-0.3.1/src/liger_kernel/transformers/model/mixtral.py +158 -0
  28. liger_kernel-0.3.1/src/liger_kernel/transformers/model/phi3.py +136 -0
  29. liger_kernel-0.3.1/src/liger_kernel/transformers/model/qwen2.py +135 -0
  30. liger_kernel-0.3.1/src/liger_kernel/transformers/model/qwen2_vl.py +172 -0
  31. liger_kernel-0.3.1/src/liger_kernel/transformers/monkey_patch.py +695 -0
  32. liger_kernel-0.3.1/src/liger_kernel/transformers/rms_norm.py +35 -0
  33. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/transformers/swiglu.py +24 -0
  34. liger_kernel-0.3.1/src/liger_kernel/transformers/trainer_integration.py +2 -0
  35. liger_kernel-0.3.1/src/liger_kernel.egg-info/PKG-INFO +395 -0
  36. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel.egg-info/SOURCES.txt +16 -1
  37. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel.egg-info/requires.txt +7 -3
  38. liger_kernel-0.1.0/PKG-INFO +0 -6
  39. liger_kernel-0.1.0/README.md +0 -205
  40. liger_kernel-0.1.0/setup.py +0 -26
  41. liger_kernel-0.1.0/src/liger_kernel/ops/fused_linear_cross_entropy.py +0 -161
  42. liger_kernel-0.1.0/src/liger_kernel/ops/rms_norm.py +0 -185
  43. liger_kernel-0.1.0/src/liger_kernel/transformers/__init__.py +0 -6
  44. liger_kernel-0.1.0/src/liger_kernel/transformers/cross_entropy.py +0 -11
  45. liger_kernel-0.1.0/src/liger_kernel/transformers/monkey_patch.py +0 -130
  46. liger_kernel-0.1.0/src/liger_kernel/transformers/rms_norm.py +0 -16
  47. liger_kernel-0.1.0/src/liger_kernel/transformers/trainer_integration.py +0 -45
  48. liger_kernel-0.1.0/src/liger_kernel.egg-info/PKG-INFO +0 -6
  49. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/LICENSE +0 -0
  50. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/NOTICE +0 -0
  51. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/setup.cfg +0 -0
  52. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/ops/__init__.py +0 -0
  53. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/transformers/model/__init__.py +0 -0
  54. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/transformers/rope.py +0 -0
  55. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/triton/__init__.py +0 -0
  56. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel/triton/monkey_patch.py +0 -0
  57. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel.egg-info/dependency_links.txt +0 -0
  58. {liger_kernel-0.1.0 → liger_kernel-0.3.1}/src/liger_kernel.egg-info/top_level.txt +0 -0
@@ -0,0 +1,395 @@
1
+ Metadata-Version: 2.1
2
+ Name: liger_kernel
3
+ Version: 0.3.1
4
+ Summary: Efficient Triton kernels for LLM Training
5
+ License: BSD 2-CLAUSE LICENSE
6
+ Copyright 2024 LinkedIn Corporation
7
+ All Rights Reserved.
8
+ Redistribution and use in source and binary forms, with or
9
+ without modification, are permitted provided that the following
10
+ conditions are met:
11
+ 1. Redistributions of source code must retain the above copyright
12
+ notice, this list of conditions and the following disclaimer.
13
+ 2. Redistributions in binary form must reproduce the above
14
+ copyright notice, this list of conditions and the following
15
+ disclaimer in the documentation and/or other materials provided
16
+ with the distribution.
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+
29
+ Project-URL: Homepage, https://github.com/linkedin/Liger-Kernel
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ License-File: NOTICE
33
+ Requires-Dist: torch>=2.1.2
34
+ Requires-Dist: triton>=2.3.0
35
+ Provides-Extra: transformers
36
+ Requires-Dist: transformers~=4.0; extra == "transformers"
37
+ Provides-Extra: dev
38
+ Requires-Dist: transformers>=4.44.2; extra == "dev"
39
+ Requires-Dist: matplotlib>=3.7.2; extra == "dev"
40
+ Requires-Dist: flake8>=4.0.1.1; extra == "dev"
41
+ Requires-Dist: black>=24.4.2; extra == "dev"
42
+ Requires-Dist: isort>=5.13.2; extra == "dev"
43
+ Requires-Dist: pytest>=7.1.2; extra == "dev"
44
+ Requires-Dist: datasets>=2.19.2; extra == "dev"
45
+ Requires-Dist: seaborn; extra == "dev"
46
+
47
+ # Liger Kernel: Efficient Triton Kernels for LLM Training
48
+
49
+
50
+ <table style="width: 100%; text-align: center; border-collapse: collapse;">
51
+ <tr>
52
+ <th style="padding: 10px;" colspan="2">Stable</th>
53
+ <th style="padding: 10px;" colspan="2">Nightly</th>
54
+ <th style="padding: 10px;">Discord</th>
55
+ </tr>
56
+ <tr>
57
+ <td style="padding: 10px;">
58
+ <a href="https://pepy.tech/project/liger-kernel">
59
+ <img src="https://static.pepy.tech/badge/liger-kernel" alt="Downloads (Stable)">
60
+ </a>
61
+ </td>
62
+ <td style="padding: 10px;">
63
+ <a href="https://pypi.org/project/liger-kernel">
64
+ <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel?color=green">
65
+ </a>
66
+ </td>
67
+ <td style="padding: 10px;">
68
+ <a href="https://pepy.tech/project/liger-kernel-nightly">
69
+ <img src="https://static.pepy.tech/badge/liger-kernel-nightly" alt="Downloads (Nightly)">
70
+ </a>
71
+ </td>
72
+ <td style="padding: 10px;">
73
+ <a href="https://pypi.org/project/liger-kernel-nightly">
74
+ <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel-nightly?color=green">
75
+ </a>
76
+ </td>
77
+ <td style="padding: 10px;">
78
+ <a href="https://discord.gg/gpumode">
79
+ <img src="https://dcbadge.vercel.app/api/server/gpumode?style=flat" alt="Join Our Discord">
80
+ </a>
81
+ </td>
82
+ </tr>
83
+ </table>
84
+
85
+
86
+
87
+ <img src="https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/logo-banner.png">
88
+
89
+ [Installation](#installation) | [Getting Started](#getting-started) | [Examples](#examples) | [APIs](#apis) | [Structure](#structure) | [Contributing](#contributing) | [Acknowledgement](#acknowledgement)
90
+
91
+ <details>
92
+ <summary>Latest News 🔥</summary>
93
+
94
+ - [2024/9/6] We release v0.2.1 ([X post](https://x.com/liger_kernel/status/1832168197002510649)). 2500+ Stars, 10+ New Contributors, 50+ PRs, 50k Downloads in two weeks!
95
+ - [2024/8/31] CUDA MODE talk, [Liger-Kernel: Real-world Triton kernel for LLM Training](https://youtu.be/gWble4FreV4?si=dxPeIchhkJ36Mbns), [Slides](https://github.com/cuda-mode/lectures?tab=readme-ov-file#lecture-28-liger-kernel)
96
+ - [2024/8/23] Official release: check out our [X post](https://x.com/hsu_byron/status/1827072737673982056)
97
+
98
+ </details>
99
+
100
+
101
+ **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](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.
102
+
103
+ ## Supercharge Your Model with Liger Kernel
104
+
105
+ ![Banner](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/banner.GIF)
106
+
107
+ 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.
108
+
109
+
110
+ | Speed Up | Memory Reduction |
111
+ |--------------------------|-------------------------|
112
+ | ![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) |
113
+
114
+ > **Note:**
115
+ > - Benchmark conditions: LLaMA 3-8B, Batch Size = 8, Data Type = `bf16`, Optimizer = AdamW, Gradient Checkpointing = True, Distributed Strategy = FSDP1 on 8 A100s.
116
+ > - Hugging Face models start to OOM at a 4K context length, whereas Hugging Face + Liger Kernel scales up to 16K.
117
+
118
+ ## Examples
119
+
120
+ ### Basic
121
+
122
+ | **Example** | **Description** | **Lightning Studio** |
123
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
124
+ | [**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 |
125
+ | [**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 |
126
+
127
+ ### Advanced
128
+
129
+ | **Example** | **Description** | **Lightning Studio** |
130
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
131
+ | [**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 |
132
+
133
+ ## Key Features
134
+
135
+ - **Ease of use:** Simply patch your Hugging Face model with one line of code, or compose your own model using our Liger Kernel modules.
136
+ - **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.
137
+ - **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.
138
+ - **Lightweight:** Liger Kernel has minimal dependencies, requiring only Torch and Triton—no extra libraries needed! Say goodbye to dependency headaches!
139
+ - **Multi-GPU supported:** Compatible with multi-GPU setups (PyTorch FSDP, DeepSpeed, DDP, etc.).
140
+ - **Trainer Framework Integration**: [Axolotl](https://github.com/axolotl-ai-cloud/axolotl), [LLaMa-Factory](https://github.com/hiyouga/LLaMA-Factory), [SFTTrainer](https://github.com/huggingface/trl/releases/tag/v0.10.1), [Hugging Face Trainer](https://github.com/huggingface/transformers/pull/32860), [SWIFT](https://github.com/modelscope/ms-swift)
141
+
142
+ ## Target Audiences
143
+
144
+ - **Researchers**: Looking to compose models using efficient and reliable kernels for frontier experiments.
145
+ - **ML Practitioners**: Focused on maximizing GPU training efficiency with optimal, high-performance kernels.
146
+ - **Curious Novices**: Eager to learn how to write reliable Triton kernels to enhance training efficiency.
147
+
148
+
149
+ ## Installation
150
+
151
+ ### Dependencies
152
+
153
+ - `torch >= 2.1.2`
154
+ - `triton >= 2.3.0`
155
+
156
+ ### Optional Dependencies
157
+
158
+ - `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.
159
+
160
+ > **Note:**
161
+ > Our kernels inherit the full spectrum of hardware compatibility offered by [Triton](https://github.com/triton-lang/triton).
162
+
163
+ To install the stable version:
164
+
165
+ ```bash
166
+ $ pip install liger-kernel
167
+ ```
168
+
169
+ To install the nightly version:
170
+
171
+ ```bash
172
+ $ pip install liger-kernel-nightly
173
+ ```
174
+
175
+ To install from source:
176
+
177
+ ```bash
178
+ git clone https://github.com/linkedin/Liger-Kernel.git
179
+ cd Liger-Kernel
180
+ pip install -e .
181
+ # or if using transformers
182
+ pip install -e .[transformers]
183
+ ```
184
+
185
+ ## Getting Started
186
+
187
+ There are a couple of ways to apply Liger kernels, depending on the level of customization required.
188
+
189
+ ### 1. Use AutoLigerKernelForCausalLM
190
+
191
+ 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.
192
+
193
+ ```python
194
+ from liger_kernel.transformers import AutoLigerKernelForCausalLM
195
+
196
+ # This AutoModel wrapper class automatically monkey-patches the
197
+ # model with the optimized Liger kernels if the model is supported.
198
+ model = AutoLigerKernelForCausalLM.from_pretrained("path/to/some/model")
199
+ ```
200
+
201
+ ### 2. Apply Model-Specific Patching APIs
202
+
203
+ Using the [patching APIs](#patching), you can swap Hugging Face models with optimized Liger Kernels.
204
+
205
+ ```python
206
+ import transformers
207
+ from liger_kernel.transformers import apply_liger_kernel_to_llama
208
+
209
+ # 1a. Adding this line automatically monkey-patches the model with the optimized Liger kernels
210
+ apply_liger_kernel_to_llama()
211
+
212
+ # 1b. You could alternatively specify exactly which kernels are applied
213
+ apply_liger_kernel_to_llama(
214
+ rope=True,
215
+ swiglu=True,
216
+ cross_entropy=True,
217
+ fused_linear_cross_entropy=False,
218
+ rms_norm=False
219
+ )
220
+
221
+ # 2. Instantiate patched model
222
+ model = transformers.AutoModelForCausalLM("path/to/llama/model")
223
+ ```
224
+
225
+ ### 3. Compose Your Own Model
226
+
227
+ You can take individual [kernels](#kernels) to compose your models.
228
+
229
+ ```python
230
+ from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
231
+ import torch.nn as nn
232
+ import torch
233
+
234
+ model = nn.Linear(128, 256).cuda()
235
+
236
+ # fuses linear + cross entropy layers together and performs chunk-by-chunk computation to reduce memory
237
+ loss_fn = LigerFusedLinearCrossEntropyLoss()
238
+
239
+ input = torch.randn(4, 128, requires_grad=True, device="cuda")
240
+ target = torch.randint(256, (4, ), device="cuda")
241
+
242
+ loss = loss_fn(model.weight, input, target)
243
+ loss.backward()
244
+ ```
245
+
246
+
247
+ ## Structure
248
+
249
+ ### Source Code
250
+
251
+ - `ops/`: Core Triton operations.
252
+ - `transformers/`: PyTorch `nn.Module` implementations built on Triton operations, compliant with the `transformers` API.
253
+
254
+ ### Tests
255
+
256
+ - `transformers/`: Correctness tests for the Triton-based layers.
257
+ - `convergence/`: Patches Hugging Face models with all kernels, runs multiple iterations, and compares weights, logits, and loss layer-by-layer.
258
+
259
+ ### Benchmark
260
+
261
+ - `benchmark/`: Execution time and memory benchmarks compared to Hugging Face layers.
262
+
263
+ ## APIs
264
+
265
+ ### AutoModel
266
+
267
+ | **AutoModel Variant** | **API** |
268
+ |-----------|---------|
269
+ | AutoModelForCausalLM | `liger_kernel.transformers.AutoLigerKernelForCausalLM` |
270
+
271
+
272
+ ### Patching
273
+
274
+ | **Model** | **API** | **Supported Operations** |
275
+ |-------------|--------------------------------------------------------------|-------------------------------------------------------------------------|
276
+ | LLaMA 2 & 3 | `liger_kernel.transformers.apply_liger_kernel_to_llama` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
277
+ | Mistral | `liger_kernel.transformers.apply_liger_kernel_to_mistral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
278
+ | Mixtral | `liger_kernel.transformers.apply_liger_kernel_to_mixtral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
279
+ | Gemma1 | `liger_kernel.transformers.apply_liger_kernel_to_gemma` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
280
+ | Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss |
281
+ | Qwen2 & Qwen2.5 | `liger_kernel.transformers.apply_liger_kernel_to_qwen2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
282
+ | Qwen2-VL | `liger_kernel.transformers.apply_liger_kernel_to_qwen2_vl` | RMSNorm, LayerNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
283
+ | Phi3 & Phi3.5 | `liger_kernel.transformers.apply_liger_kernel_to_phi3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
284
+
285
+
286
+
287
+ ### Kernels
288
+
289
+ | **Kernel** | **API** |
290
+ |---------------------------------|-------------------------------------------------------------|
291
+ | RMSNorm | `liger_kernel.transformers.LigerRMSNorm` |
292
+ | LayerNorm | `liger_kernel.transformers.LigerLayerNorm` |
293
+ | RoPE | `liger_kernel.transformers.liger_rotary_pos_emb` |
294
+ | SwiGLU | `liger_kernel.transformers.LigerSwiGLUMLP` |
295
+ | GeGLU | `liger_kernel.transformers.LigerGEGLUMLP` |
296
+ | CrossEntropy | `liger_kernel.transformers.LigerCrossEntropyLoss` |
297
+ | FusedLinearCrossEntropy | `liger_kernel.transformers.LigerFusedLinearCrossEntropyLoss`|
298
+ | KLDivergence | `liger_kernel.transformers.LigerKLDIVLoss` |
299
+
300
+ - **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.
301
+ - **LayerNorm**: [LayerNorm](https://arxiv.org/pdf/1607.06450), which centers and normalizes activations across the feature dimension, is implemented by fusing the centering, normalization and scaling steps into a single Triton kernel, and achieves ~2X speedup.
302
+ - **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.
303
+ - **SwiGLU**: [Swish Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
304
+ $$\text{SwiGLU}(x)=\text{Swish}_{\beta}(xW+b)\otimes(xV+c)$$
305
+ , 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.
306
+ - **GeGLU**: [GELU Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
307
+ $$\text{GeGLU}(x)=\text{GELU}(xW+b)\otimes(xV+c)$$
308
+ , 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.
309
+ - **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.).
310
+ <!-- TODO: verify vocab sizes are accurate -->
311
+ - **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.
312
+ - **KLDivergence**: [KL Divergence](https://pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html) is implemented by fusing the forward into a single triton kernel, with reduction done outside the kernel. It achieves ~1.5X speed and ~15% memory reduction for 128K vocab size.
313
+
314
+ ### Experimental Kernels
315
+
316
+ | **Kernel** | **API** |
317
+ |---------------------------------|-------------------------------------------------------------|
318
+ | Embedding | `liger_kernel.transformers.experimental.LigerEmbedding` |
319
+
320
+
321
+ - **Embedding**: [Embedding](https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html) is implemented by fusing embedding lookup and output operations. It achieves a peak speedup of ~1.5x in the forward pass and an overall speedup of ~1.1x.
322
+
323
+ <!-- TODO: be more specific about batch size -->
324
+ > **Note:**
325
+ > 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.
326
+
327
+ ## Note on ML Compiler
328
+
329
+ ### Torch Compile
330
+
331
+ 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.
332
+
333
+ | Configuration | Throughput (tokens/sec) | Memory Reserved (GB) |
334
+ |--------------------------------|----------------------------|-------------------------|
335
+ | Torch Compile | 3780 | 66.4 |
336
+ | Torch Compile + Liger Kernel | 3702 | 31.0 |
337
+
338
+ > **Note:**
339
+ > 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.
340
+ > 2. Tested on torch `2.5.0.dev20240731+cu118`
341
+
342
+ ## Contributing
343
+
344
+ [CONTRIBUTING GUIDE](https://github.com/linkedin/Liger-Kernel/blob/main/CONTRIBUTING.md)
345
+
346
+ ## Acknowledgement
347
+
348
+
349
+ ### Design
350
+
351
+ - [@claire_yishan](https://twitter.com/claire_yishan) for the LOGO design
352
+ - [Wave Snippets](https://www.wavesnippets.com/) for generating the animated code snippets
353
+
354
+ ### Code
355
+
356
+ We referenced or used the following projects:
357
+
358
+
359
+
360
+ | # | Project | Description | Location | License |
361
+ |---|----------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
362
+ | 1 | [Unsloth](https://github.com/unslothai/unsloth/blob/fd753fed99ed5f10ef8a9b7139588d9de9ddecfb/unsloth/kernels/utils.py#L43) | `calculate_settings` to determine block size and warp; We reuse it for Norm and MLP | [Liger Kernel Utils](https://github.com/linkedin/Liger-Kernel/blob/e249eee723978bf8610ff1ea2297d048a2417e20/src/liger_kernel/ops/utils.py#L23) | [Apache](https://github.com/unslothai/unsloth/blob/fd753fed99ed5f10ef8a9b7139588d9de9ddecfb/LICENSE) |
363
+ | 2 | [Unsloth](https://github.com/unslothai/unsloth/blob/976d11a10d54383aeb7a692c69e01151a20bfd72/unsloth/kernels/rms_layernorm.py#L48) | We modified and added dW calculation on top of Unsloth implementation | [Liger Kernel RMS Norm](https://github.com/linkedin/Liger-Kernel/blob/e249eee723978bf8610ff1ea2297d048a2417e20/src/liger_kernel/ops/rms_norm.py#L50) | [Apache](https://github.com/unslothai/unsloth/blob/fd753fed99ed5f10ef8a9b7139588d9de9ddecfb/LICENSE) |
364
+ | 3 | [Triton tutorial](https://triton-lang.org/main/index.html) | We modified on top of triton tutorials | [Liger Kernel RMS Norm](https://github.com/linkedin/Liger-Kernel/blob/e249eee723978bf8610ff1ea2297d048a2417e20/src/liger_kernel/ops/rms_norm.py#L50) | [MIT](https://github.com/triton-lang/triton/blob/main/LICENSE) |
365
+ | 4 | [tiny shakespeare dataset](https://huggingface.co/datasets/karpathy/tiny_shakespeare) | We use tiny shakespeare dataset to conduct convergence test on mini model | [Liger Kernel Convergence](https://github.com/linkedin/Liger-Kernel/tree/main/test/convergence) | N/A |
366
+ | 5 | [Efficient Cross Entropy](https://github.com/mgmalek/efficient_cross_entropy) | We use the idea of gradient-in-forward and chunking | [Liger Kernel Linear Cross Entropy](https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/ops/fused_linear_cross_entropy.py) | [MIT](https://github.com/mgmalek/efficient_cross_entropy/blob/main/LICENSE) |
367
+ | 6 | [Flash attn](https://github.com/Dao-AILab/flash-attention) | We take many optimization ideas from the work, such as tiling and recomputation | | [BSD](https://github.com/Dao-AILab/flash-attention/blob/main/LICENSE) |
368
+ | 7 | [AutoAWQ](https://github.com/casper-hansen/AutoAWQ) | We reference the design of automodel | [Liger Kernel Auto Model](https://github.com/linkedin/Liger-Kernel/blob/main/src/liger_kernel/transformers/auto_model.py) | [MIT](https://github.com/casper-hansen/AutoAWQ/blob/main/LICENSE) |
369
+ | 8 | [llm.c](https://github.com/karpathy/llm.c) | We reference the design of end-to-end testing | [Liger Kernel Convergence Tests](https://github.com/linkedin/Liger-Kernel/tree/main/test/convergence) | [MIT](https://github.com/karpathy/llm.c/blob/master/LICENSE) |
370
+
371
+ Many thanks to the contributors to these projects for their invaluable work that helped make Liger possible.
372
+
373
+ ## License
374
+
375
+ [BSD 2-CLAUSE](https://github.com/linkedin/Liger-Kernel/blob/main/LICENSE)
376
+
377
+ ## Contact
378
+
379
+ - For public discussion, join [our discord channel](https://discord.gg/vNBDpjhb)
380
+ - For formal collaboration, send an email to byhsu@linkedin.com
381
+
382
+ ## Cite this work
383
+
384
+ Biblatex entry:
385
+ ```bib
386
+ @software{liger2024,
387
+ title = {Liger-Kernel: Efficient Triton Kernels for LLM Training},
388
+ author = {Hsu, Pin-Lun and Dai, Yun and Kothapalli, Vignesh and Song, Qingquan and Tang, Shao and Zhu, Siyu},
389
+ url = {https://github.com/linkedin/Liger-Kernel},
390
+ year = {2024}
391
+ }
392
+ ```
393
+
394
+ ## Star History
395
+ [![Star History Chart](https://api.star-history.com/svg?repos=linkedin/Liger-Kernel&type=Date)](https://star-history.com/#linkedin/Liger-Kernel&Date)