liger-kernel 0.4.0__py3-none-any.whl → 0.4.2__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.
@@ -8,12 +8,17 @@ from packaging import version
8
8
  from transformers import PreTrainedModel
9
9
 
10
10
  from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss
11
+ from liger_kernel.transformers.functional import liger_cross_entropy
11
12
  from liger_kernel.transformers.geglu import LigerGEGLUMLP
12
13
  from liger_kernel.transformers.layer_norm import LigerLayerNorm
13
14
  from liger_kernel.transformers.model.gemma import lce_forward as gemma_lce_forward
14
15
  from liger_kernel.transformers.model.gemma import (
15
16
  lce_forward_deprecated as gemma_lce_forward_deprecated,
16
17
  )
18
+ from liger_kernel.transformers.model.gemma2 import lce_forward as gemma2_lce_forward
19
+ from liger_kernel.transformers.model.gemma2 import (
20
+ lce_forward_deprecated as gemma2_lce_forward_deprected,
21
+ )
17
22
  from liger_kernel.transformers.model.llama import lce_forward as llama_lce_forward
18
23
  from liger_kernel.transformers.model.llama import (
19
24
  lce_forward_deprecated as llama_lce_forward_deprecated,
@@ -51,12 +56,15 @@ def _bind_method_to_module(module, method_name: str, new_method: Callable):
51
56
  module.__dict__[method_name] = new_method.__get__(module, module.__class__)
52
57
 
53
58
 
54
- def _patch_rms_norm_module(module, offset=0.0, eps=1e-6, casting_mode="llama"):
59
+ def _patch_rms_norm_module(
60
+ module, offset=0.0, eps=1e-6, casting_mode="llama", in_place=True
61
+ ):
55
62
  module.offset = offset
56
63
  module.casting_mode = casting_mode
57
64
  module.variance_epsilon = (
58
65
  getattr(module, "variance_epsilon", None) or getattr(module, "eps", None) or eps
59
66
  )
67
+ module.in_place = in_place
60
68
  _bind_method_to_module(module, "forward", LigerRMSNorm.forward)
61
69
  _bind_method_to_module(module, "extra_repr", LigerRMSNorm.extra_repr)
62
70
 
@@ -99,6 +107,7 @@ def apply_liger_kernel_to_llama(
99
107
  ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
100
108
 
101
109
  from transformers.models.llama import modeling_llama
110
+ from transformers.models.llama.modeling_llama import LlamaModel
102
111
 
103
112
  if rope:
104
113
  modeling_llama.apply_rotary_pos_emb = liger_rotary_pos_emb
@@ -106,8 +115,16 @@ def apply_liger_kernel_to_llama(
106
115
  modeling_llama.LlamaRMSNorm = LigerRMSNorm
107
116
  if swiglu:
108
117
  modeling_llama.LlamaMLP = LigerSwiGLUMLP
118
+
109
119
  if cross_entropy:
110
- modeling_llama.CrossEntropyLoss = LigerCrossEntropyLoss
120
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
121
+ from transformers.loss.loss_utils import nn
122
+
123
+ nn.functional.cross_entropy = liger_cross_entropy
124
+ else:
125
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
126
+ modeling_llama.CrossEntropyLoss = LigerCrossEntropyLoss
127
+
111
128
  if fused_linear_cross_entropy:
112
129
  if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
113
130
  modeling_llama.LlamaForCausalLM.forward = llama_lce_forward
@@ -119,15 +136,8 @@ def apply_liger_kernel_to_llama(
119
136
  # The model instance already exists, so we need to additionally patch the
120
137
  # instance variables that reference already-instantiated modules (e.g. LlamaRMSNorm or LlamaMLP)
121
138
 
122
- if hasattr(model, "model"):
123
- # The case for LlamaForCausalLM or LlamaForSequenceClassification, for example
124
- base_model = model.model
125
- elif hasattr(model, "transformer"):
126
- # LlamaForQuestionAnswering uses "transformer" instead of "model"
127
- base_model = model.transformer
128
- else:
129
- # Direct LlamaModel
130
- base_model = model
139
+ # get the base model from the model instance
140
+ base_model: LlamaModel = getattr(model, model.base_model_prefix, model)
131
141
 
132
142
  if rms_norm:
133
143
  _patch_rms_norm_module(base_model.norm)
@@ -194,7 +204,13 @@ def apply_liger_kernel_to_mllama(
194
204
  if swiglu:
195
205
  modeling_mllama.MllamaTextMLP = LigerSwiGLUMLP
196
206
  if cross_entropy:
197
- modeling_mllama.CrossEntropyLoss = LigerCrossEntropyLoss
207
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
208
+ from transformers.loss.loss_utils import nn
209
+
210
+ nn.functional.cross_entropy = liger_cross_entropy
211
+ else:
212
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
213
+ modeling_mllama.CrossEntropyLoss = LigerCrossEntropyLoss
198
214
  if fused_linear_cross_entropy:
199
215
  if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
200
216
  modeling_mllama.MllamaForCausalLM.forward = mllama_lce_forward
@@ -258,7 +274,7 @@ def apply_liger_kernel_to_mistral(
258
274
  Apply Liger kernels to replace original implementation in HuggingFace Mistral models
259
275
 
260
276
  Args:
261
- rope (bool): Whether to apply Liger's rotary position embedding. Default is True.
277
+ rope (bool): Whether to apply Liger's rotary position embedding. Default is False.
262
278
  cross_entropy (bool): Whether to apply Liger's cross entropy loss. Default is True.
263
279
  fused_linear_cross_entropy (bool):
264
280
  Whether to apply Liger's fused linear cross entropy loss. Default is True.
@@ -275,6 +291,7 @@ def apply_liger_kernel_to_mistral(
275
291
  ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
276
292
 
277
293
  from transformers.models.mistral import modeling_mistral
294
+ from transformers.models.mistral.modeling_mistral import MistralModel
278
295
 
279
296
  if rope:
280
297
  modeling_mistral.apply_rotary_pos_emb = liger_rotary_pos_emb
@@ -291,12 +308,8 @@ def apply_liger_kernel_to_mistral(
291
308
  # The model instance already exists, so we need to additionally patch the
292
309
  # instance variables that reference already-instantiated modules
293
310
 
294
- if hasattr(model, "model"):
295
- # The case for MistralForCausalLM, MistralForTokenClassification for example
296
- base_model = model.model
297
- else:
298
- # Direct MistralModel
299
- base_model = model
311
+ # get the base model from the model instance
312
+ base_model: MistralModel = getattr(model, model.base_model_prefix, model)
300
313
 
301
314
  if rms_norm:
302
315
  _patch_rms_norm_module(base_model.norm)
@@ -340,13 +353,21 @@ def apply_liger_kernel_to_mixtral(
340
353
  ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
341
354
 
342
355
  from transformers.models.mixtral import modeling_mixtral
356
+ from transformers.models.mixtral.modeling_mixtral import MixtralModel
343
357
 
344
358
  if rope:
345
359
  modeling_mixtral.apply_rotary_pos_emb = liger_rotary_pos_emb
346
360
  if rms_norm:
347
361
  modeling_mixtral.MixtralRMSNorm = LigerRMSNorm
348
362
  if cross_entropy:
349
- modeling_mixtral.CrossEntropyLoss = LigerCrossEntropyLoss
363
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
364
+ from transformers.loss.loss_utils import nn
365
+
366
+ nn.functional.cross_entropy = liger_cross_entropy
367
+ else:
368
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
369
+ modeling_mixtral.CrossEntropyLoss = LigerCrossEntropyLoss
370
+
350
371
  if fused_linear_cross_entropy:
351
372
  if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
352
373
  modeling_mixtral.MixtralForCausalLM.forward = mixtral_lce_forward
@@ -360,12 +381,8 @@ def apply_liger_kernel_to_mixtral(
360
381
  # The model instance already exists, so we need to additionally patch the
361
382
  # instance variables that reference already-instantiated modules
362
383
 
363
- if hasattr(model, "model"):
364
- # The case for MixtralForCausalLM, MixtralForTokenClassification for example
365
- base_model = model.model
366
- else:
367
- # Direct MixtralModel
368
- base_model = model
384
+ # get the base model from the model instance
385
+ base_model: MixtralModel = getattr(model, model.base_model_prefix, model)
369
386
 
370
387
  if rms_norm:
371
388
  _patch_rms_norm_module(base_model.norm)
@@ -410,6 +427,7 @@ def apply_liger_kernel_to_gemma(
410
427
  ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
411
428
 
412
429
  from transformers.models.gemma import modeling_gemma
430
+ from transformers.models.gemma.modeling_gemma import GemmaModel
413
431
 
414
432
  # https://github.com/huggingface/transformers/blob/v4.44.2/src/transformers/models/gemma/modeling_gemma.py#L109
415
433
  LigerRMSNormForGemma = partial(
@@ -424,7 +442,13 @@ def apply_liger_kernel_to_gemma(
424
442
  if rms_norm:
425
443
  modeling_gemma.GemmaRMSNorm = LigerRMSNormForGemma
426
444
  if cross_entropy:
427
- modeling_gemma.CrossEntropyLoss = LigerCrossEntropyLoss
445
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
446
+ from transformers.loss.loss_utils import nn
447
+
448
+ nn.functional.cross_entropy = liger_cross_entropy
449
+ else:
450
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
451
+ modeling_gemma.CrossEntropyLoss = LigerCrossEntropyLoss
428
452
  if geglu:
429
453
  modeling_gemma.GemmaMLP = LigerGEGLUMLP
430
454
  if fused_linear_cross_entropy:
@@ -438,12 +462,8 @@ def apply_liger_kernel_to_gemma(
438
462
  # The model instance already exists, so we need to additionally patch the
439
463
  # instance variables that reference already-instantiated modules
440
464
 
441
- if hasattr(model, "model"):
442
- # The case for GemmaForCausalLM, GemmaForTokenClassification for example
443
- base_model = model.model
444
- else:
445
- # Direct GemmaModel
446
- base_model = model
465
+ # get the base model from the model instance
466
+ base_model: GemmaModel = getattr(model, model.base_model_prefix, model)
447
467
 
448
468
  if rms_norm:
449
469
  _patch_rms_norm_module_for_gemma(base_model.norm)
@@ -460,7 +480,8 @@ def apply_liger_kernel_to_gemma(
460
480
 
461
481
  def apply_liger_kernel_to_gemma2(
462
482
  rope: bool = True,
463
- cross_entropy: bool = True,
483
+ cross_entropy: bool = False,
484
+ fused_linear_cross_entropy: bool = True,
464
485
  rms_norm: bool = True,
465
486
  geglu: bool = True,
466
487
  model: PreTrainedModel = None,
@@ -471,19 +492,28 @@ def apply_liger_kernel_to_gemma2(
471
492
 
472
493
  Args:
473
494
  rope (bool): Whether to apply Liger's rotary position embedding. Default is True.
474
- cross_entropy (bool): Whether to apply Liger's cross entropy loss. Default is True.
495
+ cross_entropy (bool): Whether to apply Liger's cross entropy loss. Default is False.
496
+ fused_linear_cross_entropy (bool):
497
+ Whether to apply Liger's fused linear cross entropy loss. Default is True.
498
+ `cross_entropy` and `fused_linear_cross_entropy` cannot both be True.
499
+ If `fused_linear_cross_entropy` is True, the logits will not be materialized but more memory efficient.
475
500
  rms_norm (bool): Whether to apply Liger's RMSNorm. Default is True.
476
501
  geglu (bool): Whether to apply Liger's GeGLU MLP. Default is True.
477
502
  model (PreTrainedModel): The model instance to apply Liger kernels to, if the model has already been
478
503
  loaded. Default is None.
479
504
  """
505
+ assert not (
506
+ cross_entropy and fused_linear_cross_entropy
507
+ ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
508
+
480
509
  from transformers.models.gemma2 import modeling_gemma2
510
+ from transformers.models.gemma2.modeling_gemma2 import Gemma2Model
481
511
 
482
512
  LigerRMSNormForGemma2 = partial(
483
- LigerRMSNorm, offset=1.0, casting_mode="gemma", init_fn="zeros"
513
+ LigerRMSNorm, offset=1.0, casting_mode="gemma", init_fn="zeros", in_place=False
484
514
  )
485
515
  _patch_rms_norm_module_for_gemma2 = partial(
486
- _patch_rms_norm_module, offset=1.0, casting_mode="gemma"
516
+ _patch_rms_norm_module, offset=1.0, casting_mode="gemma", in_place=False
487
517
  )
488
518
 
489
519
  if rope:
@@ -492,7 +522,19 @@ def apply_liger_kernel_to_gemma2(
492
522
  # https://github.com/huggingface/transformers/blob/v4.44.2/src/transformers/models/gemma/modeling_gemma.py#L109
493
523
  modeling_gemma2.Gemma2RMSNorm = LigerRMSNormForGemma2
494
524
  if cross_entropy:
495
- modeling_gemma2.CrossEntropyLoss = LigerCrossEntropyLoss
525
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
526
+ from transformers.loss.loss_utils import nn
527
+
528
+ nn.functional.cross_entropy = liger_cross_entropy
529
+ else:
530
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
531
+ modeling_gemma2.CrossEntropyLoss = LigerCrossEntropyLoss
532
+ if fused_linear_cross_entropy:
533
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
534
+ modeling_gemma2.Gemma2ForCausalLM.forward = gemma2_lce_forward
535
+ else:
536
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
537
+ modeling_gemma2.Gemma2ForCausalLM.forward = gemma2_lce_forward_deprected
496
538
  if geglu:
497
539
  modeling_gemma2.Gemma2MLP = LigerGEGLUMLP
498
540
 
@@ -500,12 +542,8 @@ def apply_liger_kernel_to_gemma2(
500
542
  # The model instance already exists, so we need to additionally patch the
501
543
  # instance variables that reference already-instantiated modules
502
544
 
503
- if hasattr(model, "model"):
504
- # The case for Gemma2ForCausalLM, Gemma2ForTokenClassification for example
505
- base_model = model.model
506
- else:
507
- # Direct Gemma2Model
508
- base_model = model
545
+ # get the base model from the model instance
546
+ base_model: Gemma2Model = getattr(model, model.base_model_prefix, model)
509
547
 
510
548
  if rms_norm:
511
549
  _patch_rms_norm_module_for_gemma2(base_model.norm)
@@ -556,13 +594,21 @@ def apply_liger_kernel_to_qwen2(
556
594
  ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
557
595
 
558
596
  from transformers.models.qwen2 import modeling_qwen2
597
+ from transformers.models.qwen2.modeling_qwen2 import Qwen2Model
559
598
 
560
599
  if rope:
561
600
  modeling_qwen2.apply_rotary_pos_emb = liger_rotary_pos_emb
562
601
  if rms_norm:
563
602
  modeling_qwen2.Qwen2RMSNorm = LigerRMSNorm
603
+
564
604
  if cross_entropy:
565
- modeling_qwen2.CrossEntropyLoss = LigerCrossEntropyLoss
605
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
606
+ from transformers.loss.loss_utils import nn
607
+
608
+ nn.functional.cross_entropy = liger_cross_entropy
609
+ else:
610
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
611
+ modeling_qwen2.CrossEntropyLoss = LigerCrossEntropyLoss
566
612
 
567
613
  # import pdb; pdb.set_trace()
568
614
  if fused_linear_cross_entropy:
@@ -580,12 +626,8 @@ def apply_liger_kernel_to_qwen2(
580
626
  # The model instance already exists, so we need to additionally patch the
581
627
  # instance variables that reference already-instantiated modules
582
628
 
583
- if hasattr(model, "model"):
584
- # The case for Qwen2ForCausalLM, Qwen2ForTokenClassification for example
585
- base_model = model.model
586
- else:
587
- # Direct Qwen2Model
588
- base_model = model
629
+ # get the base model from the model instance
630
+ base_model: Qwen2Model = getattr(model, model.base_model_prefix, model)
589
631
 
590
632
  if rms_norm:
591
633
  _patch_rms_norm_module(base_model.norm)
@@ -630,6 +672,7 @@ def apply_liger_kernel_to_qwen2_vl(
630
672
  ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
631
673
 
632
674
  from transformers.models.qwen2_vl import modeling_qwen2_vl
675
+ from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLModel
633
676
 
634
677
  from liger_kernel.transformers.model.qwen2_vl import (
635
678
  lce_forward as qwen2_vl_lce_forward,
@@ -653,12 +696,8 @@ def apply_liger_kernel_to_qwen2_vl(
653
696
  # The model instance already exists, so we need to additionally patch the
654
697
  # instance variables that reference already-instantiated modules
655
698
 
656
- if hasattr(model, "model"):
657
- # The case for Qwen2VLForConditionalGeneration.
658
- base_model = model.model
659
- else:
660
- # Direct Qwen2VLModel
661
- base_model = model
699
+ # get the base model from the model instance
700
+ base_model: Qwen2VLModel = getattr(model, model.base_model_prefix, model)
662
701
 
663
702
  if hasattr(model, "visual"):
664
703
  # Patch Qwen2VisionTransformerPretrainedModel
@@ -707,6 +746,7 @@ def apply_liger_kernel_to_phi3(
707
746
  ), "cross_entropy and fused_linear_cross_entropy cannot both be True."
708
747
 
709
748
  from transformers.models.phi3 import modeling_phi3
749
+ from transformers.models.phi3.modeling_phi3 import Phi3Model
710
750
 
711
751
  if rope:
712
752
  modeling_phi3.apply_rotary_pos_emb = liger_rotary_pos_emb # Same as Gemma
@@ -715,7 +755,13 @@ def apply_liger_kernel_to_phi3(
715
755
  if swiglu:
716
756
  modeling_phi3.Phi3MLP = LigerPhi3SwiGLUMLP
717
757
  if cross_entropy:
718
- modeling_phi3.CrossEntropyLoss = LigerCrossEntropyLoss
758
+ if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
759
+ from transformers.loss.loss_utils import nn
760
+
761
+ nn.functional.cross_entropy = liger_cross_entropy
762
+ else:
763
+ logger.warning(TRANSFORMER_DEPRECATION_WARNING)
764
+ modeling_phi3.CrossEntropyLoss = LigerCrossEntropyLoss
719
765
  if fused_linear_cross_entropy:
720
766
  if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
721
767
  modeling_phi3.Phi3ForCausalLM.forward = phi3_lce_forward
@@ -727,12 +773,8 @@ def apply_liger_kernel_to_phi3(
727
773
  # The model instance already exists, so we need to additionally patch the
728
774
  # instance variables that reference already-instantiated modules
729
775
 
730
- if hasattr(model, "model"):
731
- # The case for Phi3ForCausalLM, Phi3ForTokenClassification for example
732
- base_model = model.model
733
- else:
734
- # Direct Phi3Model
735
- base_model = model
776
+ # get the base model from the model instance
777
+ base_model: Phi3Model = getattr(model, model.base_model_prefix, model)
736
778
 
737
779
  if rms_norm:
738
780
  _patch_rms_norm_module(base_model.norm)
@@ -6,7 +6,13 @@ from liger_kernel.ops.rms_norm import LigerRMSNormFunction
6
6
 
7
7
  class LigerRMSNorm(nn.Module):
8
8
  def __init__(
9
- self, hidden_size, eps=1e-6, offset=0.0, casting_mode="llama", init_fn="ones"
9
+ self,
10
+ hidden_size,
11
+ eps=1e-6,
12
+ offset=0.0,
13
+ casting_mode="llama",
14
+ init_fn="ones",
15
+ in_place=True,
10
16
  ):
11
17
  super().__init__()
12
18
  assert init_fn in [
@@ -16,10 +22,11 @@ class LigerRMSNorm(nn.Module):
16
22
  self.weight = nn.Parameter(
17
23
  torch.ones(hidden_size) if init_fn == "ones" else torch.zeros(hidden_size)
18
24
  )
19
- self.variance_epsilon, self.offset, self.casting_mode = (
25
+ self.variance_epsilon, self.offset, self.casting_mode, self.in_place = (
20
26
  eps,
21
27
  offset,
22
28
  casting_mode,
29
+ in_place,
23
30
  )
24
31
 
25
32
  def forward(self, hidden_states):
@@ -29,7 +36,8 @@ class LigerRMSNorm(nn.Module):
29
36
  self.variance_epsilon,
30
37
  self.offset,
31
38
  self.casting_mode,
39
+ self.in_place,
32
40
  )
33
41
 
34
42
  def extra_repr(self):
35
- return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}, offset={self.offset}"
43
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}, offset={self.offset}, in_place={self.in_place}"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: liger_kernel
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: Efficient Triton kernels for LLM Training
5
5
  License: BSD 2-CLAUSE LICENSE
6
6
  Copyright 2024 LinkedIn Corporation
@@ -99,7 +99,8 @@ Requires-Dist: transformers~=4.0; extra == "transformers"
99
99
 
100
100
  <details>
101
101
  <summary>Latest News 🔥</summary>
102
-
102
+
103
+ - [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!
103
104
  - [2024/10/21] We have released the tech report of Liger Kernel on Arxiv: https://arxiv.org/pdf/2410.10989
104
105
  - [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!
105
106
  - [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)
@@ -127,18 +128,12 @@ With one line of code, Liger Kernel can increase throughput by more than 20% and
127
128
 
128
129
  ## Examples
129
130
 
130
- ### Basic
131
-
132
- | **Example** | **Description** | **Lightning Studio** |
133
- |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
134
- | [**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 |
135
- | [**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 |
136
131
 
137
- ### Advanced
138
-
139
- | **Example** | **Description** | **Lightning Studio** |
140
- |------------------------------------------------|---------------------------------------------------------------------------------------------------|----------------------|
141
- | [**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
+ | **Use Case** | **Description** |
133
+ |------------------------------------------------|---------------------------------------------------------------------------------------------------|
134
+ | [**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 |
135
+ | [**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 |
136
+ | [**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 | |
142
137
 
143
138
  ## Key Features
144
139
 
@@ -149,13 +144,6 @@ With one line of code, Liger Kernel can increase throughput by more than 20% and
149
144
  - **Multi-GPU supported:** Compatible with multi-GPU setups (PyTorch FSDP, DeepSpeed, DDP, etc.).
150
145
  - **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)
151
146
 
152
- ## Target Audiences
153
-
154
- - **Researchers**: Looking to compose models using efficient and reliable kernels for frontier experiments.
155
- - **ML Practitioners**: Focused on maximizing GPU training efficiency with optimal, high-performance kernels.
156
- - **Curious Novices**: Eager to learn how to write reliable Triton kernels to enhance training efficiency.
157
-
158
-
159
147
  ## Installation
160
148
 
161
149
  ### Dependencies
@@ -261,23 +249,6 @@ loss = loss_fn(model.weight, input, target)
261
249
  loss.backward()
262
250
  ```
263
251
 
264
-
265
- ## Structure
266
-
267
- ### Source Code
268
-
269
- - `ops/`: Core Triton operations.
270
- - `transformers/`: PyTorch `nn.Module` implementations built on Triton operations, compliant with the `transformers` API.
271
-
272
- ### Tests
273
-
274
- - `transformers/`: Correctness tests for the Triton-based layers.
275
- - `convergence/`: Patches Hugging Face models with all kernels, runs multiple iterations, and compares weights, logits, and loss layer-by-layer.
276
-
277
- ### Benchmark
278
-
279
- - `benchmark/`: Execution time and memory benchmarks compared to Hugging Face layers.
280
-
281
252
  ## APIs
282
253
 
283
254
  ### AutoModel
@@ -296,7 +267,7 @@ loss.backward()
296
267
  | Mistral | `liger_kernel.transformers.apply_liger_kernel_to_mistral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
297
268
  | Mixtral | `liger_kernel.transformers.apply_liger_kernel_to_mixtral` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
298
269
  | Gemma1 | `liger_kernel.transformers.apply_liger_kernel_to_gemma` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
299
- | Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss |
270
+ | Gemma2 | `liger_kernel.transformers.apply_liger_kernel_to_gemma2` | RoPE, RMSNorm, GeGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
300
271
  | Qwen2 & Qwen2.5 | `liger_kernel.transformers.apply_liger_kernel_to_qwen2` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
301
272
  | Qwen2-VL | `liger_kernel.transformers.apply_liger_kernel_to_qwen2_vl` | RMSNorm, LayerNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
302
273
  | Phi3 & Phi3.5 | `liger_kernel.transformers.apply_liger_kernel_to_phi3` | RoPE, RMSNorm, SwiGLU, CrossEntropyLoss, FusedLinearCrossEntropy |
@@ -320,6 +291,7 @@ loss.backward()
320
291
 
321
292
  - **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.
322
293
  - **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.
294
+ - **GroupNorm**: [GroupNorm](https://arxiv.org/pdf/1803.08494), which normalizes activations across the group dimension for a given sample. Channels are grouped in K groups over which the normalization is performed, is implemented by fusing the centering, normalization and scaling steps into a single Triton kernel, and can achieve up to ~2X speedup as the number of channels/groups increases.
323
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.
324
296
  - **SwiGLU**: [Swish Gated Linear Units](https://arxiv.org/pdf/2002.05202), given by
325
297
  $$\text{SwiGLU}(x)=\text{Swish}_{\beta}(xW+b)\otimes(xV+c)$$
@@ -332,7 +304,7 @@ $$\text{GeGLU}(x)=\text{GELU}(xW+b)\otimes(xV+c)$$
332
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.
333
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.
334
306
  - **JSD**: [Generalized JSD](https://arxiv.org/pdf/2306.13649) (Jensen-Shannon divergence), is implemented by computing both the loss and gradient in the forward pass. It achieves ~1.5X speed and ~54% memory reduction for 128k vocab size.
335
- - **FusedLinearJSD**: Peak memory usage of JSD loss is further improved by fusing the model head with the model head with the JSD and chunking the input for block-wise loss and gradient calculation. It achieves ~85% memory reduction for 128k vocab size where batch size $\times$ sequence length is 8192.
307
+ - **FusedLinearJSD**: Peak memory usage of JSD loss is further improved by fusing the model head with the JSD and chunking the input for block-wise loss and gradient calculation. It achieves ~85% memory reduction for 128k vocab size where batch size $\times$ sequence length is 8192.
336
308
 
337
309
 
338
310
  ### Experimental Kernels
@@ -345,54 +317,17 @@ $$\text{GeGLU}(x)=\text{GELU}(xW+b)\otimes(xV+c)$$
345
317
  - **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.
346
318
  - **Matmul int2xint8**: is implemented by using the cache tiled matrix multiplication and by fusing the matmul with the unpacking process which achieves a considerable speed up and performs on par with @torch.compile
347
319
  <!-- TODO: be more specific about batch size -->
348
- > **Note:**
349
- > 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.
350
320
 
351
- ## Contributing
321
+ ## Contributing, Acknowledgements, and License
352
322
 
353
- [CONTRIBUTING GUIDE](https://github.com/linkedin/Liger-Kernel/blob/main/CONTRIBUTING.md)
354
-
355
- ## Acknowledgement
356
-
357
-
358
- ### Design
359
-
360
- - [@claire_yishan](https://twitter.com/claire_yishan) for the LOGO design
361
- - [Wave Snippets](https://www.wavesnippets.com/) for generating the animated code snippets
362
-
363
- ### Code
364
-
365
- We referenced or used the following projects:
366
-
367
-
368
-
369
- | # | Project | Description | Location | License |
370
- |---|----------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
371
- | 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) |
372
- | 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) |
373
- | 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) |
374
- | 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 |
375
- | 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) |
376
- | 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) |
377
- | 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) |
378
- | 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) |
379
-
380
- Many thanks to the contributors to these projects for their invaluable work that helped make Liger possible.
381
-
382
- ## License
383
-
384
- This project is licensed under the [BSD 2-CLAUSE](https://github.com/linkedin/Liger-Kernel/blob/main/LICENSE) License (see `LICENSE` for details).
385
- It also includes components from projects licensed under:
386
-
387
- - Apache License 2.0 (see `LICENSE-APACHE-2.0` for details).
388
- - MIT License (see `LICENSE-MIT-AutoAWQ` for details).
389
- - MIT License (see `LICENSE-MIT-Efficient Cross Entropy` for details).
390
- - MIT License (see `LICENSE-MIT-llmc` for details).
391
- - MIT License (see `LICENSE-MIT-triton` for details).
323
+ - [Contributing Guidelines](https://github.com/linkedin/Liger-Kernel/blob/main/docs/CONTRIBUTING.md)
324
+ - [Acknowledgements](https://github.com/linkedin/Liger-Kernel/blob/main/docs/Acknowledgement.md)
325
+ - [License Information](https://github.com/linkedin/Liger-Kernel/blob/main/docs/License.md)
392
326
 
393
327
  ## Contact
394
328
 
395
- - For public discussion, join [our discord channel](https://discord.gg/vNBDpjhb)
329
+ - For issues, create a Github ticket in this repository
330
+ - For open discussion, join [our discord channel](https://discord.gg/gpumode)
396
331
  - For formal collaboration, send an email to byhsu@linkedin.com
397
332
 
398
333
  ## Cite this work
@@ -425,3 +360,4 @@ Biblatex entry:
425
360
  ↑ Back to Top ↑
426
361
  </a>
427
362
  </p>
363
+