liger-kernel-nightly 0.0.1.dev20240819184814__py3-none-any.whl → 0.6.4.dev20251212103629__py3-none-any.whl

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 (126) hide show
  1. liger_kernel/__init__.py +0 -0
  2. liger_kernel/chunked_loss/README.md +25 -0
  3. liger_kernel/chunked_loss/__init__.py +8 -0
  4. liger_kernel/chunked_loss/cosine_similarity_loss.py +136 -0
  5. liger_kernel/chunked_loss/cpo_loss.py +157 -0
  6. liger_kernel/chunked_loss/dpo_loss.py +229 -0
  7. liger_kernel/chunked_loss/functional.py +17 -0
  8. liger_kernel/chunked_loss/fused_linear_distillation.py +292 -0
  9. liger_kernel/chunked_loss/fused_linear_ppo.py +366 -0
  10. liger_kernel/chunked_loss/fused_linear_preference.py +433 -0
  11. liger_kernel/chunked_loss/fused_linear_unpaired_preference.py +341 -0
  12. liger_kernel/chunked_loss/grpo_loss.py +307 -0
  13. liger_kernel/chunked_loss/jsd_loss.py +200 -0
  14. liger_kernel/chunked_loss/kto_loss.py +210 -0
  15. liger_kernel/chunked_loss/orpo_loss.py +144 -0
  16. liger_kernel/chunked_loss/simpo_loss.py +165 -0
  17. liger_kernel/env_report.py +63 -0
  18. liger_kernel/ops/__init__.py +141 -0
  19. liger_kernel/ops/backends/README.md +151 -0
  20. liger_kernel/ops/backends/__init__.py +13 -0
  21. liger_kernel/ops/backends/_ascend/__init__.py +5 -0
  22. liger_kernel/ops/backends/_ascend/ops/__init__.py +15 -0
  23. liger_kernel/ops/backends/registry.py +61 -0
  24. liger_kernel/ops/cross_entropy.py +383 -114
  25. liger_kernel/ops/dyt.py +160 -0
  26. liger_kernel/ops/experimental/embedding.py +141 -0
  27. liger_kernel/ops/experimental/mm_int8int2.py +349 -0
  28. liger_kernel/ops/fused_add_rms_norm.py +416 -0
  29. liger_kernel/ops/fused_linear_cross_entropy.py +346 -132
  30. liger_kernel/ops/fused_linear_jsd.py +228 -0
  31. liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
  32. liger_kernel/ops/geglu.py +66 -64
  33. liger_kernel/ops/group_norm.py +306 -0
  34. liger_kernel/ops/grpo_loss.py +312 -0
  35. liger_kernel/ops/jsd.py +201 -0
  36. liger_kernel/ops/kl_div.py +262 -0
  37. liger_kernel/ops/layer_norm.py +320 -0
  38. liger_kernel/ops/llama4_rope.py +225 -0
  39. liger_kernel/ops/multi_token_attention.py +207 -0
  40. liger_kernel/ops/poly_norm.py +390 -0
  41. liger_kernel/ops/qwen2vl_mrope.py +222 -0
  42. liger_kernel/ops/rms_norm.py +484 -88
  43. liger_kernel/ops/rope.py +122 -117
  44. liger_kernel/ops/softmax.py +201 -0
  45. liger_kernel/ops/sparsemax.py +179 -0
  46. liger_kernel/ops/swiglu.py +68 -65
  47. liger_kernel/ops/tiled_mlp.py +136 -0
  48. liger_kernel/ops/tvd.py +207 -0
  49. liger_kernel/ops/utils.py +82 -3
  50. liger_kernel/transformers/__init__.py +218 -6
  51. liger_kernel/transformers/auto_model.py +38 -0
  52. liger_kernel/transformers/cross_entropy.py +52 -7
  53. liger_kernel/transformers/dyt.py +22 -0
  54. liger_kernel/transformers/experimental/__init__.py +5 -0
  55. liger_kernel/transformers/experimental/embedding.py +26 -0
  56. liger_kernel/transformers/fsdp.py +55 -0
  57. liger_kernel/transformers/functional.py +301 -0
  58. liger_kernel/transformers/fused_add_rms_norm.py +39 -0
  59. liger_kernel/transformers/fused_linear_cross_entropy.py +59 -10
  60. liger_kernel/transformers/fused_linear_jsd.py +95 -0
  61. liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
  62. liger_kernel/transformers/geglu.py +6 -7
  63. liger_kernel/transformers/group_norm.py +50 -0
  64. liger_kernel/transformers/grpo_loss.py +153 -0
  65. liger_kernel/transformers/jsd.py +70 -0
  66. liger_kernel/transformers/kl_div.py +12 -0
  67. liger_kernel/transformers/layer_norm.py +24 -0
  68. liger_kernel/transformers/llama4_rope.py +93 -0
  69. liger_kernel/transformers/model/falcon_h1.py +122 -0
  70. liger_kernel/transformers/model/gemma.py +261 -0
  71. liger_kernel/transformers/model/gemma2.py +283 -0
  72. liger_kernel/transformers/model/gemma3.py +332 -0
  73. liger_kernel/transformers/model/glm4.py +141 -0
  74. liger_kernel/transformers/model/glm4v.py +163 -0
  75. liger_kernel/transformers/model/glm4v_moe.py +172 -0
  76. liger_kernel/transformers/model/gpt_oss.py +211 -0
  77. liger_kernel/transformers/model/hunyuan_v1.py +134 -0
  78. liger_kernel/transformers/model/internvl.py +157 -0
  79. liger_kernel/transformers/model/llama.py +221 -41
  80. liger_kernel/transformers/model/llama4.py +121 -0
  81. liger_kernel/transformers/model/llava.py +344 -0
  82. liger_kernel/transformers/model/loss_utils.py +95 -0
  83. liger_kernel/transformers/model/mistral.py +145 -0
  84. liger_kernel/transformers/model/mixtral.py +293 -0
  85. liger_kernel/transformers/model/mllama.py +269 -0
  86. liger_kernel/transformers/model/olmo2.py +141 -0
  87. liger_kernel/transformers/model/olmo3.py +142 -0
  88. liger_kernel/transformers/model/output_classes.py +147 -0
  89. liger_kernel/transformers/model/paligemma.py +433 -0
  90. liger_kernel/transformers/model/phi3.py +120 -0
  91. liger_kernel/transformers/model/qwen2.py +259 -0
  92. liger_kernel/transformers/model/qwen2_5_vl.py +163 -0
  93. liger_kernel/transformers/model/qwen2_vl.py +159 -0
  94. liger_kernel/transformers/model/qwen3.py +136 -0
  95. liger_kernel/transformers/model/qwen3_moe.py +152 -0
  96. liger_kernel/transformers/model/qwen3_next.py +146 -0
  97. liger_kernel/transformers/model/qwen3_vl.py +150 -0
  98. liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
  99. liger_kernel/transformers/model/smollm3.py +199 -0
  100. liger_kernel/transformers/model/smolvlm.py +158 -0
  101. liger_kernel/transformers/monkey_patch.py +2816 -21
  102. liger_kernel/transformers/multi_token_attention.py +64 -0
  103. liger_kernel/transformers/poly_norm.py +42 -0
  104. liger_kernel/transformers/qwen2vl_mrope.py +20 -0
  105. liger_kernel/transformers/rms_norm.py +75 -5
  106. liger_kernel/transformers/rope.py +47 -3
  107. liger_kernel/transformers/softmax.py +12 -0
  108. liger_kernel/transformers/sparsemax.py +16 -0
  109. liger_kernel/transformers/swiglu.py +62 -6
  110. liger_kernel/transformers/tiled_mlp.py +133 -0
  111. liger_kernel/transformers/trainer/__init__.py +4 -0
  112. liger_kernel/transformers/trainer/orpo_trainer.py +130 -0
  113. liger_kernel/transformers/trainer_integration.py +2 -45
  114. liger_kernel/transformers/tvd.py +13 -0
  115. liger_kernel/triton/__init__.py +1 -3
  116. liger_kernel/triton/monkey_patch.py +1 -5
  117. liger_kernel/utils.py +96 -0
  118. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/METADATA +447 -0
  119. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/NOTICE +58 -0
  120. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/RECORD +124 -0
  121. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/WHEEL +1 -1
  122. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/METADATA +0 -21
  123. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/NOTICE +0 -4
  124. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/RECORD +0 -27
  125. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/LICENSE +0 -0
  126. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/top_level.txt +0 -0
@@ -1,45 +1,2 @@
1
- import logging
2
-
3
- from liger_kernel.transformers.monkey_patch import (
4
- apply_liger_kernel_to_gemma,
5
- apply_liger_kernel_to_llama,
6
- apply_liger_kernel_to_mistral,
7
- apply_liger_kernel_to_mixtral,
8
- )
9
-
10
- logger = logging.getLogger(__name__)
11
-
12
- # Model type corresponds to the keys defined in transformers/models/auto/modeling_auto.py
13
- MODEL_TYPE_TO_APPLY_LIGER_FN = {
14
- "gemma": apply_liger_kernel_to_gemma,
15
- "llama": apply_liger_kernel_to_llama,
16
- "mistral": apply_liger_kernel_to_mistral,
17
- "mixtral": apply_liger_kernel_to_mixtral,
18
- }
19
-
20
-
21
- def _apply_liger_kernel(model_type: str = "", **kwargs) -> None:
22
- """
23
- Applies Liger kernels based on the specified model type. The custom
24
- kernels for the specified model type will be applied with the provided
25
- keyword arguments, otherwise the default configuration will be used.
26
-
27
- Args:
28
- - model_type: the model types as defined in transformers/models/auto/modeling_auto.py
29
- and specified in the model's config.json
30
- - kwargs: keyword arguments that are passed to the corresponding apply_liger_kernel_to_* function.
31
- """
32
-
33
- if not model_type:
34
- logger.info("Model type was not provided. No Liger kernels will be applied.")
35
- return
36
-
37
- if model_type not in MODEL_TYPE_TO_APPLY_LIGER_FN.keys():
38
- logger.info(
39
- f"There are currently no Liger kernels supported for model type: {model_type}."
40
- )
41
- return
42
-
43
- logger.info(f"Applying Liger kernels for model type: {model_type}.")
44
- # Apply the default combination of liger kernels available for the model
45
- MODEL_TYPE_TO_APPLY_LIGER_FN[model_type](**kwargs)
1
+ # To not break HF Trainer integration
2
+ from liger_kernel.transformers.monkey_patch import _apply_liger_kernel # noqa: F401
@@ -0,0 +1,13 @@
1
+ import torch.nn as nn
2
+
3
+ from liger_kernel.ops import LigerTVDLossFunction
4
+
5
+
6
+ class LigerTVDLoss(nn.Module):
7
+ def __init__(self, reduction="batchmean", ignore_index: int = -100):
8
+ super(LigerTVDLoss, self).__init__()
9
+ self.reduction = reduction
10
+ self.ignore_index = ignore_index
11
+
12
+ def forward(self, p, q, shift_labels=None):
13
+ return LigerTVDLossFunction.apply(p, q, shift_labels, self.reduction, self.ignore_index)
@@ -1,3 +1 @@
1
- from liger_kernel.triton.monkey_patch import ( # noqa: F401
2
- apply_liger_triton_cache_manager,
3
- )
1
+ from liger_kernel.triton.monkey_patch import apply_liger_triton_cache_manager # noqa: F401
@@ -1,12 +1,10 @@
1
1
  import os
2
2
  import random
3
3
 
4
- from overrides import override
5
4
  from triton.runtime.cache import FileCacheManager
6
5
 
7
6
 
8
7
  class LigerTritonFileCacheManager(FileCacheManager):
9
- @override
10
8
  def put(self, data, filename, binary=True) -> str:
11
9
  if not self.cache_dir:
12
10
  raise RuntimeError("Could not create or locate cache dir")
@@ -39,6 +37,4 @@ def apply_liger_triton_cache_manager():
39
37
  Experimental feature to get around transient FileNotFoundError in triton compilation.
40
38
  For more details please see https://github.com/triton-lang/triton/pull/4295
41
39
  """
42
- os.environ["TRITON_CACHE_MANAGER"] = (
43
- "liger_kernel.triton.monkey_patch:LigerTritonFileCacheManager"
44
- )
40
+ os.environ["TRITON_CACHE_MANAGER"] = "liger_kernel.triton.monkey_patch:LigerTritonFileCacheManager"
liger_kernel/utils.py ADDED
@@ -0,0 +1,96 @@
1
+ try:
2
+ import peft # noqa: F401
3
+
4
+ PEFT_AVAILABLE = True
5
+ except ImportError:
6
+ PEFT_AVAILABLE = False
7
+
8
+ import torch
9
+
10
+
11
+ def is_peft_available():
12
+ return PEFT_AVAILABLE
13
+
14
+
15
+ def infer_device():
16
+ """
17
+ Get current device name based on available devices
18
+ """
19
+ if torch.cuda.is_available(): # Works for both Nvidia and AMD
20
+ return "cuda"
21
+ # Use Ascend NPU if available (torch.npu)
22
+ elif is_npu_available():
23
+ return "npu"
24
+ # XPU (Intel) if available
25
+ elif torch.xpu.is_available():
26
+ return "xpu"
27
+ else:
28
+ return "cpu"
29
+
30
+
31
+ def is_npu_available() -> bool:
32
+ """Detect Ascend NPU availability."""
33
+ try:
34
+ from transformers.utils import is_torch_npu_available
35
+
36
+ return is_torch_npu_available()
37
+ except Exception:
38
+ return False
39
+
40
+
41
+ def get_npu_multi_processor_count() -> int:
42
+ """Return a heuristic multi-processor count for NPU."""
43
+ if is_npu_available():
44
+ NPU_MULTI_PROCESSOR_COUNT = 48
45
+ dev_props = torch.npu.get_device_properties()
46
+ # The vector_core_num attribute is supported in the torch.npu v7.2.0 release version.
47
+ return dev_props.vector_core_num if hasattr(dev_props, "vector_core_num") else NPU_MULTI_PROCESSOR_COUNT
48
+ # Reasonable default to avoid division by zero
49
+ return 1
50
+
51
+
52
+ def transformers_version_dispatch(
53
+ required_version: str,
54
+ before_fn,
55
+ after_fn,
56
+ before_args: tuple = (),
57
+ after_args: tuple = (),
58
+ before_kwargs: dict = None,
59
+ after_kwargs: dict = None,
60
+ ):
61
+ """
62
+ Dispatches to different functions based on package version comparison.
63
+
64
+ Args:
65
+ required_version: Version to compare against (e.g. "4.48.0")
66
+ before_fn: Function to call if package_version < required_version
67
+ after_fn: Function to call if package_version >= required_version
68
+ before_args: Positional arguments for before_fn
69
+ after_args: Positional arguments for after_fn
70
+ before_kwargs: Keyword arguments for before_fn
71
+ after_kwargs: Keyword arguments for after_fn
72
+
73
+ Returns:
74
+ Result from either before_fn or after_fn
75
+
76
+ Example:
77
+ >>> rotary_emb = transformers_version_dispatch(
78
+ ... "4.48.0",
79
+ ... LlamaRotaryEmbedding,
80
+ ... LlamaRotaryEmbedding,
81
+ ... before_args=(head_dim,),
82
+ ... after_args=(LlamaConfig(head_dim=head_dim),),
83
+ ... before_kwargs={'device': device},
84
+ ... after_kwargs={'device': device}
85
+ ... )
86
+ """
87
+ from packaging import version
88
+ from transformers import __version__ as transformers_version
89
+
90
+ before_kwargs = before_kwargs or {}
91
+ after_kwargs = after_kwargs or {}
92
+
93
+ if version.parse(transformers_version) < version.parse(required_version):
94
+ return before_fn(*before_args, **before_kwargs)
95
+ else:
96
+ return after_fn(*after_args, **after_kwargs)
@@ -0,0 +1,447 @@
1
+ Metadata-Version: 2.1
2
+ Name: liger_kernel_nightly
3
+ Version: 0.6.4.dev20251212103629
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.1
35
+ Provides-Extra: dev
36
+ Requires-Dist: transformers>=4.49.0; extra == "dev"
37
+ Requires-Dist: matplotlib>=3.7.2; extra == "dev"
38
+ Requires-Dist: ruff>=0.12.0; extra == "dev"
39
+ Requires-Dist: pytest>=7.1.2; extra == "dev"
40
+ Requires-Dist: pytest-xdist; extra == "dev"
41
+ Requires-Dist: pytest-cov; extra == "dev"
42
+ Requires-Dist: pytest-asyncio; extra == "dev"
43
+ Requires-Dist: pytest-rerunfailures; extra == "dev"
44
+ Requires-Dist: datasets>=2.19.2; extra == "dev"
45
+ Requires-Dist: seaborn; extra == "dev"
46
+ Requires-Dist: mkdocs-material; extra == "dev"
47
+ Requires-Dist: torchvision>=0.20; extra == "dev"
48
+
49
+ <a name="readme-top"></a>
50
+
51
+ # Liger Kernel: Efficient Triton Kernels for LLM Training
52
+
53
+
54
+ <table style="width: 100%; text-align: center; border-collapse: collapse;">
55
+ <tr>
56
+ <th style="padding: 10px;" colspan="2">Stable</th>
57
+ <th style="padding: 10px;" colspan="2">Nightly</th>
58
+ <th style="padding: 10px;">Discord</th>
59
+ </tr>
60
+ <tr>
61
+ <td style="padding: 10px;">
62
+ <a href="https://pepy.tech/project/liger-kernel">
63
+ <img src="https://static.pepy.tech/badge/liger-kernel" alt="Downloads (Stable)">
64
+ </a>
65
+ </td>
66
+ <td style="padding: 10px;">
67
+ <a href="https://pypi.org/project/liger-kernel">
68
+ <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel?color=green">
69
+ </a>
70
+ </td>
71
+ <td style="padding: 10px;">
72
+ <a href="https://pepy.tech/project/liger-kernel-nightly">
73
+ <img src="https://static.pepy.tech/badge/liger-kernel-nightly" alt="Downloads (Nightly)">
74
+ </a>
75
+ </td>
76
+ <td style="padding: 10px;">
77
+ <a href="https://pypi.org/project/liger-kernel-nightly">
78
+ <img alt="PyPI - Version" src="https://img.shields.io/pypi/v/liger-kernel-nightly?color=green">
79
+ </a>
80
+ </td>
81
+ <td style="padding: 10px;">
82
+ <a href="https://discord.gg/gpumode">
83
+ <img src="https://dcbadge.limes.pink/api/server/gpumode?style=flat" alt="Join Our Discord">
84
+ </a>
85
+ </td>
86
+ </tr>
87
+ </table>
88
+
89
+
90
+
91
+ <img src="https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/logo-banner.png">
92
+
93
+ [Installation](#installation) | [Getting Started](#getting-started) | [Examples](#examples) | [High-level APIs](#high-level-apis) | [Low-level APIs](#low-level-apis) | [Cite our work](#cite-this-work)
94
+
95
+ <details>
96
+ <summary>Latest News 🔥</summary>
97
+
98
+ - [2025/03/06] We release a joint blog post on TorchTune × Liger - [Peak Performance, Minimized Memory: Optimizing torchtune’s performance with torch.compile & Liger Kernel](https://pytorch.org/blog/peak-performance-minimized-memory/)
99
+ - [2024/12/11] We release [v0.5.0](https://github.com/linkedin/Liger-Kernel/releases/tag/v0.5.0): 80% more memory efficient post training losses (DPO, ORPO, CPO, etc)!
100
+ - [2024/12/5] We release LinkedIn Engineering Blog - [Liger-Kernel: Empowering an open source ecosystem of Triton Kernels for Efficient LLM Training](https://www.linkedin.com/blog/engineering/open-source/liger-kernel-open-source-ecosystem-for-efficient-llm-training)
101
+ - [2024/11/6] We release [v0.4.0](https://github.com/linkedin/Liger-Kernel/releases/tag/v0.4.0): Full AMD support, Tech Report, Modal CI, Llama-3.2-Vision!
102
+ - [2024/10/21] We have released the tech report of Liger Kernel on Arxiv: https://arxiv.org/pdf/2410.10989
103
+ - [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!
104
+ - [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)
105
+ - [2024/8/23] Official release: check out our [X post](https://x.com/hsu_byron/status/1827072737673982056)
106
+
107
+ </details>
108
+
109
+
110
+ **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.
111
+
112
+ We've also added optimized Post-Training kernels that deliver **up to 80% memory savings** for alignment and distillation tasks. We support losses like DPO, CPO, ORPO, SimPO, KTO, JSD, and many more. Check out [how we optimize the memory](https://x.com/hsu_byron/status/1866577403918917655).
113
+
114
+ You can view the documentation site for additional installation, usage examples, and API references:https://linkedin.github.io/Liger-Kernel/
115
+
116
+ You can view the Liger Kernel Technical Report: https://openreview.net/forum?id=36SjAIT42G
117
+
118
+ ## Supercharge Your Model with Liger Kernel
119
+
120
+ ![Banner](https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/banner.GIF)
121
+
122
+ 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.
123
+
124
+
125
+ | Speed Up | Memory Reduction |
126
+ |--------------------------|-------------------------|
127
+ | ![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) |
128
+
129
+ > **Note:**
130
+ > - Benchmark conditions: LLaMA 3-8B, Batch Size = 8, Data Type = `bf16`, Optimizer = AdamW, Gradient Checkpointing = True, Distributed Strategy = FSDP1 on 8 A100s.
131
+ > - Hugging Face models start to OOM at a 4K context length, whereas Hugging Face + Liger Kernel scales up to 16K.
132
+
133
+ ## Optimize Post Training with Liger Kernel
134
+
135
+ <p align="center">
136
+ <img src="https://raw.githubusercontent.com/linkedin/Liger-Kernel/main/docs/images/post-training.png" width="50%" alt="Post Training">
137
+ </p>
138
+
139
+ We provide optimized post training kernels like DPO, ORPO, SimPO, and more which can reduce memory usage by up to 80%. You can easily use them as python modules.
140
+
141
+ ```python
142
+ from liger_kernel.chunked_loss import LigerFusedLinearORPOLoss
143
+ orpo_loss = LigerFusedLinearORPOLoss()
144
+ y = orpo_loss(lm_head.weight, x, target)
145
+ ```
146
+
147
+
148
+ ## Examples
149
+
150
+ | **Use Case** | **Description** |
151
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|
152
+ | [**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 |
153
+ | [**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 |
154
+ | [**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 |
155
+ | [**Vision-Language Model SFT**](https://github.com/linkedin/Liger-Kernel/tree/main/examples/huggingface/run_qwen2_vl.sh) | Finetune Qwen2-VL on image-text data using 4 A100s with FSDP |
156
+ | [**Liger ORPO Trainer**](https://github.com/linkedin/Liger-Kernel/blob/main/examples/alignment/run_orpo.py) | Align Llama 3.2 using Liger ORPO Trainer with FSDP with 50% memory reduction |
157
+
158
+ ## Key Features
159
+
160
+ - **Ease of use:** Simply patch your Hugging Face model with one line of code, or compose your own model using our Liger Kernel modules.
161
+ - **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.
162
+ - **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.
163
+ - **Lightweight:** Liger Kernel has minimal dependencies, requiring only Torch and Triton—no extra libraries needed! Say goodbye to dependency headaches!
164
+ - **Multi-GPU supported:** Compatible with multi-GPU setups (PyTorch FSDP, DeepSpeed, DDP, etc.).
165
+ - **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), [oumi](https://github.com/oumi-ai/oumi/tree/main)
166
+
167
+ ## Installation
168
+
169
+ ### Dependencies
170
+
171
+ #### CUDA
172
+
173
+ - `torch >= 2.1.2`
174
+ - `triton >= 2.3.0`
175
+
176
+ #### ROCm
177
+
178
+ - `torch >= 2.5.0` Install according to the instruction in Pytorch official webpage.
179
+ - `triton >= 3.0.0` Install from pypi. (e.g. `pip install triton==3.0.0`)
180
+
181
+ ```bash
182
+ pip install -e .[dev]
183
+ pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.3/
184
+ ```
185
+
186
+ ### Optional Dependencies
187
+
188
+ - `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.
189
+
190
+ > **Note:**
191
+ > Our kernels inherit the full spectrum of hardware compatibility offered by [Triton](https://github.com/triton-lang/triton).
192
+
193
+ To install the stable version:
194
+
195
+ ```bash
196
+ $ pip install liger-kernel
197
+ ```
198
+
199
+ To install the nightly version:
200
+
201
+ ```bash
202
+ $ pip install liger-kernel-nightly
203
+ ```
204
+
205
+ To install from source:
206
+
207
+ ```bash
208
+ git clone https://github.com/linkedin/Liger-Kernel.git
209
+ cd Liger-Kernel
210
+
211
+ # Install Default Dependencies
212
+ # Setup.py will detect whether you are using AMD or NVIDIA
213
+ pip install -e .
214
+
215
+ # Setup Development Dependencies
216
+ pip install -e ".[dev]"
217
+
218
+ # NOTE -> For AMD users only
219
+ pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.3/
220
+ ```
221
+
222
+
223
+ ## Getting Started
224
+
225
+ There are a couple of ways to apply Liger kernels, depending on the level of customization required.
226
+
227
+ ### 1. Use AutoLigerKernelForCausalLM
228
+
229
+ 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.
230
+
231
+ ```python
232
+ from liger_kernel.transformers import AutoLigerKernelForCausalLM
233
+
234
+ # This AutoModel wrapper class automatically monkey-patches the
235
+ # model with the optimized Liger kernels if the model is supported.
236
+ model = AutoLigerKernelForCausalLM.from_pretrained("path/to/some/model")
237
+ ```
238
+
239
+ ### 2. Apply Model-Specific Patching APIs
240
+
241
+ Using the [patching APIs](#patching), you can swap Hugging Face models with optimized Liger Kernels.
242
+
243
+ ```python
244
+ import transformers
245
+ from liger_kernel.transformers import apply_liger_kernel_to_llama
246
+
247
+ # 1a. Adding this line automatically monkey-patches the model with the optimized Liger kernels
248
+ apply_liger_kernel_to_llama()
249
+
250
+ # 1b. You could alternatively specify exactly which kernels are applied
251
+ apply_liger_kernel_to_llama(
252
+ rope=True,
253
+ swiglu=True,
254
+ cross_entropy=True,
255
+ fused_linear_cross_entropy=False,
256
+ rms_norm=False
257
+ )
258
+
259
+ # 2. Instantiate patched model
260
+ model = transformers.AutoModelForCausalLM("path/to/llama/model")
261
+ ```
262
+
263
+ ### 3. Compose Your Own Model
264
+
265
+ You can take individual [kernels](https://github.com/linkedin/Liger-Kernel?tab=readme-ov-file#model-kernels) to compose your models.
266
+
267
+ ```python
268
+ from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
269
+ import torch.nn as nn
270
+ import torch
271
+
272
+ model = nn.Linear(128, 256).cuda()
273
+
274
+ # fuses linear + cross entropy layers together and performs chunk-by-chunk computation to reduce memory
275
+ loss_fn = LigerFusedLinearCrossEntropyLoss()
276
+
277
+ input = torch.randn(4, 128, requires_grad=True, device="cuda")
278
+ target = torch.randint(256, (4, ), device="cuda")
279
+
280
+ loss = loss_fn(model.weight, input, target)
281
+ loss.backward()
282
+ ```
283
+
284
+ ## High-level APIs
285
+
286
+ ### AutoModel
287
+
288
+ | **AutoModel Variant** | **API** |
289
+ |-----------|---------|
290
+ | AutoModelForCausalLM | `liger_kernel.transformers.AutoLigerKernelForCausalLM` |
291
+
292
+
293
+ ### Patching
294
+
295
+ | **Model** | **API** | **Supported Operations** |
296
+ |-------------|--------------------------------------------------------------|-------------------------------------------------------------------------|
297
+ | Llama4 (Text) & (Multimodal) | `liger_kernel.transformers.apply_liger_kernel_to_llama4` | RMSNorm, LayerNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
298
+ | LLaMA 2 & 3 | `liger_kernel.transformers.apply_liger_kernel_to_llama` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
299
+ | LLaMA 3.2-Vision | `liger_kernel.transformers.apply_liger_kernel_to_mllama` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
300
+ | Mistral | `liger_kernel.transformers.apply_liger_kernel_to_mistral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
301
+ | Mixtral | `liger_kernel.transformers.apply_liger_kernel_to_mixtral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
302
+ | Gemma1 | `liger_kernel.transformers.apply_liger_kernel_to_gemma` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
303
+ | Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
304
+ | Gemma3 (Text) | `liger_kernel.transformers.apply_liger_kernel_to_gemma3_text` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
305
+ | Gemma3 (Multimodal) | `liger_kernel.transformers.apply_liger_kernel_to_gemma3` | LayerNorm, RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
306
+ | Paligemma, Paligemma2, & Paligemma2 Mix | `liger_kernel.transformers.apply_liger_kernel_to_paligemma` | LayerNorm, RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
307
+ | Qwen2, Qwen2.5, & QwQ | `liger_kernel.transformers.apply_liger_kernel_to_qwen2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
308
+ | Qwen2-VL, & QVQ | `liger_kernel.transformers.apply_liger_kernel_to_qwen2_vl` | RMSNorm, LayerNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
309
+ | Qwen2.5-VL | `liger_kernel.transformers.apply_liger_kernel_to_qwen2_5_vl` | RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
310
+ | Qwen3 | `liger_kernel.transformers.apply_liger_kernel_to_qwen3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
311
+ | Qwen3 MoE | `liger_kernel.transformers.apply_liger_kernel_to_qwen3_moe` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
312
+ | Phi3 & Phi3.5 | `liger_kernel.transformers.apply_liger_kernel_to_phi3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
313
+ | Granite 3.0 & 3.1 | `liger_kernel.transformers.apply_liger_kernel_to_granite` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss |
314
+ | OLMo2 | `liger_kernel.transformers.apply_liger_kernel_to_olmo2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
315
+ | Olmo3 | `liger_kernel.transformers.apply_liger_kernel_to_olmo3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
316
+ | GLM-4 | `liger_kernel.transformers.apply_liger_kernel_to_glm4` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
317
+ | GPT-OSS | `liger_kernel.transformers.apply_liger_kernel_to_gpt_oss` | RoPE, RMSNorm, CrossEntropyLoss, FusedLinearCrossEntropy |
318
+ | InternVL3 | `liger_kernel.transformers.apply_liger_kernel_to_internvl` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
319
+ | HunyuanV1 | `liger_kernel.transformers.apply_liger_kernel_to_hunyuan_v1_dense` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
320
+ | HunyuanV1 MoE | `liger_kernel.transformers.apply_liger_kernel_to_hunyuan_v1_moe` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
321
+
322
+
323
+ ## Low-level APIs
324
+
325
+ - `Fused Linear` kernels combine linear layers with losses, reducing memory usage by up to 80% - ideal for HBM-constrained workloads.
326
+ - Other kernels use fusion and in-place techniques for memory and performance optimization.
327
+
328
+ ### Model Kernels
329
+
330
+ | **Kernel** | **API** |
331
+ |---------------------------------|-------------------------------------------------------------|
332
+ | RMSNorm | `liger_kernel.transformers.LigerRMSNorm` |
333
+ | LayerNorm | `liger_kernel.transformers.LigerLayerNorm` |
334
+ | RoPE | `liger_kernel.transformers.liger_rotary_pos_emb` |
335
+ | SwiGLU | `liger_kernel.transformers.LigerSwiGLUMLP` |
336
+ | GeGLU | `liger_kernel.transformers.LigerGEGLUMLP` |
337
+ | CrossEntropy | `liger_kernel.transformers.LigerCrossEntropyLoss` |
338
+ | Fused Linear CrossEntropy | `liger_kernel.transformers.LigerFusedLinearCrossEntropyLoss`|
339
+ | Multi Token Attention | `liger_kernel.transformers.LigerMultiTokenAttention` |
340
+ | Softmax | `liger_kernel.transformers.LigerSoftmax` |
341
+ | Sparsemax | `liger_kernel.transformers.LigerSparsemax` |
342
+
343
+
344
+ ### Alignment Kernels
345
+
346
+ | **Kernel** | **API** |
347
+ |---------------------------------|-------------------------------------------------------------|
348
+ | Fused Linear CPO Loss | `liger_kernel.chunked_loss.LigerFusedLinearCPOLoss` |
349
+ | Fused Linear DPO Loss | `liger_kernel.chunked_loss.LigerFusedLinearDPOLoss` |
350
+ | Fused Linear ORPO Loss | `liger_kernel.chunked_loss.LigerFusedLinearORPOLoss` |
351
+ | Fused Linear SimPO Loss | `liger_kernel.chunked_loss.LigerFusedLinearSimPOLoss` |
352
+ | Fused Linear KTO Loss | `liger_kernel.chunked_loss.LigerFusedLinearKTOLoss` |
353
+
354
+ ### Distillation Kernels
355
+
356
+ | **Kernel** | **API** |
357
+ |---------------------------------|-------------------------------------------------------------|
358
+ | KLDivergence | `liger_kernel.transformers.LigerKLDIVLoss` |
359
+ | JSD | `liger_kernel.transformers.LigerJSD` |
360
+ | Fused Linear JSD | `liger_kernel.transformers.LigerFusedLinearJSD` |
361
+ | TVD | `liger_kernel.transformers.LigerTVDLoss` |
362
+
363
+ ### Experimental Kernels
364
+
365
+ | **Kernel** | **API** |
366
+ |---------------------------------|-------------------------------------------------------------|
367
+ | Embedding | `liger_kernel.transformers.experimental.LigerEmbedding` |
368
+ | Matmul int2xint8 | `liger_kernel.transformers.experimental.matmul` |
369
+
370
+
371
+ ## Contributing, Acknowledgements, and License
372
+
373
+ - [Contributing Guidelines](https://github.com/linkedin/Liger-Kernel/blob/main/docs/contributing.md)
374
+ - [Acknowledgements](https://github.com/linkedin/Liger-Kernel/blob/main/docs/acknowledgement.md)
375
+ - [License Information](https://github.com/linkedin/Liger-Kernel/blob/main/docs/license.md)
376
+
377
+ ## Sponsorship and Collaboration
378
+
379
+ - [Glows.ai](https://platform.glows.ai/): Sponsoring NVIDIA GPUs for our open source developers.
380
+ - [AMD](https://www.amd.com/en.html): Providing AMD GPUs for our AMD CI.
381
+ - [Intel](https://www.intel.com/): Providing Intel GPUs for our Intel CI.
382
+ - [Modal](https://modal.com/): Free 3000 credits from GPU MODE IRL for our NVIDIA CI.
383
+ - [EmbeddedLLM](https://embeddedllm.com/): Making Liger Kernel run fast and stable on AMD.
384
+ - [HuggingFace](https://huggingface.co/): Integrating Liger Kernel into Hugging Face Transformers and TRL.
385
+ - [Lightning AI](https://lightning.ai/): Integrating Liger Kernel into Lightning Thunder.
386
+ - [Axolotl](https://axolotl.ai/): Integrating Liger Kernel into Axolotl.
387
+ - [Llama-Factory](https://github.com/hiyouga/LLaMA-Factory): Integrating Liger Kernel into Llama-Factory.
388
+
389
+
390
+ ## CI status
391
+
392
+ <table style="width: 100%; text-align: center; border-collapse: collapse;">
393
+ <tr>
394
+ <th style="padding: 10px;">Build</th>
395
+ </tr>
396
+ <tr>
397
+ <td style="padding: 10px;">
398
+ <div style="display: block;">
399
+ <a href="https://github.com/linkedin/Liger-Kernel/actions/workflows/nvi-ci.yml">
400
+ <img src="https://github.com/linkedin/Liger-Kernel/actions/workflows/nvi-ci.yml/badge.svg?branch=main&event=push" alt="Build">
401
+ </a>
402
+ </div>
403
+ <div style="display: block;">
404
+ <a href="https://github.com/linkedin/Liger-Kernel/actions/workflows/amd-ci.yml">
405
+ <img src="https://github.com/linkedin/Liger-Kernel/actions/workflows/amd-ci.yml/badge.svg?branch=main&event=push" alt="Build">
406
+ </a>
407
+ </div>
408
+ <div style="display: block;">
409
+ <a href="https://github.com/linkedin/Liger-Kernel/actions/workflows/intel-ci.yml">
410
+ <img src="https://github.com/linkedin/Liger-Kernel/actions/workflows/intel-ci.yml/badge.svg?branch=main&event=push" alt="Build">
411
+ </a>
412
+ </div>
413
+ </td>
414
+ </tr>
415
+ </table>
416
+
417
+
418
+
419
+ ## Contact
420
+
421
+ - For issues, create a Github ticket in this repository
422
+ - For open discussion, join [our discord channel on GPUMode](https://discord.com/channels/1189498204333543425/1275130785933951039)
423
+ - For formal collaboration, send an email to Yanning Chen(yannchen@linkedin.com) and Zhipeng Wang(zhipwang@linkedin.com)
424
+
425
+ ## Cite this work
426
+
427
+ Biblatex entry:
428
+ ```bib
429
+ @inproceedings{
430
+ hsu2025ligerkernel,
431
+ title={Liger-Kernel: Efficient Triton Kernels for {LLM} Training},
432
+ author={Pin-Lun Hsu and Yun Dai and Vignesh Kothapalli and Qingquan Song and Shao Tang and Siyu Zhu and Steven Shimizu and Shivam Sahni and Haowen Ning and Yanning Chen and Zhipeng Wang},
433
+ booktitle={Championing Open-source DEvelopment in ML Workshop @ ICML25},
434
+ year={2025},
435
+ url={https://openreview.net/forum?id=36SjAIT42G}
436
+ }
437
+ ```
438
+
439
+ ## Star History
440
+ [![Star History Chart](https://api.star-history.com/svg?repos=linkedin/Liger-Kernel&type=Date)](https://www.star-history.com/#linkedin/Liger-Kernel&Date)
441
+
442
+ <p align="right" style="font-size: 14px; color: #555; margin-top: 20px;">
443
+ <a href="#readme-top" style="text-decoration: none; color: #007bff; font-weight: bold;">
444
+ ↑ Back to Top ↑
445
+ </a>
446
+ </p>
447
+