liger-kernel-nightly 0.5.5.dev20250402185702__py3-none-any.whl → 0.6.4.dev20260112233432__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.

Potentially problematic release.


This version of liger-kernel-nightly might be problematic. Click here for more details.

Files changed (115) hide show
  1. liger_kernel/chunked_loss/__init__.py +1 -0
  2. liger_kernel/chunked_loss/cosine_similarity_loss.py +142 -0
  3. liger_kernel/chunked_loss/dpo_loss.py +61 -3
  4. liger_kernel/chunked_loss/functional.py +2 -0
  5. liger_kernel/chunked_loss/fused_linear_distillation.py +23 -5
  6. liger_kernel/chunked_loss/fused_linear_ppo.py +36 -0
  7. liger_kernel/chunked_loss/fused_linear_preference.py +0 -1
  8. liger_kernel/chunked_loss/grpo_loss.py +76 -5
  9. liger_kernel/chunked_loss/jsd_loss.py +46 -15
  10. liger_kernel/ops/__init__.py +141 -0
  11. liger_kernel/ops/backends/README.md +151 -0
  12. liger_kernel/ops/backends/__init__.py +13 -0
  13. liger_kernel/ops/backends/_ascend/__init__.py +5 -0
  14. liger_kernel/ops/backends/_ascend/ascend-ub-manager-design.md +485 -0
  15. liger_kernel/ops/backends/_ascend/ops/__init__.py +49 -0
  16. liger_kernel/ops/backends/_ascend/ops/geglu.py +266 -0
  17. liger_kernel/ops/backends/_ascend/ops/qwen2vl_mrope.py +285 -0
  18. liger_kernel/ops/backends/_ascend/ops/rope.py +290 -0
  19. liger_kernel/ops/backends/_ascend/ops/swiglu.py +142 -0
  20. liger_kernel/ops/backends/_ascend/ops/tvd.py +221 -0
  21. liger_kernel/ops/backends/_ascend/ub_manager.py +349 -0
  22. liger_kernel/ops/backends/registry.py +61 -0
  23. liger_kernel/ops/cross_entropy.py +134 -65
  24. liger_kernel/ops/dyt.py +115 -180
  25. liger_kernel/ops/fused_add_rms_norm.py +416 -0
  26. liger_kernel/ops/fused_linear_cross_entropy.py +117 -23
  27. liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
  28. liger_kernel/ops/geglu.py +6 -4
  29. liger_kernel/ops/group_norm.py +7 -7
  30. liger_kernel/ops/grpo_loss.py +312 -0
  31. liger_kernel/ops/jsd.py +2 -1
  32. liger_kernel/ops/kl_div.py +9 -5
  33. liger_kernel/ops/layer_norm.py +146 -78
  34. liger_kernel/ops/llama4_rope.py +225 -0
  35. liger_kernel/ops/multi_token_attention.py +207 -0
  36. liger_kernel/ops/poly_norm.py +390 -0
  37. liger_kernel/ops/rms_norm.py +398 -99
  38. liger_kernel/ops/rope.py +1 -1
  39. liger_kernel/ops/softmax.py +201 -0
  40. liger_kernel/ops/sparsemax.py +179 -0
  41. liger_kernel/ops/swiglu.py +1 -1
  42. liger_kernel/ops/tiled_mlp.py +136 -0
  43. liger_kernel/ops/utils.py +14 -0
  44. liger_kernel/transformers/__init__.py +208 -17
  45. liger_kernel/transformers/auto_model.py +21 -0
  46. liger_kernel/transformers/cross_entropy.py +9 -4
  47. liger_kernel/transformers/dyt.py +6 -4
  48. liger_kernel/transformers/experimental/__init__.py +5 -0
  49. liger_kernel/transformers/experimental/embedding.py +1 -1
  50. liger_kernel/transformers/fsdp.py +55 -0
  51. liger_kernel/transformers/functional.py +122 -20
  52. liger_kernel/transformers/fused_add_rms_norm.py +39 -0
  53. liger_kernel/transformers/fused_linear_cross_entropy.py +16 -5
  54. liger_kernel/transformers/fused_linear_jsd.py +1 -1
  55. liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
  56. liger_kernel/transformers/geglu.py +1 -1
  57. liger_kernel/transformers/group_norm.py +1 -1
  58. liger_kernel/transformers/grpo_loss.py +153 -0
  59. liger_kernel/transformers/jsd.py +1 -1
  60. liger_kernel/transformers/kl_div.py +1 -1
  61. liger_kernel/transformers/layer_norm.py +1 -1
  62. liger_kernel/transformers/llama4_rope.py +93 -0
  63. liger_kernel/transformers/model/exaone4.py +136 -0
  64. liger_kernel/transformers/model/falcon_h1.py +122 -0
  65. liger_kernel/transformers/model/gemma.py +57 -27
  66. liger_kernel/transformers/model/gemma2.py +65 -28
  67. liger_kernel/transformers/model/gemma3.py +331 -0
  68. liger_kernel/transformers/model/glm4.py +141 -0
  69. liger_kernel/transformers/model/glm4v.py +163 -0
  70. liger_kernel/transformers/model/glm4v_moe.py +172 -0
  71. liger_kernel/transformers/model/gpt_oss.py +211 -0
  72. liger_kernel/transformers/model/hunyuan_v1.py +134 -0
  73. liger_kernel/transformers/model/internvl.py +157 -0
  74. liger_kernel/transformers/model/llama.py +109 -27
  75. liger_kernel/transformers/model/llama4.py +121 -0
  76. liger_kernel/transformers/model/llava.py +111 -136
  77. liger_kernel/transformers/model/loss_utils.py +50 -12
  78. liger_kernel/transformers/model/mistral.py +51 -34
  79. liger_kernel/transformers/model/mixtral.py +50 -29
  80. liger_kernel/transformers/model/mllama.py +46 -24
  81. liger_kernel/transformers/model/olmo2.py +47 -22
  82. liger_kernel/transformers/model/olmo3.py +142 -0
  83. liger_kernel/transformers/model/output_classes.py +147 -0
  84. liger_kernel/transformers/model/paligemma.py +50 -14
  85. liger_kernel/transformers/model/phi3.py +47 -172
  86. liger_kernel/transformers/model/qwen2.py +55 -23
  87. liger_kernel/transformers/model/qwen2_5_vl.py +62 -103
  88. liger_kernel/transformers/model/qwen2_vl.py +59 -108
  89. liger_kernel/transformers/model/qwen3.py +136 -0
  90. liger_kernel/transformers/model/qwen3_moe.py +152 -0
  91. liger_kernel/transformers/model/qwen3_next.py +146 -0
  92. liger_kernel/transformers/model/qwen3_vl.py +150 -0
  93. liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
  94. liger_kernel/transformers/model/smollm3.py +199 -0
  95. liger_kernel/transformers/model/smolvlm.py +158 -0
  96. liger_kernel/transformers/monkey_patch.py +2018 -244
  97. liger_kernel/transformers/multi_token_attention.py +64 -0
  98. liger_kernel/transformers/poly_norm.py +42 -0
  99. liger_kernel/transformers/qwen2vl_mrope.py +1 -1
  100. liger_kernel/transformers/rms_norm.py +54 -6
  101. liger_kernel/transformers/rope.py +45 -1
  102. liger_kernel/transformers/softmax.py +12 -0
  103. liger_kernel/transformers/sparsemax.py +16 -0
  104. liger_kernel/transformers/swiglu.py +39 -1
  105. liger_kernel/transformers/tiled_mlp.py +125 -0
  106. liger_kernel/transformers/trainer/orpo_trainer.py +1 -53
  107. liger_kernel/transformers/tvd.py +1 -1
  108. liger_kernel/utils.py +63 -0
  109. {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/METADATA +73 -39
  110. liger_kernel_nightly-0.6.4.dev20260112233432.dist-info/RECORD +132 -0
  111. liger_kernel_nightly-0.5.5.dev20250402185702.dist-info/RECORD +0 -80
  112. {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/LICENSE +0 -0
  113. {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/NOTICE +0 -0
  114. {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/WHEEL +0 -0
  115. {liger_kernel_nightly-0.5.5.dev20250402185702.dist-info → liger_kernel_nightly-0.6.4.dev20260112233432.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,147 @@
1
+ """
2
+ Custom output classes for Liger-Kernel that extend transformers' ModelOutput classes
3
+ with optional token accuracy field.
4
+ """
5
+
6
+ from dataclasses import dataclass
7
+ from typing import Optional
8
+
9
+ import torch
10
+
11
+ from transformers.modeling_outputs import CausalLMOutputWithPast
12
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast
13
+
14
+ # The following model-specific outputs are optional and depend on the installed
15
+ # transformers version. Guard their imports so our module remains importable
16
+ # even when those models are not available in the environment.
17
+ try:
18
+ from transformers.models.gemma3.modeling_gemma3 import Gemma3CausalLMOutputWithPast as _Gemma3CausalLMOutputWithPast
19
+ except Exception:
20
+ _Gemma3CausalLMOutputWithPast = None
21
+
22
+ try:
23
+ from transformers.models.glm4v_moe.modeling_glm4v_moe import (
24
+ Glm4vMoeCausalLMOutputWithPast as _Glm4vMoeCausalLMOutputWithPast,
25
+ )
26
+ except Exception:
27
+ _Glm4vMoeCausalLMOutputWithPast = None
28
+
29
+ try:
30
+ from transformers.models.internvl.modeling_internvl import (
31
+ InternVLCausalLMOutputWithPast as _InternVLCausalLMOutputWithPast,
32
+ )
33
+ except Exception:
34
+ _InternVLCausalLMOutputWithPast = None
35
+
36
+ try:
37
+ from transformers.models.llava.modeling_llava import LlavaCausalLMOutputWithPast as _LlavaCausalLMOutputWithPast
38
+ except Exception:
39
+ _LlavaCausalLMOutputWithPast = None
40
+
41
+ try:
42
+ from transformers.models.paligemma.modeling_paligemma import (
43
+ PaliGemmaCausalLMOutputWithPast as _PaliGemmaCausalLMOutputWithPast,
44
+ )
45
+ except Exception:
46
+ _PaliGemmaCausalLMOutputWithPast = None
47
+
48
+ try:
49
+ from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import (
50
+ Qwen2_5_VLCausalLMOutputWithPast as _Qwen2_5_VLCausalLMOutputWithPast,
51
+ )
52
+ except Exception:
53
+ _Qwen2_5_VLCausalLMOutputWithPast = None
54
+
55
+ try:
56
+ from transformers.models.qwen2_vl.modeling_qwen2_vl import (
57
+ Qwen2VLCausalLMOutputWithPast as _Qwen2VLCausalLMOutputWithPast,
58
+ )
59
+ except Exception:
60
+ _Qwen2VLCausalLMOutputWithPast = None
61
+
62
+ try:
63
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import (
64
+ Qwen3VLCausalLMOutputWithPast as _Qwen3VLCausalLMOutputWithPast,
65
+ )
66
+ except Exception:
67
+ _Qwen3VLCausalLMOutputWithPast = None
68
+
69
+ try:
70
+ from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import (
71
+ Qwen3VLMoeCausalLMOutputWithPast as _Qwen3VLMoeCausalLMOutputWithPast,
72
+ )
73
+ except Exception:
74
+ _Qwen3VLMoeCausalLMOutputWithPast = None
75
+
76
+
77
+ @dataclass
78
+ class LigerCausalLMOutputWithPast(CausalLMOutputWithPast):
79
+ token_accuracy: Optional[torch.FloatTensor] = None
80
+
81
+
82
+ @dataclass
83
+ class LigerMoeCausalLMOutputWithPast(MoeCausalLMOutputWithPast):
84
+ token_accuracy: Optional[torch.FloatTensor] = None
85
+
86
+
87
+ if _Gemma3CausalLMOutputWithPast is not None:
88
+
89
+ @dataclass
90
+ class LigerGemma3CausalLMOutputWithPast(_Gemma3CausalLMOutputWithPast):
91
+ token_accuracy: Optional[torch.FloatTensor] = None
92
+
93
+
94
+ if _Glm4vMoeCausalLMOutputWithPast is not None:
95
+
96
+ @dataclass
97
+ class LigerGlm4vMoeCausalLMOutputWithPast(_Glm4vMoeCausalLMOutputWithPast):
98
+ token_accuracy: Optional[torch.FloatTensor] = None
99
+
100
+
101
+ if _LlavaCausalLMOutputWithPast is not None:
102
+
103
+ @dataclass
104
+ class LigerLlavaCausalLMOutputWithPast(_LlavaCausalLMOutputWithPast):
105
+ token_accuracy: Optional[torch.FloatTensor] = None
106
+
107
+
108
+ if _InternVLCausalLMOutputWithPast is not None:
109
+
110
+ @dataclass
111
+ class LigerInternVLCausalLMOutputWithPast(_InternVLCausalLMOutputWithPast):
112
+ token_accuracy: Optional[torch.FloatTensor] = None
113
+
114
+
115
+ if _PaliGemmaCausalLMOutputWithPast is not None:
116
+
117
+ @dataclass
118
+ class LigerPaliGemmaCausalLMOutputWithPast(_PaliGemmaCausalLMOutputWithPast):
119
+ token_accuracy: Optional[torch.FloatTensor] = None
120
+
121
+
122
+ if _Qwen2_5_VLCausalLMOutputWithPast is not None:
123
+
124
+ @dataclass
125
+ class LigerQwen2_5_VLCausalLMOutputWithPast(_Qwen2_5_VLCausalLMOutputWithPast):
126
+ token_accuracy: Optional[torch.FloatTensor] = None
127
+
128
+
129
+ if _Qwen2VLCausalLMOutputWithPast is not None:
130
+
131
+ @dataclass
132
+ class LigerQwen2VLCausalLMOutputWithPast(_Qwen2VLCausalLMOutputWithPast):
133
+ token_accuracy: Optional[torch.FloatTensor] = None
134
+
135
+
136
+ if _Qwen3VLCausalLMOutputWithPast is not None:
137
+
138
+ @dataclass
139
+ class LigerQwen3VLCausalLMOutputWithPast(_Qwen3VLCausalLMOutputWithPast):
140
+ token_accuracy: Optional[torch.FloatTensor] = None
141
+
142
+
143
+ if _Qwen3VLMoeCausalLMOutputWithPast is not None:
144
+
145
+ @dataclass
146
+ class LigerQwen3VLMoeCausalLMOutputWithPast(_Qwen3VLMoeCausalLMOutputWithPast):
147
+ token_accuracy: Optional[torch.FloatTensor] = None
@@ -7,22 +7,19 @@ import torch
7
7
 
8
8
  from torch.nn import CrossEntropyLoss
9
9
  from transformers.cache_utils import Cache
10
- from transformers.models.paligemma.modeling_paligemma import _CONFIG_FOR_DOC
11
- from transformers.models.paligemma.modeling_paligemma import PALIGEMMA_INPUTS_DOCSTRING
12
10
  from transformers.models.paligemma.modeling_paligemma import PaliGemmaCausalLMOutputWithPast
13
- from transformers.utils import add_start_docstrings_to_model_forward
14
11
  from transformers.utils import is_torchdynamo_compiling
15
12
  from transformers.utils import logging
16
- from transformers.utils import replace_return_docstrings
17
13
  from transformers.utils.deprecation import deprecate_kwarg
18
14
 
19
15
  from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
16
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
17
+ from liger_kernel.transformers.model.loss_utils import unpack_cross_entropy_result
18
+ from liger_kernel.transformers.model.output_classes import LigerPaliGemmaCausalLMOutputWithPast
20
19
 
21
20
  logger = logging.get_logger(__name__)
22
21
 
23
22
 
24
- @add_start_docstrings_to_model_forward(PALIGEMMA_INPUTS_DOCSTRING)
25
- @replace_return_docstrings(output_type=PaliGemmaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
26
23
  def lce_forward_deprecated(
27
24
  self,
28
25
  input_ids: torch.LongTensor = None,
@@ -206,8 +203,6 @@ def lce_forward_deprecated(
206
203
 
207
204
 
208
205
  @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
209
- @add_start_docstrings_to_model_forward(PALIGEMMA_INPUTS_DOCSTRING)
210
- @replace_return_docstrings(output_type=PaliGemmaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
211
206
  def lce_forward(
212
207
  self,
213
208
  input_ids: torch.LongTensor = None,
@@ -224,8 +219,9 @@ def lce_forward(
224
219
  output_hidden_states: Optional[bool] = None,
225
220
  return_dict: Optional[bool] = None,
226
221
  logits_to_keep: Union[int, torch.Tensor] = 0,
222
+ skip_logits: Optional[bool] = None,
227
223
  **lm_kwargs,
228
- ) -> Union[Tuple, PaliGemmaCausalLMOutputWithPast]:
224
+ ) -> Union[Tuple, LigerPaliGemmaCausalLMOutputWithPast]:
229
225
  r"""
230
226
  Args:
231
227
  labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
@@ -334,12 +330,20 @@ def lce_forward(
334
330
  **lm_kwargs,
335
331
  )
336
332
 
333
+ shift_labels = lm_kwargs.pop("shift_labels", None)
337
334
  hidden_states = outputs[0]
338
335
 
339
336
  loss = None
340
337
  logits = None
338
+ token_accuracy = None
341
339
 
342
- if self.training and (labels is not None):
340
+ if skip_logits and labels is None:
341
+ raise ValueError("skip_logits is True, but labels is None")
342
+
343
+ if skip_logits is None:
344
+ skip_logits = self.training and (labels is not None)
345
+
346
+ if skip_logits:
343
347
  shift_hidden_states = hidden_states[..., :-1, :]
344
348
  shift_labels = labels[..., 1:]
345
349
 
@@ -359,8 +363,16 @@ def lce_forward(
359
363
  shift_hidden_states = shift_hidden_states.view(-1, self.config.text_config.hidden_size)
360
364
  shift_labels = shift_labels.view(-1).to(hidden_device)
361
365
 
362
- lce = LigerFusedLinearCrossEntropyLoss()
363
- loss = lce(self.language_model.lm_head.weight, shift_hidden_states, shift_labels)
366
+ # Use LigerForCausalLMLoss with accuracy support and pass already shifted labels
367
+ result = LigerForCausalLMLoss(
368
+ hidden_states=shift_hidden_states,
369
+ lm_head_weight=self.language_model.lm_head.weight,
370
+ labels=None,
371
+ shift_labels=shift_labels,
372
+ hidden_size=self.config.text_config.hidden_size,
373
+ **lm_kwargs,
374
+ )
375
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
364
376
  else:
365
377
  logits = self.language_model.lm_head(hidden_states)
366
378
  if labels is not None:
@@ -383,15 +395,39 @@ def lce_forward(
383
395
  flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
384
396
  flat_labels = shift_labels.view(-1).to(shift_logits.device)
385
397
  loss = loss_fct(flat_logits, flat_labels)
398
+ elif shift_labels is not None:
399
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
400
+ logits = logits.float()
401
+ shift_logits = logits[..., :-1, :]
402
+ if attention_mask is not None:
403
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
404
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
405
+ shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(logits.device)
406
+ shift_logits = shift_logits[shift_attention_mask.to(logits.device) != 0].contiguous()
407
+ shift_labels = shift_labels[shift_attention_mask.to(shift_labels.device) != 0].contiguous()
408
+ else:
409
+ shift_logits = shift_logits.contiguous()
410
+ shift_labels = shift_labels.contiguous()
411
+ # Flatten the tokens
412
+ loss_fct = CrossEntropyLoss()
413
+
414
+ flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
415
+ flat_labels = shift_labels.view(-1).to(shift_logits.device)
416
+ loss = loss_fct(flat_logits, flat_labels)
417
+
386
418
  if not return_dict:
387
419
  output = (logits,) + outputs[1:]
388
- return (loss,) + output if loss is not None else output
420
+ output = (loss,) + output if loss is not None else output
421
+ output = output + (token_accuracy,) if token_accuracy is not None else output
422
+ return output
389
423
 
390
- return PaliGemmaCausalLMOutputWithPast(
424
+ # Return PaliGemma output with token_accuracy field
425
+ return LigerPaliGemmaCausalLMOutputWithPast(
391
426
  loss=loss,
392
427
  logits=logits,
393
428
  past_key_values=outputs.past_key_values,
394
429
  hidden_states=outputs.hidden_states,
395
430
  attentions=outputs.attentions,
396
431
  image_hidden_states=image_features if pixel_values is not None else None,
432
+ token_accuracy=token_accuracy,
397
433
  )
@@ -5,20 +5,14 @@ from typing import Union
5
5
 
6
6
  import torch
7
7
 
8
- from torch.nn import CrossEntropyLoss
9
- from transformers.modeling_outputs import CausalLMOutputWithPast
10
- from transformers.models.phi3.modeling_phi3 import _CONFIG_FOR_DOC
11
- from transformers.models.phi3.modeling_phi3 import PHI3_INPUTS_DOCSTRING
12
- from transformers.utils import add_start_docstrings_to_model_forward
13
- from transformers.utils import replace_return_docstrings
14
-
15
- from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
8
+ from transformers.modeling_outputs import BaseModelOutputWithPast
9
+
16
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 LigerCausalLMOutputWithPast
17
13
 
18
14
 
19
- @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
20
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
21
- def lce_forward_deprecated(
15
+ def lce_forward(
22
16
  self,
23
17
  input_ids: torch.LongTensor = None,
24
18
  attention_mask: Optional[torch.Tensor] = None,
@@ -31,34 +25,26 @@ def lce_forward_deprecated(
31
25
  output_hidden_states: Optional[bool] = None,
32
26
  return_dict: Optional[bool] = None,
33
27
  cache_position: Optional[torch.LongTensor] = None,
34
- ) -> Union[Tuple, CausalLMOutputWithPast]:
28
+ logits_to_keep: Union[int, torch.Tensor] = 0,
29
+ skip_logits: Optional[bool] = None,
30
+ **kwargs,
31
+ ) -> Union[Tuple, LigerCausalLMOutputWithPast]:
35
32
  r"""
36
- Copy paste phi3 forward from transfomers v4.44.2 but replace torch cross entropy with liger fused linear cross entropy
37
-
38
-
39
- Args:
40
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
41
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
42
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
43
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
44
-
45
- Returns:
46
-
47
33
  Example:
48
34
 
49
35
  ```python
50
36
  >>> from transformers import AutoTokenizer, Phi3ForCausalLM
51
37
 
52
- >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
53
- >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
38
+ >>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
39
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
54
40
 
55
- >>> prompt = "This is an example script ."
41
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
56
42
  >>> inputs = tokenizer(prompt, return_tensors="pt")
57
43
 
58
44
  >>> # Generate
59
45
  >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
60
46
  >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
61
- 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
47
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
62
48
  ```"""
63
49
 
64
50
  output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
@@ -67,179 +53,68 @@ def lce_forward_deprecated(
67
53
  )
68
54
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
69
55
 
70
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
71
- outputs = self.model(
56
+ outputs: BaseModelOutputWithPast = self.model(
72
57
  input_ids=input_ids,
73
58
  attention_mask=attention_mask,
74
59
  position_ids=position_ids,
75
60
  past_key_values=past_key_values,
76
61
  inputs_embeds=inputs_embeds,
77
62
  use_cache=use_cache,
78
- output_attentions=output_attentions,
79
- output_hidden_states=output_hidden_states,
80
- return_dict=return_dict,
63
+ cache_position=cache_position,
64
+ **kwargs,
81
65
  )
82
66
 
83
- hidden_states = outputs[0]
67
+ hidden_states = outputs.last_hidden_state
68
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
69
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
70
+ kept_hidden_states = hidden_states[:, slice_indices, :]
84
71
 
85
- loss = None
72
+ shift_labels = kwargs.pop("shift_labels", None)
86
73
  logits = None
74
+ loss = None
75
+ token_accuracy = None
87
76
 
88
- if self.training and labels is not None:
89
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
90
- shift_labels = labels[..., 1:].contiguous()
91
-
92
- # flatten tokens
93
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
94
- shift_labels = shift_labels.view(-1)
95
-
96
- lce = LigerFusedLinearCrossEntropyLoss()
97
- loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
98
- else:
99
- logits = self.lm_head(hidden_states)
100
-
101
- loss = None
102
- if labels is not None:
103
- # Upcast to float if we need to compute the loss to avoid potential precision issues
104
- logits = logits.float()
105
- # Shift so that tokens < n predict n
106
- shift_logits = logits[..., :-1, :].contiguous()
107
- shift_labels = labels[..., 1:].contiguous()
108
- # Flatten the tokens
109
- loss_fct = CrossEntropyLoss()
110
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
111
- shift_labels = shift_labels.view(-1)
112
- # Enable model parallelism
113
- shift_labels = shift_labels.to(shift_logits.device)
114
- loss = loss_fct(shift_logits, shift_labels)
115
-
116
- if not return_dict:
117
- output = (logits,) + outputs[1:]
118
- return (loss,) + output if loss is not None else output
119
-
120
- return CausalLMOutputWithPast(
121
- loss=loss,
122
- logits=logits,
123
- past_key_values=outputs.past_key_values,
124
- hidden_states=outputs.hidden_states,
125
- attentions=outputs.attentions,
126
- )
127
-
128
-
129
- @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
130
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
131
- def lce_forward(
132
- self,
133
- input_ids: torch.LongTensor = None,
134
- attention_mask: Optional[torch.Tensor] = None,
135
- position_ids: Optional[torch.LongTensor] = None,
136
- past_key_values: Optional[List[torch.FloatTensor]] = None,
137
- inputs_embeds: Optional[torch.FloatTensor] = None,
138
- labels: Optional[torch.LongTensor] = None,
139
- use_cache: Optional[bool] = None,
140
- output_attentions: Optional[bool] = None,
141
- output_hidden_states: Optional[bool] = None,
142
- return_dict: Optional[bool] = None,
143
- cache_position: Optional[torch.LongTensor] = None,
144
- num_logits_to_keep: int = 0,
145
- **loss_kwargs,
146
- ) -> Union[Tuple, CausalLMOutputWithPast]:
147
- r"""
148
- Args:
149
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
150
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
151
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
152
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
153
-
154
- num_logits_to_keep (`int`, *optional*):
155
- Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
156
- `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
157
- token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
158
-
159
- Returns:
160
-
161
- Example:
162
-
163
- ```python
164
- >>> from transformers import AutoTokenizer, Phi3ForCausalLM
165
-
166
- >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
167
- >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
168
-
169
- >>> prompt = "This is an example script ."
170
- >>> inputs = tokenizer(prompt, return_tensors="pt")
171
-
172
- >>> # Generate
173
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
174
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
175
- 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
176
- ```"""
177
-
178
- from transformers.models.phi3.modeling_phi3 import logging
179
-
180
- logger = logging.get_logger(__name__)
181
-
182
- if (
183
- use_cache
184
- and self.config.rope_scaling
185
- and cache_position is not None
186
- and cache_position[0] == self.config.original_max_position_embeddings
187
- ):
188
- logger.warning(
189
- f"If you are not using the generate method, you may encounter nonsensical outputs after the {self.config.original_max_position_embeddings}th token, as the KV cache needs to be recomputed."
190
- )
191
-
192
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
193
- output_hidden_states = (
194
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
195
- )
196
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
197
-
198
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
199
- outputs = self.model(
200
- input_ids=input_ids,
201
- attention_mask=attention_mask,
202
- position_ids=position_ids,
203
- past_key_values=past_key_values,
204
- inputs_embeds=inputs_embeds,
205
- use_cache=use_cache,
206
- output_attentions=output_attentions,
207
- output_hidden_states=output_hidden_states,
208
- return_dict=return_dict,
209
- )
77
+ if skip_logits and labels is None and shift_labels is None:
78
+ raise ValueError("skip_logits is True, but labels and shift_labels are None")
210
79
 
211
- hidden_states = outputs[0]
80
+ if skip_logits is None:
81
+ # By default, if in training mode, don't materialize logits
82
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
212
83
 
213
- logits = None
214
- loss = None
215
- # if in training mode, don't materialize logits
216
- if self.training and (labels is not None):
217
- loss = LigerForCausalLMLoss(
218
- hidden_states=hidden_states,
84
+ # Compute loss
85
+ if skip_logits:
86
+ result = LigerForCausalLMLoss(
87
+ hidden_states=kept_hidden_states,
219
88
  lm_head_weight=self.lm_head.weight,
220
89
  labels=labels,
90
+ shift_labels=shift_labels,
221
91
  hidden_size=self.config.hidden_size,
222
- **loss_kwargs,
92
+ **kwargs,
223
93
  )
224
-
225
- else: # if in inference mode materialize logits
226
- logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
227
- if labels is not None:
94
+ loss, _, token_accuracy = unpack_cross_entropy_result(result)
95
+ else:
96
+ logits = self.lm_head(kept_hidden_states)
97
+ if labels is not None or shift_labels is not None:
228
98
  loss = self.loss_function(
229
99
  logits=logits,
230
100
  labels=labels,
101
+ shift_labels=shift_labels,
231
102
  vocab_size=self.config.vocab_size,
232
- **loss_kwargs,
103
+ **kwargs,
233
104
  )
234
105
 
235
106
  if not return_dict:
236
- output = (logits,) + outputs[1:]
237
- return (loss,) + output if loss is not None else output
107
+ output_tuple = (logits,) + outputs[1:]
108
+ output = (loss,) + output_tuple if loss is not None else output_tuple
109
+ output = output + (token_accuracy,) if token_accuracy is not None else output
110
+ return output
238
111
 
239
- return CausalLMOutputWithPast(
112
+ # Return custom output class with token_accuracy field
113
+ return LigerCausalLMOutputWithPast(
240
114
  loss=loss,
241
115
  logits=logits,
242
116
  past_key_values=outputs.past_key_values,
243
117
  hidden_states=outputs.hidden_states,
244
118
  attentions=outputs.attentions,
119
+ token_accuracy=token_accuracy,
245
120
  )