liger-kernel 0.6.4__py3-none-any.whl → 0.6.5__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 (71) hide show
  1. liger_kernel/chunked_loss/cosine_similarity_loss.py +7 -1
  2. liger_kernel/chunked_loss/fused_linear_distillation.py +10 -3
  3. liger_kernel/chunked_loss/jsd_loss.py +21 -6
  4. liger_kernel/ops/__init__.py +141 -0
  5. liger_kernel/ops/backends/README.md +151 -0
  6. liger_kernel/ops/backends/__init__.py +13 -0
  7. liger_kernel/ops/backends/_ascend/__init__.py +5 -0
  8. liger_kernel/ops/backends/_ascend/ascend-ub-manager-design.md +492 -0
  9. liger_kernel/ops/backends/_ascend/ops/__init__.py +61 -0
  10. liger_kernel/ops/backends/_ascend/ops/embedding.py +214 -0
  11. liger_kernel/ops/backends/_ascend/ops/geglu.py +191 -0
  12. liger_kernel/ops/backends/_ascend/ops/llama4_rope.py +298 -0
  13. liger_kernel/ops/backends/_ascend/ops/qwen2vl_mrope.py +275 -0
  14. liger_kernel/ops/backends/_ascend/ops/rope.py +265 -0
  15. liger_kernel/ops/backends/_ascend/ops/swiglu.py +142 -0
  16. liger_kernel/ops/backends/_ascend/ops/tvd.py +223 -0
  17. liger_kernel/ops/backends/_ascend/ub_manager.py +367 -0
  18. liger_kernel/ops/backends/registry.py +61 -0
  19. liger_kernel/ops/cross_entropy.py +14 -4
  20. liger_kernel/ops/dyt.py +5 -2
  21. liger_kernel/ops/fused_add_rms_norm.py +21 -23
  22. liger_kernel/ops/fused_linear_cross_entropy.py +2 -1
  23. liger_kernel/ops/geglu.py +5 -3
  24. liger_kernel/ops/group_norm.py +12 -8
  25. liger_kernel/ops/kl_div.py +8 -11
  26. liger_kernel/ops/layer_norm.py +17 -16
  27. liger_kernel/ops/poly_norm.py +19 -21
  28. liger_kernel/ops/rms_norm.py +149 -71
  29. liger_kernel/ops/utils.py +25 -0
  30. liger_kernel/transformers/__init__.py +6 -0
  31. liger_kernel/transformers/auto_model.py +21 -0
  32. liger_kernel/transformers/cross_entropy.py +1 -1
  33. liger_kernel/transformers/dyt.py +1 -1
  34. liger_kernel/transformers/experimental/embedding.py +1 -1
  35. liger_kernel/transformers/functional.py +20 -20
  36. liger_kernel/transformers/fused_add_rms_norm.py +1 -1
  37. liger_kernel/transformers/fused_linear_cross_entropy.py +1 -1
  38. liger_kernel/transformers/fused_linear_jsd.py +1 -1
  39. liger_kernel/transformers/fused_neighborhood_attention.py +1 -1
  40. liger_kernel/transformers/geglu.py +1 -1
  41. liger_kernel/transformers/group_norm.py +1 -1
  42. liger_kernel/transformers/grpo_loss.py +1 -1
  43. liger_kernel/transformers/jsd.py +1 -1
  44. liger_kernel/transformers/kl_div.py +1 -1
  45. liger_kernel/transformers/layer_norm.py +1 -1
  46. liger_kernel/transformers/llama4_rope.py +1 -1
  47. liger_kernel/transformers/model/exaone4.py +136 -0
  48. liger_kernel/transformers/model/gemma2.py +3 -3
  49. liger_kernel/transformers/model/gemma3.py +11 -5
  50. liger_kernel/transformers/model/gpt_oss.py +211 -0
  51. liger_kernel/transformers/model/loss_utils.py +6 -0
  52. liger_kernel/transformers/model/paligemma.py +1 -0
  53. liger_kernel/transformers/monkey_patch.py +196 -39
  54. liger_kernel/transformers/multi_token_attention.py +1 -1
  55. liger_kernel/transformers/poly_norm.py +1 -1
  56. liger_kernel/transformers/qwen2vl_mrope.py +1 -1
  57. liger_kernel/transformers/rms_norm.py +8 -3
  58. liger_kernel/transformers/rope.py +28 -27
  59. liger_kernel/transformers/softmax.py +1 -1
  60. liger_kernel/transformers/sparsemax.py +1 -1
  61. liger_kernel/transformers/swiglu.py +1 -1
  62. liger_kernel/transformers/tiled_mlp.py +5 -13
  63. liger_kernel/transformers/tvd.py +1 -1
  64. liger_kernel/utils.py +54 -0
  65. {liger_kernel-0.6.4.dist-info → liger_kernel-0.6.5.dist-info}/METADATA +11 -4
  66. liger_kernel-0.6.5.dist-info/RECORD +134 -0
  67. {liger_kernel-0.6.4.dist-info → liger_kernel-0.6.5.dist-info}/WHEEL +1 -1
  68. liger_kernel-0.6.4.dist-info/RECORD +0 -118
  69. {liger_kernel-0.6.4.dist-info → liger_kernel-0.6.5.dist-info}/licenses/LICENSE +0 -0
  70. {liger_kernel-0.6.4.dist-info → liger_kernel-0.6.5.dist-info}/licenses/NOTICE +0 -0
  71. {liger_kernel-0.6.4.dist-info → liger_kernel-0.6.5.dist-info}/top_level.txt +0 -0
@@ -1,7 +1,7 @@
1
1
  import torch
2
2
  import torch.nn as nn
3
3
 
4
- from liger_kernel.ops.fused_add_rms_norm import LigerFusedAddRMSNormFunction
4
+ from liger_kernel.ops import LigerFusedAddRMSNormFunction
5
5
 
6
6
 
7
7
  class LigerFusedAddRMSNorm(nn.Module):
@@ -2,7 +2,7 @@ from typing import Optional
2
2
 
3
3
  import torch
4
4
 
5
- from liger_kernel.ops.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyFunction
5
+ from liger_kernel.ops import LigerFusedLinearCrossEntropyFunction
6
6
  from liger_kernel.transformers.functional import CrossEntropyOutput
7
7
 
8
8
 
@@ -2,7 +2,7 @@ from typing import Optional
2
2
 
3
3
  import torch
4
4
 
5
- from liger_kernel.ops.fused_linear_jsd import LigerFusedLinearJSDFunction
5
+ from liger_kernel.ops import LigerFusedLinearJSDFunction
6
6
 
7
7
 
8
8
  class LigerFusedLinearJSD(torch.nn.Module):
@@ -5,7 +5,7 @@ from typing import Optional
5
5
  import torch
6
6
  import torch.nn as nn
7
7
 
8
- from liger_kernel.ops.fused_neighborhood_attention import LigerFusedNeighborhoodAttentionFunction
8
+ from liger_kernel.ops import LigerFusedNeighborhoodAttentionFunction
9
9
 
10
10
 
11
11
  class LigerFusedNeighborhoodAttention(nn.Module):
@@ -1,6 +1,6 @@
1
1
  import torch.nn as nn
2
2
 
3
- from liger_kernel.ops.geglu import LigerGELUMulFunction
3
+ from liger_kernel.ops import LigerGELUMulFunction
4
4
 
5
5
 
6
6
  class LigerGEGLUMLP(nn.Module):
@@ -1,7 +1,7 @@
1
1
  import torch
2
2
  import torch.nn as nn
3
3
 
4
- from liger_kernel.ops.group_norm import LigerGroupNormFunction
4
+ from liger_kernel.ops import LigerGroupNormFunction
5
5
 
6
6
 
7
7
  class LigerGroupNorm(nn.Module):
@@ -1,7 +1,7 @@
1
1
  import torch
2
2
 
3
3
  from liger_kernel.chunked_loss.fused_linear_ppo import LigerFusedLinearPPOBase
4
- from liger_kernel.ops.grpo_loss import GrpoLossFunction
4
+ from liger_kernel.ops import GrpoLossFunction
5
5
 
6
6
 
7
7
  def triton_grpo_loss(
@@ -2,7 +2,7 @@ from typing import Optional
2
2
 
3
3
  import torch
4
4
 
5
- from liger_kernel.ops.jsd import LigerJSDFunction
5
+ from liger_kernel.ops import LigerJSDFunction
6
6
 
7
7
 
8
8
  class LigerJSD(torch.nn.Module):
@@ -1,6 +1,6 @@
1
1
  import torch.nn as nn
2
2
 
3
- from liger_kernel.ops.kl_div import LigerKLDivLossFunction
3
+ from liger_kernel.ops import LigerKLDivLossFunction
4
4
 
5
5
 
6
6
  class LigerKLDIVLoss(nn.KLDivLoss):
@@ -1,7 +1,7 @@
1
1
  import torch
2
2
  import torch.nn as nn
3
3
 
4
- from liger_kernel.ops.layer_norm import LigerLayerNormFunction
4
+ from liger_kernel.ops import LigerLayerNormFunction
5
5
 
6
6
 
7
7
  class LigerLayerNorm(nn.Module):
@@ -5,7 +5,7 @@ Supports both text and vision RoPE variants with fused operations for optimal pe
5
5
 
6
6
  import torch
7
7
 
8
- from liger_kernel.ops.llama4_rope import LigerLlama4RopeFunction
8
+ from liger_kernel.ops import LigerLlama4RopeFunction
9
9
 
10
10
 
11
11
  def liger_llama4_text_rotary_pos_emb(
@@ -0,0 +1,136 @@
1
+ from typing import List
2
+ from typing import Optional
3
+ from typing import Union
4
+
5
+ import torch
6
+
7
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
8
+ from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
9
+ from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
10
+
11
+
12
+ def lce_forward(
13
+ self,
14
+ input_ids: Optional[torch.LongTensor] = None,
15
+ attention_mask: Optional[torch.Tensor] = None,
16
+ position_ids: Optional[torch.LongTensor] = None,
17
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
18
+ inputs_embeds: Optional[torch.FloatTensor] = None,
19
+ labels: Optional[torch.LongTensor] = None,
20
+ use_cache: Optional[bool] = None,
21
+ output_attentions: Optional[bool] = None,
22
+ output_hidden_states: Optional[bool] = None,
23
+ cache_position: Optional[torch.LongTensor] = None,
24
+ logits_to_keep: Union[int, torch.Tensor] = 0,
25
+ skip_logits: Optional[bool] = None,
26
+ return_dict: Optional[bool] = None,
27
+ **kwargs,
28
+ ) -> LigerCausalLMOutputWithPast:
29
+ r"""
30
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
31
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
32
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
33
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
34
+
35
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
36
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
37
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
38
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
39
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
40
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
41
+
42
+ Returns:
43
+
44
+ Example:
45
+
46
+ ````python
47
+ >>> from transformers import AutoTokenizer, Exaone4ForCausalLM
48
+
49
+ >>> model = Exaone4ForCausalLM.from_pretrained("LGAI-EXAONE/EXAONE-4.0-1.2B")
50
+ >>> tokenizer = AutoTokenizer.from_pretrained("LGAI-EXAONE/EXAONE-4.0-1.2B")
51
+
52
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
53
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
54
+
55
+ >>> # Generate
56
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
57
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
58
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
59
+ ```"""
60
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
61
+ output_hidden_states = (
62
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
63
+ )
64
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
65
+
66
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
67
+ outputs = self.model(
68
+ input_ids=input_ids,
69
+ attention_mask=attention_mask,
70
+ position_ids=position_ids,
71
+ past_key_values=past_key_values,
72
+ inputs_embeds=inputs_embeds,
73
+ use_cache=use_cache,
74
+ output_attentions=output_attentions,
75
+ output_hidden_states=output_hidden_states,
76
+ cache_position=cache_position,
77
+ **kwargs,
78
+ )
79
+
80
+ hidden_states = outputs[0]
81
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
82
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
83
+ kept_hidden_states = hidden_states[:, slice_indices, :]
84
+
85
+ shift_labels = kwargs.pop("shift_labels", None)
86
+ # Remove output-control parameters that shouldn't be passed to loss functions
87
+ kwargs.pop("return_dict", None)
88
+ logits = None
89
+ loss = None
90
+ token_accuracy = None
91
+
92
+ if skip_logits and labels is None and shift_labels is None:
93
+ raise ValueError("skip_logits is True, but labels and shift_labels are None")
94
+
95
+ if skip_logits is None:
96
+ # By default, if in training mode, don't materialize logits
97
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
98
+
99
+ # Compute loss
100
+ if skip_logits:
101
+ result = LigerForCausalLMLoss(
102
+ hidden_states=kept_hidden_states,
103
+ lm_head_weight=self.lm_head.weight,
104
+ labels=labels,
105
+ shift_labels=shift_labels,
106
+ hidden_size=self.config.hidden_size,
107
+ **kwargs,
108
+ )
109
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
110
+
111
+ else:
112
+ logits = self.lm_head(kept_hidden_states)
113
+ if labels is not None or shift_labels is not None:
114
+ loss = self.loss_function(
115
+ logits=logits,
116
+ labels=labels,
117
+ shift_labels=shift_labels,
118
+ vocab_size=self.config.vocab_size,
119
+ **kwargs,
120
+ )
121
+
122
+ if not return_dict:
123
+ output = (logits,) + outputs[1:]
124
+ output = ((loss,) + output) if loss is not None else output
125
+ output = output + (token_accuracy,) if token_accuracy is not None else output
126
+ return output
127
+
128
+ # Return custom output class with accuracy field
129
+ return LigerCausalLMOutputWithPast(
130
+ loss=loss,
131
+ logits=logits,
132
+ past_key_values=outputs.past_key_values,
133
+ hidden_states=outputs.hidden_states,
134
+ attentions=outputs.attentions,
135
+ token_accuracy=token_accuracy,
136
+ )
@@ -7,7 +7,7 @@ from typing import Union
7
7
  import torch
8
8
 
9
9
  from torch.nn import CrossEntropyLoss
10
- from transformers.cache_utils import HybridCache
10
+ from transformers.cache_utils import Cache
11
11
  from transformers.modeling_outputs import CausalLMOutputWithPast
12
12
  from transformers.utils.deprecation import deprecate_kwarg
13
13
 
@@ -24,7 +24,7 @@ def lce_forward_deprecated(
24
24
  input_ids: torch.LongTensor = None,
25
25
  attention_mask: Optional[torch.Tensor] = None,
26
26
  position_ids: Optional[torch.LongTensor] = None,
27
- past_key_values: Optional[HybridCache] = None,
27
+ past_key_values: Optional[Cache] = None,
28
28
  inputs_embeds: Optional[torch.FloatTensor] = None,
29
29
  labels: Optional[torch.LongTensor] = None,
30
30
  use_cache: Optional[bool] = None,
@@ -149,7 +149,7 @@ def lce_forward(
149
149
  input_ids: torch.LongTensor = None,
150
150
  attention_mask: Optional[torch.Tensor] = None,
151
151
  position_ids: Optional[torch.LongTensor] = None,
152
- past_key_values: Optional[HybridCache] = None,
152
+ past_key_values: Optional[Cache] = None,
153
153
  inputs_embeds: Optional[torch.FloatTensor] = None,
154
154
  labels: Optional[torch.LongTensor] = None,
155
155
  use_cache: Optional[bool] = None,
@@ -6,10 +6,8 @@ import torch
6
6
  import torch.nn as nn
7
7
 
8
8
  from transformers.cache_utils import Cache
9
- from transformers.cache_utils import HybridCache
10
9
  from transformers.utils import logging
11
10
 
12
- from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
13
11
  from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
14
12
  from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
15
13
  from liger_kernel.transformers.model.output_classes import LigerCausalLMOutputWithPast
@@ -23,7 +21,7 @@ def causal_forward(
23
21
  input_ids: torch.LongTensor = None,
24
22
  attention_mask: Optional[torch.Tensor] = None,
25
23
  position_ids: Optional[torch.LongTensor] = None,
26
- past_key_values: Optional[HybridCache] = None,
24
+ past_key_values: Optional[Cache] = None,
27
25
  inputs_embeds: Optional[torch.FloatTensor] = None,
28
26
  labels: Optional[torch.LongTensor] = None,
29
27
  use_cache: Optional[bool] = None,
@@ -235,6 +233,7 @@ def multimodal_forward(
235
233
  **lm_kwargs,
236
234
  )
237
235
 
236
+ shift_labels = lm_kwargs.pop("shift_labels", None)
238
237
  hidden_states = outputs[0]
239
238
 
240
239
  slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
@@ -268,8 +267,15 @@ def multimodal_forward(
268
267
  shift_hidden_states = shift_hidden_states.view(-1, self.config.text_config.hidden_size)
269
268
  shift_labels = shift_labels.view(-1).to(hidden_device)
270
269
 
271
- lce = LigerFusedLinearCrossEntropyLoss()
272
- result = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
270
+ result = LigerForCausalLMLoss(
271
+ hidden_states=shift_hidden_states,
272
+ lm_head_weight=self.lm_head.weight,
273
+ labels=shift_labels,
274
+ hidden_size=self.config.text_config.hidden_size,
275
+ shift_labels=shift_labels,
276
+ final_logit_softcapping=getattr(self.config.text_config, "final_logit_softcapping", None),
277
+ **lm_kwargs,
278
+ )
273
279
  loss, _, token_accuracy = unpack_cross_entropy_result(result)
274
280
 
275
281
  else:
@@ -0,0 +1,211 @@
1
+ from typing import List
2
+ from typing import Optional
3
+ from typing import Union
4
+
5
+ import torch
6
+
7
+ from transformers.modeling_outputs import MoeModelOutputWithPast
8
+ from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func
9
+
10
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
11
+ from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
12
+ from liger_kernel.transformers.model.output_classes import LigerMoeCausalLMOutputWithPast
13
+
14
+
15
+ def lce_forward(
16
+ self,
17
+ input_ids: Optional[torch.LongTensor] = None,
18
+ attention_mask: Optional[torch.Tensor] = None,
19
+ position_ids: Optional[torch.LongTensor] = None,
20
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
21
+ inputs_embeds: Optional[torch.FloatTensor] = None,
22
+ labels: Optional[torch.LongTensor] = None,
23
+ use_cache: Optional[bool] = None,
24
+ output_attentions: Optional[bool] = None,
25
+ output_hidden_states: Optional[bool] = None,
26
+ output_router_logits: Optional[bool] = None,
27
+ cache_position: Optional[torch.LongTensor] = None,
28
+ logits_to_keep: Union[int, torch.Tensor] = 0,
29
+ skip_logits: Optional[bool] = None,
30
+ **kwargs,
31
+ ) -> LigerMoeCausalLMOutputWithPast:
32
+ r"""
33
+ Forward pass for causal language modeling with Mixture of Experts (MoE) architecture using Liger Kernel optimizations.
34
+
35
+ Args:
36
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
37
+ Indices of input sequence tokens in the vocabulary. Indices can be obtained using tokenizers.
38
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
39
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
40
+ - 1 for tokens that are **not masked**,
41
+ - 0 for tokens that are **masked**.
42
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
43
+ Indices of positions of each input sequence tokens in the position embeddings.
44
+ past_key_values (`List[torch.FloatTensor]` or `Cache`, *optional*):
45
+ Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up
46
+ sequential decoding. See `past_key_values` input for more details.
47
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
48
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
49
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
50
+ than the model's internal embedding lookup matrix.
51
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
52
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
53
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
54
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
55
+ use_cache (`bool`, *optional*):
56
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
57
+ (see `past_key_values`).
58
+ output_attentions (`bool`, *optional*):
59
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
60
+ tensors for more detail.
61
+ output_hidden_states (`bool`, *optional*):
62
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
63
+ more detail.
64
+ output_router_logits (`bool`, *optional*):
65
+ Whether or not to return the router logits of all MoE layers. See `router_logits` under returned tensors
66
+ for more detail.
67
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
68
+ Indices depicting the position of the input sequence tokens in the sequence.
69
+ logits_to_keep (`int` or `torch.Tensor`, *optional*, defaults to 0):
70
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
71
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
72
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
73
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
74
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
75
+ skip_logits (`bool`, *optional*):
76
+ Whether to skip logit computation and directly compute loss. If `None`, defaults to `True` during training
77
+ when labels are provided (to save memory), and `False` during inference.
78
+
79
+ Returns:
80
+ `LigerMoeCausalLMOutputWithPast`: An output object containing:
81
+ - loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
82
+ Language modeling loss (for next-token prediction), including the auxiliary load balancing loss.
83
+ - aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
84
+ Auxiliary load balancing loss for the sparse MoE modules.
85
+ - logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
86
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
87
+ Note: logits are `None` during training when `skip_logits=True` to save memory.
88
+ - past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed):
89
+ Cached key and value projection states for faster sequential decoding.
90
+ - hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
91
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for each layer) of shape
92
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer.
93
+ - attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True`):
94
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
95
+ sequence_length)`. Attentions weights after the attention softmax.
96
+ - router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True`):
97
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
98
+ Router logits of the MoE layers, useful to compute the auxiliary loss and z_loss.
99
+ - token_accuracy (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
100
+ Token-level prediction accuracy.
101
+
102
+ Example:
103
+
104
+ ```python
105
+ >>> from transformers import AutoTokenizer, GptOssForCausalLM
106
+ >>> from liger_kernel.transformers import apply_liger_kernel_to_gpt_oss
107
+
108
+ >>> # Apply Liger Kernel patches for optimized performance
109
+ >>> apply_liger_kernel_to_gpt_oss()
110
+
111
+ >>> model = GptOssForCausalLM.from_pretrained("openai/gpt-oss-20b")
112
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/gpt-oss-20b")
113
+
114
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
115
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
116
+
117
+ >>> # Inference: Forward pass returns logits
118
+ >>> outputs = model(**inputs)
119
+ >>> outputs.logits.shape
120
+ torch.Size([1, 12, 201088])
121
+
122
+ >>> # Get next token prediction
123
+ >>> next_token_logits = outputs.logits[:, -1, :]
124
+ >>> predicted_token_id = next_token_logits.argmax(dim=-1)
125
+
126
+ >>> # Training: Forward pass with labels returns loss
127
+ >>> labels = inputs.input_ids.clone()
128
+ >>> outputs = model(**inputs, labels=labels)
129
+ >>> outputs.loss
130
+ tensor(2.6454)
131
+ ```"""
132
+
133
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
134
+ output_router_logits = (
135
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
136
+ )
137
+
138
+ output_hidden_states = (
139
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
140
+ )
141
+
142
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
143
+ outputs: MoeModelOutputWithPast = self.model(
144
+ input_ids=input_ids,
145
+ attention_mask=attention_mask,
146
+ position_ids=position_ids,
147
+ past_key_values=past_key_values,
148
+ inputs_embeds=inputs_embeds,
149
+ use_cache=use_cache,
150
+ output_attentions=output_attentions,
151
+ output_hidden_states=output_hidden_states,
152
+ output_router_logits=output_router_logits,
153
+ cache_position=cache_position,
154
+ **kwargs,
155
+ )
156
+
157
+ hidden_states = outputs.last_hidden_state
158
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
159
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
160
+ kept_hidden_states = hidden_states[:, slice_indices, :]
161
+
162
+ shift_labels = kwargs.pop("shift_labels", None)
163
+ logits = None
164
+ loss = None
165
+ token_accuracy = None
166
+
167
+ if skip_logits is None:
168
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
169
+
170
+ if skip_logits:
171
+ result = LigerForCausalLMLoss(
172
+ hidden_states=kept_hidden_states,
173
+ lm_head_weight=self.lm_head.weight,
174
+ labels=labels,
175
+ shift_labels=shift_labels,
176
+ hidden_size=self.config.hidden_size,
177
+ **kwargs,
178
+ )
179
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
180
+ else: # if in inference model materialize logits
181
+ logits = self.lm_head(kept_hidden_states)
182
+ if labels is not None or shift_labels is not None:
183
+ loss = self.loss_function(
184
+ logits=logits,
185
+ labels=labels,
186
+ shift_labels=shift_labels,
187
+ vocab_size=self.vocab_size,
188
+ **kwargs,
189
+ )
190
+
191
+ aux_loss = None
192
+ if output_router_logits:
193
+ aux_loss = load_balancing_loss_func(
194
+ outputs.router_logits,
195
+ self.num_experts,
196
+ self.num_experts_per_tok,
197
+ attention_mask,
198
+ )
199
+ if labels is not None:
200
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
201
+
202
+ return LigerMoeCausalLMOutputWithPast(
203
+ loss=loss,
204
+ aux_loss=aux_loss,
205
+ logits=logits,
206
+ past_key_values=outputs.past_key_values,
207
+ hidden_states=outputs.hidden_states,
208
+ attentions=outputs.attentions,
209
+ router_logits=outputs.router_logits,
210
+ token_accuracy=token_accuracy,
211
+ )
@@ -1,3 +1,5 @@
1
+ import inspect
2
+
1
3
  from typing import Optional
2
4
  from typing import Tuple
3
5
 
@@ -71,6 +73,10 @@ def LigerForCausalLMLoss(
71
73
  return_token_accuracy: bool = False,
72
74
  **kwargs,
73
75
  ):
76
+ # Filter out inapplicable kwargs to liger_fused_linear_cross_entropy
77
+ applicable_params = inspect.signature(F.liger_fused_linear_cross_entropy).parameters
78
+ kwargs = {k: v for k, v in kwargs.items() if k in applicable_params}
79
+
74
80
  # Skip upcast since intermediate values for the loss are all fp32 in kernel
75
81
  if shift_labels is None:
76
82
  # Shift so that token < n predict n
@@ -330,6 +330,7 @@ def lce_forward(
330
330
  **lm_kwargs,
331
331
  )
332
332
 
333
+ shift_labels = lm_kwargs.pop("shift_labels", None)
333
334
  hidden_states = outputs[0]
334
335
 
335
336
  loss = None