liger-kernel 0.0.1__tar.gz → 0.3.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 (58) hide show
  1. liger_kernel-0.3.0/PKG-INFO +388 -0
  2. liger_kernel-0.3.0/README.md +343 -0
  3. liger_kernel-0.3.0/pyproject.toml +41 -0
  4. liger_kernel-0.3.0/src/liger_kernel/env_report.py +46 -0
  5. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/ops/cross_entropy.py +130 -63
  6. liger_kernel-0.3.0/src/liger_kernel/ops/experimental/embedding.py +143 -0
  7. liger_kernel-0.3.0/src/liger_kernel/ops/fused_linear_cross_entropy.py +238 -0
  8. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/ops/geglu.py +54 -42
  9. liger_kernel-0.3.0/src/liger_kernel/ops/kl_div.py +247 -0
  10. liger_kernel-0.3.0/src/liger_kernel/ops/layer_norm.py +236 -0
  11. liger_kernel-0.3.0/src/liger_kernel/ops/rms_norm.py +321 -0
  12. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/ops/rope.py +91 -84
  13. liger_kernel-0.3.0/src/liger_kernel/ops/swiglu.py +120 -0
  14. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/ops/utils.py +12 -0
  15. liger_kernel-0.3.0/src/liger_kernel/transformers/__init__.py +28 -0
  16. liger_kernel-0.3.0/src/liger_kernel/transformers/auto_model.py +33 -0
  17. liger_kernel-0.3.0/src/liger_kernel/transformers/cross_entropy.py +21 -0
  18. liger_kernel-0.3.0/src/liger_kernel/transformers/experimental/embedding.py +28 -0
  19. liger_kernel-0.3.0/src/liger_kernel/transformers/functional.py +19 -0
  20. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/transformers/fused_linear_cross_entropy.py +8 -2
  21. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/transformers/geglu.py +4 -2
  22. liger_kernel-0.3.0/src/liger_kernel/transformers/kl_div.py +13 -0
  23. liger_kernel-0.3.0/src/liger_kernel/transformers/layer_norm.py +30 -0
  24. liger_kernel-0.3.0/src/liger_kernel/transformers/model/gemma.py +138 -0
  25. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/transformers/model/llama.py +1 -1
  26. liger_kernel-0.3.0/src/liger_kernel/transformers/model/mistral.py +138 -0
  27. liger_kernel-0.3.0/src/liger_kernel/transformers/model/mixtral.py +158 -0
  28. liger_kernel-0.3.0/src/liger_kernel/transformers/model/phi3.py +136 -0
  29. liger_kernel-0.3.0/src/liger_kernel/transformers/model/qwen2.py +135 -0
  30. liger_kernel-0.3.0/src/liger_kernel/transformers/model/qwen2_vl.py +172 -0
  31. liger_kernel-0.3.0/src/liger_kernel/transformers/monkey_patch.py +721 -0
  32. liger_kernel-0.3.0/src/liger_kernel/transformers/rms_norm.py +35 -0
  33. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/transformers/swiglu.py +24 -0
  34. liger_kernel-0.3.0/src/liger_kernel/transformers/trainer_integration.py +2 -0
  35. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/triton/monkey_patch.py +0 -2
  36. liger_kernel-0.3.0/src/liger_kernel.egg-info/PKG-INFO +388 -0
  37. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel.egg-info/SOURCES.txt +17 -1
  38. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel.egg-info/requires.txt +5 -3
  39. liger_kernel-0.0.1/PKG-INFO +0 -6
  40. liger_kernel-0.0.1/README.md +0 -206
  41. liger_kernel-0.0.1/setup.py +0 -26
  42. liger_kernel-0.0.1/src/liger_kernel/ops/fused_linear_cross_entropy.py +0 -161
  43. liger_kernel-0.0.1/src/liger_kernel/ops/rms_norm.py +0 -167
  44. liger_kernel-0.0.1/src/liger_kernel/ops/swiglu.py +0 -113
  45. liger_kernel-0.0.1/src/liger_kernel/transformers/__init__.py +0 -5
  46. liger_kernel-0.0.1/src/liger_kernel/transformers/cross_entropy.py +0 -11
  47. liger_kernel-0.0.1/src/liger_kernel/transformers/monkey_patch.py +0 -100
  48. liger_kernel-0.0.1/src/liger_kernel/transformers/rms_norm.py +0 -16
  49. liger_kernel-0.0.1/src/liger_kernel.egg-info/PKG-INFO +0 -6
  50. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/LICENSE +0 -0
  51. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/NOTICE +0 -0
  52. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/setup.cfg +0 -0
  53. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/ops/__init__.py +0 -0
  54. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/transformers/model/__init__.py +0 -0
  55. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/transformers/rope.py +0 -0
  56. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel/triton/__init__.py +0 -0
  57. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel.egg-info/dependency_links.txt +0 -0
  58. {liger_kernel-0.0.1 → liger_kernel-0.3.0}/src/liger_kernel.egg-info/top_level.txt +0 -0
@@ -0,0 +1,388 @@
1
+ Metadata-Version: 2.1
2
+ Name: liger_kernel
3
+ Version: 0.3.0
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
+ Requires-Dist: transformers>=4.42.0
36
+ Provides-Extra: dev
37
+ Requires-Dist: matplotlib>=3.7.2; extra == "dev"
38
+ Requires-Dist: flake8>=4.0.1.1; extra == "dev"
39
+ Requires-Dist: black>=24.4.2; extra == "dev"
40
+ Requires-Dist: isort>=5.13.2; extra == "dev"
41
+ Requires-Dist: pytest>=7.1.2; extra == "dev"
42
+ Requires-Dist: datasets>=2.19.2; extra == "dev"
43
+ Requires-Dist: jupyter==1.0.0; extra == "dev"
44
+ Requires-Dist: seaborn; extra == "dev"
45
+
46
+ # Liger Kernel: Efficient Triton Kernels for LLM Training
47
+
48
+
49
+ <table style="width: 100%; text-align: center; border-collapse: collapse;">
50
+ <tr>
51
+ <th style="padding: 10px;" colspan="2">Stable</th>
52
+ <th style="padding: 10px;" colspan="2">Nightly</th>
53
+ <th style="padding: 10px;">Discord</th>
54
+ </tr>
55
+ <tr>
56
+ <td style="padding: 10px;">
57
+ <a href="https://pepy.tech/project/liger-kernel">
58
+ <img src="https://static.pepy.tech/badge/liger-kernel" alt="Downloads (Stable)">
59
+ </a>
60
+ </td>
61
+ <td style="padding: 10px;">
62
+ <a href="https://pypi.org/project/liger-kernel">
63
+ <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel?color=green">
64
+ </a>
65
+ </td>
66
+ <td style="padding: 10px;">
67
+ <a href="https://pepy.tech/project/liger-kernel-nightly">
68
+ <img src="https://static.pepy.tech/badge/liger-kernel-nightly" alt="Downloads (Nightly)">
69
+ </a>
70
+ </td>
71
+ <td style="padding: 10px;">
72
+ <a href="https://pypi.org/project/liger-kernel-nightly">
73
+ <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel-nightly?color=green">
74
+ </a>
75
+ </td>
76
+ <td style="padding: 10px;">
77
+ <a href="https://discord.gg/CX2YmNmn">
78
+ <img src="https://dcbadge.vercel.app/api/server/cudamode?style=flat" alt="Join Our Discord">
79
+ </a>
80
+ </td>
81
+ </tr>
82
+ </table>
83
+
84
+
85
+
86
+ <img src="https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/logo-banner.png">
87
+
88
+ [Installation](#installation) | [Getting Started](#getting-started) | [Examples](#examples) | [APIs](#apis) | [Structure](#structure) | [Contributing](#contributing) | [Acknowledgement](#acknowledgement)
89
+
90
+ <details>
91
+ <summary>Latest News 🔥</summary>
92
+
93
+ - [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!
94
+ - [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)
95
+ - [2024/8/23] Official release: check out our [X post](https://x.com/hsu_byron/status/1827072737673982056)
96
+
97
+ </details>
98
+
99
+
100
+ **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.
101
+
102
+ ## Supercharge Your Model with Liger Kernel
103
+
104
+ ![Banner](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/banner.GIF)
105
+
106
+ 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.
107
+
108
+
109
+ | Speed Up | Memory Reduction |
110
+ |--------------------------|-------------------------|
111
+ | ![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) |
112
+
113
+ > **Note:**
114
+ > - Benchmark conditions: LLaMA 3-8B, Batch Size = 8, Data Type = `bf16`, Optimizer = AdamW, Gradient Checkpointing = True, Distributed Strategy = FSDP1 on 8 A100s.
115
+ > - Hugging Face models start to OOM at a 4K context length, whereas Hugging Face + Liger Kernel scales up to 16K.
116
+
117
+ ## Examples
118
+
119
+ ### Basic
120
+
121
+ | **Example** | **Description** | **Lightning Studio** |
122
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
123
+ | [**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 |
124
+ | [**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 |
125
+
126
+ ### Advanced
127
+
128
+ | **Example** | **Description** | **Lightning Studio** |
129
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
130
+ | [**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 |
131
+
132
+ ## Key Features
133
+
134
+ - **Ease of use:** Simply patch your Hugging Face model with one line of code, or compose your own model using our Liger Kernel modules.
135
+ - **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.
136
+ - **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.
137
+ - **Lightweight:** Liger Kernel has minimal dependencies, requiring only Torch and Triton—no extra libraries needed! Say goodbye to dependency headaches!
138
+ - **Multi-GPU supported:** Compatible with multi-GPU setups (PyTorch FSDP, DeepSpeed, DDP, etc.).
139
+ - **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)
140
+
141
+ ## Target Audiences
142
+
143
+ - **Researchers**: Looking to compose models using efficient and reliable kernels for frontier experiments.
144
+ - **ML Practitioners**: Focused on maximizing GPU training efficiency with optimal, high-performance kernels.
145
+ - **Curious Novices**: Eager to learn how to write reliable Triton kernels to enhance training efficiency.
146
+
147
+
148
+ ## Installation
149
+
150
+ ### Dependencies
151
+
152
+ - `torch >= 2.1.2`
153
+ - `triton >= 2.3.0`
154
+ - `transformers >= 4.42.0`
155
+
156
+ > **Note:**
157
+ > Our kernels inherit the full spectrum of hardware compatibility offered by [Triton](https://github.com/triton-lang/triton).
158
+
159
+ To install the stable version:
160
+
161
+ ```bash
162
+ $ pip install liger-kernel
163
+ ```
164
+
165
+ To install the nightly version:
166
+
167
+ ```bash
168
+ $ pip install liger-kernel-nightly
169
+ ```
170
+
171
+ To install from source:
172
+
173
+ ```bash
174
+ git clone https://github.com/linkedin/Liger-Kernel.git
175
+ cd Liger-Kernel
176
+ pip install -e .
177
+ ```
178
+ ## Getting Started
179
+
180
+ There are a couple of ways to apply Liger kernels, depending on the level of customization required.
181
+
182
+ ### 1. Use AutoLigerKernelForCausalLM
183
+
184
+ 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.
185
+
186
+ ```python
187
+ from liger_kernel.transformers import AutoLigerKernelForCausalLM
188
+
189
+ # This AutoModel wrapper class automatically monkey-patches the
190
+ # model with the optimized Liger kernels if the model is supported.
191
+ model = AutoLigerKernelForCausalLM.from_pretrained("path/to/some/model")
192
+ ```
193
+
194
+ ### 2. Apply Model-Specific Patching APIs
195
+
196
+ Using the [patching APIs](#patching), you can swap Hugging Face models with optimized Liger Kernels.
197
+
198
+ ```python
199
+ import transformers
200
+ from liger_kernel.transformers import apply_liger_kernel_to_llama
201
+
202
+ # 1a. Adding this line automatically monkey-patches the model with the optimized Liger kernels
203
+ apply_liger_kernel_to_llama()
204
+
205
+ # 1b. You could alternatively specify exactly which kernels are applied
206
+ apply_liger_kernel_to_llama(
207
+ rope=True,
208
+ swiglu=True,
209
+ cross_entropy=True,
210
+ fused_linear_cross_entropy=False,
211
+ rms_norm=False
212
+ )
213
+
214
+ # 2. Instantiate patched model
215
+ model = transformers.AutoModelForCausalLM("path/to/llama/model")
216
+ ```
217
+
218
+ ### 3. Compose Your Own Model
219
+
220
+ You can take individual [kernels](#kernels) to compose your models.
221
+
222
+ ```python
223
+ from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
224
+ import torch.nn as nn
225
+ import torch
226
+
227
+ model = nn.Linear(128, 256).cuda()
228
+
229
+ # fuses linear + cross entropy layers together and performs chunk-by-chunk computation to reduce memory
230
+ loss_fn = LigerFusedLinearCrossEntropyLoss()
231
+
232
+ input = torch.randn(4, 128, requires_grad=True, device="cuda")
233
+ target = torch.randint(256, (4, ), device="cuda")
234
+
235
+ loss = loss_fn(model.weight, input, target)
236
+ loss.backward()
237
+ ```
238
+
239
+
240
+ ## Structure
241
+
242
+ ### Source Code
243
+
244
+ - `ops/`: Core Triton operations.
245
+ - `transformers/`: PyTorch `nn.Module` implementations built on Triton operations, compliant with the `transformers` API.
246
+
247
+ ### Tests
248
+
249
+ - `transformers/`: Correctness tests for the Triton-based layers.
250
+ - `convergence/`: Patches Hugging Face models with all kernels, runs multiple iterations, and compares weights, logits, and loss layer-by-layer.
251
+
252
+ ### Benchmark
253
+
254
+ - `benchmark/`: Execution time and memory benchmarks compared to Hugging Face layers.
255
+
256
+ ## APIs
257
+
258
+ ### AutoModel
259
+
260
+ | **AutoModel Variant** | **API** |
261
+ |-----------|---------|
262
+ | AutoModelForCausalLM | `liger_kernel.transformers.AutoLigerKernelForCausalLM` |
263
+
264
+
265
+ ### Patching
266
+
267
+ | **Model** | **API** | **Supported Operations** |
268
+ |-------------|--------------------------------------------------------------|-------------------------------------------------------------------------|
269
+ | LLaMA 2 & 3 | `liger_kernel.transformers.apply_liger_kernel_to_llama` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
270
+ | Mistral | `liger_kernel.transformers.apply_liger_kernel_to_mistral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
271
+ | Mixtral | `liger_kernel.transformers.apply_liger_kernel_to_mixtral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
272
+ | Gemma1 | `liger_kernel.transformers.apply_liger_kernel_to_gemma` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
273
+ | Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss |
274
+ | Qwen2 | `liger_kernel.transformers.apply_liger_kernel_to_qwen2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
275
+ | Qwen2-VL | `liger_kernel.transformers.apply_liger_kernel_to_qwen2_vl` | RMSNorm, LayerNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
276
+ | Phi3 | `liger_kernel.transformers.apply_liger_kernel_to_phi3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
277
+
278
+
279
+
280
+ ### Kernels
281
+
282
+ | **Kernel** | **API** |
283
+ |---------------------------------|-------------------------------------------------------------|
284
+ | RMSNorm | `liger_kernel.transformers.LigerRMSNorm` |
285
+ | LayerNorm | `liger_kernel.transformers.LigerLayerNorm` |
286
+ | RoPE | `liger_kernel.transformers.liger_rotary_pos_emb` |
287
+ | SwiGLU | `liger_kernel.transformers.LigerSwiGLUMLP` |
288
+ | GeGLU | `liger_kernel.transformers.LigerGEGLUMLP` |
289
+ | CrossEntropy | `liger_kernel.transformers.LigerCrossEntropyLoss` |
290
+ | FusedLinearCrossEntropy | `liger_kernel.transformers.LigerFusedLinearCrossEntropyLoss`|
291
+ | KLDivergence | `liger_kernel.transformers.LigerKLDIVLoss` |
292
+
293
+ - **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.
294
+ - **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.
295
+ - **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.
296
+ - **SwiGLU**: [Swish Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
297
+ $$\text{SwiGLU}(x)=\text{Swish}_{\beta}(xW+b)\otimes(xV+c)$$
298
+ , 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.
299
+ - **GeGLU**: [GELU Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
300
+ $$\text{GeGLU}(x)=\text{GELU}(xW+b)\otimes(xV+c)$$
301
+ , 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.
302
+ - **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.).
303
+ <!-- TODO: verify vocab sizes are accurate -->
304
+ - **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.
305
+ - **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.
306
+
307
+ ### Experimental Kernels
308
+
309
+ | **Kernel** | **API** |
310
+ |---------------------------------|-------------------------------------------------------------|
311
+ | Embedding | `liger_kernel.transformers.experimental.LigerEmbedding` |
312
+
313
+
314
+ - **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.
315
+
316
+ <!-- TODO: be more specific about batch size -->
317
+ > **Note:**
318
+ > 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.
319
+
320
+ ## Note on ML Compiler
321
+
322
+ ### Torch Compile
323
+
324
+ 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.
325
+
326
+ | Configuration | Throughput (tokens/sec) | Memory Reserved (GB) |
327
+ |--------------------------------|----------------------------|-------------------------|
328
+ | Torch Compile | 3780 | 66.4 |
329
+ | Torch Compile + Liger Kernel | 3702 | 31.0 |
330
+
331
+ > **Note:**
332
+ > 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.
333
+ > 2. Tested on torch `2.5.0.dev20240731+cu118`
334
+
335
+ ## Contributing
336
+
337
+ [CONTRIBUTING GUIDE](https://github.com/linkedin/Liger-Kernel/blob/main/CONTRIBUTING.md)
338
+
339
+ ## Acknowledgement
340
+
341
+
342
+ ### Design
343
+
344
+ - [@claire_yishan](https://twitter.com/claire_yishan) for the LOGO design
345
+ - [Wave Snippets](https://www.wavesnippets.com/) for generating the animated code snippets
346
+
347
+ ### Code
348
+
349
+ We referenced or used the following projects:
350
+
351
+
352
+
353
+ | # | Project | Description | Location | License |
354
+ |---|----------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
355
+ | 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) |
356
+ | 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) |
357
+ | 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) |
358
+ | 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 |
359
+ | 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) |
360
+ | 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) |
361
+ | 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) |
362
+ | 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) |
363
+
364
+ Many thanks to the contributors to these projects for their invaluable work that helped make Liger possible.
365
+
366
+ ## License
367
+
368
+ [BSD 2-CLAUSE](https://github.com/linkedin/Liger-Kernel/blob/main/LICENSE)
369
+
370
+ ## Contact
371
+
372
+ - For public discussion, join [our discord channel](https://discord.gg/vNBDpjhb)
373
+ - For formal collaboration, send an email to byhsu@linkedin.com
374
+
375
+ ## Cite this work
376
+
377
+ Biblatex entry:
378
+ ```bib
379
+ @software{liger2024,
380
+ title = {Liger-Kernel: Efficient Triton Kernels for LLM Training},
381
+ author = {Hsu, Pin-Lun and Dai, Yun and Kothapalli, Vignesh and Song, Qingquan and Tang, Shao and Zhu, Siyu},
382
+ url = {https://github.com/linkedin/Liger-Kernel},
383
+ year = {2024}
384
+ }
385
+ ```
386
+
387
+ ## Star History
388
+ [![Star History Chart](https://api.star-history.com/svg?repos=linkedin/Liger-Kernel&type=Date)](https://star-history.com/#linkedin/Liger-Kernel&Date)