liger-kernel 0.6.0__py3-none-any.whl → 0.6.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.
@@ -2,6 +2,7 @@ from typing import Optional
2
2
 
3
3
  from liger_kernel.ops.cross_entropy import LigerCrossEntropyFunction
4
4
  from liger_kernel.ops.dyt import LigerDyTFunction
5
+ from liger_kernel.ops.fused_add_rms_norm import LigerFusedAddRMSNormFunction
5
6
  from liger_kernel.ops.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyFunction
6
7
  from liger_kernel.ops.fused_linear_jsd import LigerFusedLinearJSDFunction
7
8
  from liger_kernel.ops.fused_neighborhood_attention import LigerFusedNeighborhoodAttentionFunction
@@ -63,6 +64,7 @@ def liger_fused_linear_cross_entropy(
63
64
  reduction: str = "mean",
64
65
  softcap: Optional[float] = None,
65
66
  return_z_loss: bool = False,
67
+ accum_dtype=None,
66
68
  ):
67
69
  loss, z_loss = LigerFusedLinearCrossEntropyFunction.apply(
68
70
  input,
@@ -76,6 +78,7 @@ def liger_fused_linear_cross_entropy(
76
78
  reduction,
77
79
  softcap,
78
80
  return_z_loss,
81
+ accum_dtype,
79
82
  )
80
83
  if not return_z_loss:
81
84
  return loss
@@ -253,6 +256,10 @@ def liger_rms_norm(X, W, eps, offset: float = 0.0, casting_mode: str = "llama",
253
256
  return LigerRMSNormFunction.apply(X, W, eps, offset, casting_mode, in_place)
254
257
 
255
258
 
259
+ def liger_fused_add_rms_norm(X, R, W, eps, offset: float = 0.0, casting_mode: str = "llama", in_place: bool = True):
260
+ return LigerFusedAddRMSNormFunction.apply(X, R, W, eps, offset, casting_mode, in_place)
261
+
262
+
256
263
  def liger_rope(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
257
264
  return LigerRopeFunction.apply(q, k, cos, sin, position_ids, unsqueeze_dim)
258
265
 
@@ -0,0 +1,39 @@
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from liger_kernel.ops.fused_add_rms_norm import LigerFusedAddRMSNormFunction
5
+
6
+
7
+ class LigerFusedAddRMSNorm(nn.Module):
8
+ def __init__(
9
+ self,
10
+ hidden_size,
11
+ eps=1e-6,
12
+ offset=0.0,
13
+ casting_mode="llama",
14
+ init_fn="ones",
15
+ in_place=False,
16
+ ):
17
+ super().__init__()
18
+ assert init_fn in [
19
+ "ones",
20
+ "zeros",
21
+ ], f"init_fn must be either 'ones' or 'zeros', got {init_fn}"
22
+ self.weight = nn.Parameter(torch.ones(hidden_size) if init_fn == "ones" else torch.zeros(hidden_size))
23
+ self.variance_epsilon, self.offset, self.casting_mode, self.in_place = (eps, offset, casting_mode, in_place)
24
+
25
+ def forward(self, hidden_states, residual):
26
+ return LigerFusedAddRMSNormFunction.apply(
27
+ hidden_states,
28
+ residual,
29
+ self.weight,
30
+ self.variance_epsilon,
31
+ self.offset,
32
+ self.casting_mode,
33
+ self.in_place,
34
+ )
35
+
36
+ def extra_repr(self):
37
+ return (
38
+ f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}, offset={self.offset}, in_place={self.in_place}"
39
+ )
@@ -15,6 +15,7 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
15
15
  reduction: str = "mean",
16
16
  softcap: Optional[float] = None,
17
17
  return_z_loss: bool = False,
18
+ accum_dtype: Optional[torch.dtype] = None,
18
19
  ):
19
20
  super().__init__()
20
21
  assert (label_smoothing >= 0) and (label_smoothing <= 1), (
@@ -32,6 +33,7 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
32
33
  self.reduction = reduction
33
34
  self.softcap = softcap
34
35
  self.return_z_loss = return_z_loss
36
+ self.accum_dtype = accum_dtype
35
37
 
36
38
  def forward(self, lin_weight, _input, target, bias=None):
37
39
  loss, z_loss = LigerFusedLinearCrossEntropyFunction.apply(
@@ -46,6 +48,7 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
46
48
  self.reduction,
47
49
  self.softcap,
48
50
  self.return_z_loss,
51
+ self.accum_dtype,
49
52
  )
50
53
  if not self.return_z_loss:
51
54
  return loss
@@ -0,0 +1,93 @@
1
+ """
2
+ Liger Kernel implementation of Llama4 Rotary Position Embedding (RoPE).
3
+ Supports both text and vision RoPE variants with fused operations for optimal performance.
4
+ """
5
+
6
+ import torch
7
+
8
+ from liger_kernel.ops.llama4_rope import LigerLlama4RopeFunction
9
+
10
+
11
+ def liger_llama4_text_rotary_pos_emb(
12
+ xq: torch.Tensor,
13
+ xk: torch.Tensor,
14
+ freqs_cis: torch.Tensor,
15
+ ) -> tuple[torch.Tensor, torch.Tensor]:
16
+ """
17
+ Liger-optimized implementation of Llama4 text rotary position embedding.
18
+
19
+ This implementation uses a fused Triton kernel for complex multiplication,
20
+ providing significant performance improvements over the original PyTorch implementation.
21
+
22
+ Args:
23
+ xq (torch.Tensor): Query tensor of shape (batch_size, seq_len, num_heads, head_dim)
24
+ xk (torch.Tensor): Key tensor of shape (batch_size, seq_len, num_heads, head_dim)
25
+ freqs_cis (torch.Tensor): Complex frequency tensor from Llama4TextRotaryEmbedding
26
+
27
+ Returns:
28
+ Tuple[torch.Tensor, torch.Tensor]: Rotated query and key tensors
29
+ """
30
+ # Use fused Triton kernel for complex RoPE
31
+ return LigerLlama4RopeFunction.apply(xq, xk, freqs_cis)
32
+
33
+
34
+ def liger_llama4_vision_rotary_pos_emb(
35
+ query: torch.Tensor,
36
+ key: torch.Tensor,
37
+ freqs_ci: torch.Tensor,
38
+ ) -> tuple[torch.Tensor, torch.Tensor]:
39
+ """
40
+ Liger-optimized implementation of Llama4 vision rotary position embedding.
41
+
42
+ This implementation uses the same fused Triton kernel as text RoPE,
43
+ providing performance improvements for vision transformer attention.
44
+
45
+ Args:
46
+ query (torch.Tensor): Query tensor of shape (batch_size, seq_len, num_heads, head_dim)
47
+ key (torch.Tensor): Key tensor of shape (batch_size, seq_len, num_heads, head_dim)
48
+ freqs_ci (torch.Tensor): Complex frequency tensor for 2D positions
49
+
50
+ Returns:
51
+ Tuple[torch.Tensor, torch.Tensor]: Rotated query and key tensors
52
+ """
53
+ # Handle broadcasting for vision RoPE
54
+ if freqs_ci.dim() == 3:
55
+ try:
56
+ # Try the regular 3D expansion
57
+ freqs_ci = freqs_ci.unsqueeze(0).expand(query.shape[0], -1, -1)
58
+ except RuntimeError as e:
59
+ if "expand" in str(e) and "4" in str(e):
60
+ # The tensor is actually 4D internally, handle it differently
61
+ freqs_ci = freqs_ci.squeeze(1) # Remove the middle dimension
62
+ freqs_ci = freqs_ci.unsqueeze(0).expand(query.shape[0], -1, -1)
63
+ else:
64
+ raise e
65
+ elif freqs_ci.dim() == 4: # (1, seq_len, 1, head_dim//2) - already properly shaped
66
+ # Squeeze the middle dimension to get (1, seq_len, head_dim//2)
67
+ freqs_ci = freqs_ci.squeeze(2)
68
+ elif freqs_ci.dim() == 2: # (seq_len, head_dim//2) - needs expansion
69
+ freqs_ci = freqs_ci.unsqueeze(0).expand(query.shape[0], -1, -1)
70
+ else:
71
+ raise ValueError(f"Unexpected freqs_ci shape: {freqs_ci.shape}")
72
+
73
+ # Use the same fused kernel as text RoPE
74
+ return LigerLlama4RopeFunction.apply(query, key, freqs_ci)
75
+
76
+
77
+ # Note: We only patch the functions, not the classes
78
+ # The original Llama4TextRotaryEmbedding and Llama4VisionRotaryEmbedding classes remain unchanged
79
+
80
+
81
+ # Convenience functions for monkey patching
82
+ def apply_liger_llama4_rope_full(modeling_module):
83
+ """
84
+ Apply Liger optimizations to Llama4 RoPE functions.
85
+
86
+ Args:
87
+ modeling_module: The transformers modeling module to patch
88
+ """
89
+ # Replace the text RoPE function
90
+ modeling_module.apply_rotary_emb = liger_llama4_text_rotary_pos_emb
91
+
92
+ # Replace the vision RoPE function
93
+ modeling_module.vision_apply_rotary_emb = liger_llama4_vision_rotary_pos_emb
@@ -255,7 +255,7 @@ def multimodal_forward(
255
255
  shift_labels = shift_labels.view(-1).to(hidden_device)
256
256
 
257
257
  lce = LigerFusedLinearCrossEntropyLoss()
258
- loss = lce(self.language_model.lm_head.weight, shift_hidden_states, shift_labels)
258
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
259
259
  else:
260
260
  logits = self.lm_head(kept_hidden_states)
261
261
  if labels is not None:
@@ -0,0 +1,150 @@
1
+ from typing import List
2
+ from typing import Optional
3
+ from typing import Tuple
4
+ from typing import Union
5
+
6
+ import torch
7
+
8
+ from transformers.modeling_outputs import CausalLMOutputWithPast
9
+ from transformers.utils.deprecation import deprecate_kwarg
10
+
11
+ from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
12
+
13
+
14
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
15
+ def lce_forward(
16
+ self,
17
+ input_ids: 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
+ return_dict: 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
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
32
+ r"""
33
+ Args:
34
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
35
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
36
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
37
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
38
+
39
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
40
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
41
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
42
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
43
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
44
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
45
+
46
+ Returns:
47
+
48
+ Example:
49
+
50
+ ```python
51
+ >>> from PIL import Image
52
+ >>> from transformers import AutoTokenizer, Glm4vForConditionalGeneration
53
+
54
+ >>> MODEL_PATH = "THUDM/GLM-4.1V-9B-Thinking"
55
+ >>> messages = [
56
+ {
57
+ "role": "user",
58
+ "content": [
59
+ {
60
+ "type": "image",
61
+ "url": "https://upload.wikimedia.org/wikipedia/commons/f/fa/Grayscale_8bits_palette_sample_image.png"
62
+ },
63
+ {
64
+ "type": "text",
65
+ "text": "describe this image"
66
+ }
67
+ ],
68
+ }
69
+ ]
70
+ >>> processor = AutoProcessor.from_pretrained(MODEL_PATH, use_fast=True)
71
+ >>> model = Glm4vForConditionalGeneration.from_pretrained(
72
+ pretrained_model_name_or_path=MODEL_PATH,
73
+ torch_dtype=torch.bfloat16,
74
+ device_map="auto",
75
+ )
76
+ >>> inputs = processor.apply_chat_template(
77
+ messages,
78
+ tokenize=True,
79
+ add_generation_prompt=True,
80
+ return_dict=True,
81
+ return_tensors="pt"
82
+ ).to(model.device)
83
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=8192)
84
+ output_text = processor.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=False)
85
+ <think>Got it, let's describe the image. First, there's a vintage car, specifically a Volkswagen Beetle
86
+ ```"""
87
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
88
+ output_hidden_states = (
89
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
90
+ )
91
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
92
+
93
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
94
+ outputs = self.model(
95
+ input_ids=input_ids,
96
+ attention_mask=attention_mask,
97
+ position_ids=position_ids,
98
+ past_key_values=past_key_values,
99
+ inputs_embeds=inputs_embeds,
100
+ use_cache=use_cache,
101
+ output_attentions=output_attentions,
102
+ output_hidden_states=output_hidden_states,
103
+ return_dict=return_dict,
104
+ cache_position=cache_position,
105
+ **kwargs,
106
+ )
107
+
108
+ hidden_states = outputs[0]
109
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
110
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
111
+ kept_hidden_states = hidden_states[:, slice_indices, :]
112
+
113
+ shift_labels = kwargs.pop("shift_labels", None)
114
+ logits = None
115
+ loss = None
116
+
117
+ if skip_logits and labels is None and shift_labels is None:
118
+ raise ValueError("skip_logits is True, but labels and shift_labels are None")
119
+
120
+ if skip_logits is None:
121
+ # By default, if in training mode, don't materialize logits
122
+ skip_logits = self.training and (labels is not None or shift_labels is not None)
123
+
124
+ if skip_logits:
125
+ loss = LigerForCausalLMLoss(
126
+ hidden_states=kept_hidden_states,
127
+ lm_head_weight=self.lm_head.weight,
128
+ labels=labels,
129
+ shift_labels=shift_labels,
130
+ hidden_size=self.config.hidden_size,
131
+ **kwargs,
132
+ )
133
+
134
+ else:
135
+ logits = self.lm_head(kept_hidden_states)
136
+ if labels is not None:
137
+ loss = self.loss_function(
138
+ logits=logits,
139
+ labels=labels,
140
+ vocab_size=self.config.vocab_size,
141
+ **kwargs,
142
+ )
143
+
144
+ return CausalLMOutputWithPast(
145
+ loss=loss,
146
+ logits=logits,
147
+ past_key_values=outputs.past_key_values,
148
+ hidden_states=outputs.hidden_states,
149
+ attentions=outputs.attentions,
150
+ )
@@ -13,6 +13,7 @@ def fixed_fused_linear_cross_entropy(
13
13
  num_items_in_batch: Optional[int] = None,
14
14
  ignore_index: int = -100,
15
15
  final_logit_softcapping: Optional[float] = None,
16
+ accum_dtype: Optional[torch.dtype] = None,
16
17
  **kwargs,
17
18
  ):
18
19
  reduction = "sum" if num_items_in_batch is not None else "mean"
@@ -23,6 +24,7 @@ def fixed_fused_linear_cross_entropy(
23
24
  reduction=reduction,
24
25
  ignore_index=ignore_index,
25
26
  softcap=final_logit_softcapping,
27
+ accum_dtype=accum_dtype,
26
28
  )
27
29
  if reduction == "sum":
28
30
  loss = loss / num_items_in_batch
@@ -190,7 +190,9 @@ def lce_forward(
190
190
  output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
191
191
  )
192
192
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
193
-
193
+ # Filter out accum_dtype from kwargs for model call as MllamaTextModel doesn't accept it in transformers 4.49.0
194
+ # but preserve it for loss function calls
195
+ model_kwargs = {k: v for k, v in kwargs.items() if k != "accum_dtype"}
194
196
  # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
195
197
  outputs = self.model(
196
198
  input_ids=input_ids,
@@ -206,7 +208,7 @@ def lce_forward(
206
208
  output_hidden_states=output_hidden_states,
207
209
  return_dict=return_dict,
208
210
  cache_position=cache_position,
209
- **kwargs,
211
+ **model_kwargs,
210
212
  )
211
213
 
212
214
  hidden_states = outputs[0]
@@ -5,131 +5,12 @@ from typing import Union
5
5
 
6
6
  import torch
7
7
 
8
- from torch.nn import CrossEntropyLoss
8
+ from transformers.modeling_outputs import BaseModelOutputWithPast
9
9
  from transformers.modeling_outputs import CausalLMOutputWithPast
10
- from transformers.utils.deprecation import deprecate_kwarg
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
 
15
13
 
16
- def lce_forward_deprecated(
17
- self,
18
- input_ids: torch.LongTensor = None,
19
- attention_mask: Optional[torch.Tensor] = None,
20
- position_ids: Optional[torch.LongTensor] = None,
21
- past_key_values: Optional[List[torch.FloatTensor]] = None,
22
- inputs_embeds: Optional[torch.FloatTensor] = None,
23
- labels: Optional[torch.LongTensor] = None,
24
- use_cache: Optional[bool] = None,
25
- output_attentions: Optional[bool] = None,
26
- output_hidden_states: Optional[bool] = None,
27
- return_dict: Optional[bool] = None,
28
- cache_position: Optional[torch.LongTensor] = None,
29
- skip_logits: Optional[bool] = None,
30
- ) -> Union[Tuple, CausalLMOutputWithPast]:
31
- r"""
32
- Copy paste phi3 forward from transfomers v4.44.2 but replace torch cross entropy with liger fused linear cross entropy
33
-
34
-
35
- Args:
36
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
37
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
38
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
39
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
40
-
41
- Returns:
42
-
43
- Example:
44
-
45
- ```python
46
- >>> from transformers import AutoTokenizer, Phi3ForCausalLM
47
-
48
- >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
49
- >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
50
-
51
- >>> prompt = "This is an example script ."
52
- >>> inputs = tokenizer(prompt, return_tensors="pt")
53
-
54
- >>> # Generate
55
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
56
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
57
- 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
58
- ```"""
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
- return_dict=return_dict,
77
- )
78
-
79
- hidden_states = outputs[0]
80
-
81
- loss = None
82
- logits = None
83
-
84
- if skip_logits and labels is None:
85
- raise ValueError("skip_logits is True, but labels is None")
86
-
87
- if skip_logits is None:
88
- # By default, if in training mode, don't materialize logits
89
- skip_logits = self.training and labels is not None
90
-
91
- if skip_logits:
92
- shift_hidden_states = hidden_states[..., :-1, :].contiguous()
93
- shift_labels = labels[..., 1:].contiguous()
94
-
95
- # flatten tokens
96
- shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
97
- shift_labels = shift_labels.view(-1)
98
-
99
- lce = LigerFusedLinearCrossEntropyLoss()
100
- loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
101
- else:
102
- logits = self.lm_head(hidden_states)
103
-
104
- loss = None
105
- if labels is not None:
106
- # Upcast to float if we need to compute the loss to avoid potential precision issues
107
- logits = logits.float()
108
- # Shift so that tokens < n predict n
109
- shift_logits = logits[..., :-1, :].contiguous()
110
- shift_labels = labels[..., 1:].contiguous()
111
- # Flatten the tokens
112
- loss_fct = CrossEntropyLoss()
113
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
114
- shift_labels = shift_labels.view(-1)
115
- # Enable model parallelism
116
- shift_labels = shift_labels.to(shift_logits.device)
117
- loss = loss_fct(shift_logits, shift_labels)
118
-
119
- if not return_dict:
120
- output = (logits,) + outputs[1:]
121
- return (loss,) + output if loss is not None else output
122
-
123
- return CausalLMOutputWithPast(
124
- loss=loss,
125
- logits=logits,
126
- past_key_values=outputs.past_key_values,
127
- hidden_states=outputs.hidden_states,
128
- attentions=outputs.attentions,
129
- )
130
-
131
-
132
- @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
133
14
  def lce_forward(
134
15
  self,
135
16
  input_ids: torch.LongTensor = None,
@@ -148,73 +29,41 @@ def lce_forward(
148
29
  **kwargs,
149
30
  ) -> Union[Tuple, CausalLMOutputWithPast]:
150
31
  r"""
151
- Args:
152
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
153
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
154
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
155
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
156
-
157
- logits_to_keep (`int` or `torch.Tensor`, *optional*):
158
- If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
159
- `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
160
- token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
161
- If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
162
- This is useful when using packed tensor format (single dimension for batch and sequence length).
163
-
164
- Returns:
165
-
166
32
  Example:
167
33
 
168
34
  ```python
169
35
  >>> from transformers import AutoTokenizer, Phi3ForCausalLM
170
36
 
171
- >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
172
- >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
37
+ >>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
38
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
173
39
 
174
- >>> prompt = "This is an example script ."
40
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
175
41
  >>> inputs = tokenizer(prompt, return_tensors="pt")
176
42
 
177
43
  >>> # Generate
178
44
  >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
179
45
  >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
180
- 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
46
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
181
47
  ```"""
182
48
 
183
- from transformers.models.phi3.modeling_phi3 import logging
184
-
185
- logger = logging.get_logger(__name__)
186
-
187
- if (
188
- use_cache
189
- and self.config.rope_scaling
190
- and cache_position is not None
191
- and cache_position[0] == self.config.original_max_position_embeddings
192
- ):
193
- logger.warning(
194
- 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."
195
- )
196
-
197
49
  output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
198
50
  output_hidden_states = (
199
51
  output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
200
52
  )
201
53
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
202
54
 
203
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
204
- outputs = self.model(
55
+ outputs: BaseModelOutputWithPast = self.model(
205
56
  input_ids=input_ids,
206
57
  attention_mask=attention_mask,
207
58
  position_ids=position_ids,
208
59
  past_key_values=past_key_values,
209
60
  inputs_embeds=inputs_embeds,
210
61
  use_cache=use_cache,
211
- output_attentions=output_attentions,
212
- output_hidden_states=output_hidden_states,
213
- return_dict=return_dict,
62
+ cache_position=cache_position,
214
63
  **kwargs,
215
64
  )
216
65
 
217
- hidden_states = outputs[0]
66
+ hidden_states = outputs.last_hidden_state
218
67
  # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
219
68
  slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
220
69
  kept_hidden_states = hidden_states[:, slice_indices, :]