zifei9 commited on
Commit
ef4e33e
·
verified ·
1 Parent(s): eb1d3de

Update modeling_llama.py

Browse files

updating based on transformers==4.49

Files changed (1) hide show
  1. modeling_llama.py +677 -474
modeling_llama.py CHANGED
@@ -17,162 +17,68 @@
17
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
  # See the License for the specific language governing permissions and
19
  # limitations under the License.
 
 
20
  import math
 
21
  from typing import List, Optional, Tuple, Union
22
 
23
  import torch
24
  import torch.nn.functional as F
25
  import torch.utils.checkpoint
26
  from torch import nn
 
27
 
28
- from transformers.models.llama.modeling_llama import LlamaRMSNorm
29
  from transformers.activations import ACT2FN
30
  from transformers.cache_utils import Cache, DynamicCache, StaticCache
31
- from transformers.generation import GenerationMixin
32
  from transformers.modeling_attn_mask_utils import AttentionMaskConverter
33
- from transformers.modeling_flash_attention_utils import FlashAttentionKwargs, _flash_attention_forward
34
  from transformers.modeling_outputs import (
35
  BaseModelOutputWithPast,
36
  CausalLMOutputWithPast,
37
  QuestionAnsweringModelOutput,
38
  SequenceClassifierOutputWithPast,
39
- TokenClassifierOutput,
40
  )
41
- from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
42
  from transformers.modeling_utils import PreTrainedModel
43
- from transformers.processing_utils import Unpack
44
  from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
45
  from transformers.utils import (
46
- LossKwargs,
47
- add_code_sample_docstrings,
48
  add_start_docstrings,
49
  add_start_docstrings_to_model_forward,
 
50
  is_flash_attn_greater_or_equal_2_10,
51
  logging,
52
  replace_return_docstrings,
53
  )
54
  from .configuration_llama import LlamaConfig
55
- from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
56
-
57
-
58
- logger = logging.get_logger(__name__)
59
-
60
- _CHECKPOINT_FOR_DOC = "meta-llama/Llama-2-7b-hf"
61
- _CONFIG_FOR_DOC = "LlamaConfig"
62
-
63
- ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
64
-
65
-
66
- class LlamaRotaryEmbedding(nn.Module):
67
- def __init__(
68
- self,
69
- dim=None,
70
- max_position_embeddings=2048,
71
- base=10000,
72
- device=None,
73
- scaling_factor=1.0,
74
- rope_type="default",
75
- config: Optional[LlamaConfig] = None,
76
- ):
77
- super().__init__()
78
- # TODO (joao): remove the `if` below, only used for BC
79
- self.rope_kwargs = {}
80
- if config is None:
81
- logger.warning_once(
82
- "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
83
- "`config` argument. All other arguments will be removed in v4.46"
84
- )
85
- self.rope_kwargs = {
86
- "rope_type": rope_type,
87
- "factor": scaling_factor,
88
- "dim": dim,
89
- "base": base,
90
- "max_position_embeddings": max_position_embeddings,
91
- }
92
- self.rope_type = rope_type
93
- self.max_seq_len_cached = max_position_embeddings
94
- self.original_max_seq_len = max_position_embeddings
95
- else:
96
- # BC: "rope_type" was originally "type"
97
- if config.rope_scaling is not None:
98
- self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
99
- else:
100
- self.rope_type = "default"
101
- self.max_seq_len_cached = config.max_position_embeddings
102
- self.original_max_seq_len = config.max_position_embeddings
103
-
104
- self.config = config
105
- self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
106
-
107
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
108
- self.register_buffer("inv_freq", inv_freq, persistent=False)
109
- self.original_inv_freq = self.inv_freq
110
-
111
- def _dynamic_frequency_update(self, position_ids, device):
112
- """
113
- dynamic RoPE layers should recompute `inv_freq` in the following situations:
114
- 1 - growing beyond the cached sequence length (allow scaling)
115
- 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
116
- """
117
- seq_len = torch.max(position_ids) + 1
118
- if seq_len > self.max_seq_len_cached: # growth
119
- inv_freq, self.attention_scaling = self.rope_init_fn(
120
- self.config, device, seq_len=seq_len, **self.rope_kwargs
121
- )
122
- self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
123
- self.max_seq_len_cached = seq_len
124
-
125
- if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
126
- self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
127
- self.max_seq_len_cached = self.original_max_seq_len
128
 
129
- @torch.no_grad()
130
- def forward(self, x, position_ids):
131
- if "dynamic" in self.rope_type:
132
- self._dynamic_frequency_update(position_ids, device=x.device)
133
 
134
- # Core RoPE block
135
- inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
136
- position_ids_expanded = position_ids[:, None, :].float()
137
- # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
138
- device_type = x.device.type
139
- device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
140
- with torch.autocast(device_type=device_type, enabled=False):
141
- freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
142
- emb = torch.cat((freqs, freqs), dim=-1)
143
- cos = emb.cos()
144
- sin = emb.sin()
145
 
146
- # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
147
- cos = cos * self.attention_scaling
148
- sin = sin * self.attention_scaling
149
 
150
- return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
151
 
 
152
 
153
- class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
154
- """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
155
-
156
- def __init__(self, *args, **kwargs):
157
- logger.warning_once(
158
- "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
159
- "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
160
- )
161
- kwargs["rope_type"] = "linear"
162
- super().__init__(*args, **kwargs)
163
 
 
 
 
 
 
 
 
 
 
 
164
 
165
- class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
166
- """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
167
 
168
- def __init__(self, *args, **kwargs):
169
- logger.warning_once(
170
- "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
171
- "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
172
- "__init__)."
173
- )
174
- kwargs["rope_type"] = "dynamic"
175
- super().__init__(*args, **kwargs)
176
 
177
 
178
  class LlamaMLP(nn.Module):
@@ -181,9 +87,9 @@ class LlamaMLP(nn.Module):
181
  self.config = config
182
  self.hidden_size = config.hidden_size
183
  self.intermediate_size = config.intermediate_size
184
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
185
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
186
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
187
  self.act_fn = ACT2FN[config.hidden_act]
188
 
189
  def forward(self, x):
@@ -194,13 +100,24 @@ class LlamaMLP(nn.Module):
194
  down_proj_slices = self.down_proj.weight.split(slice, dim=1)
195
 
196
  gate_proj = torch.cat(
197
- [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
 
 
 
 
 
 
 
 
 
 
 
198
  )
199
- up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
200
 
201
  intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
202
  down_proj = [
203
- F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
 
204
  ]
205
  down_proj = sum(down_proj)
206
  else:
@@ -217,7 +134,9 @@ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
217
  batch, num_key_value_heads, slen, head_dim = hidden_states.shape
218
  if n_rep == 1:
219
  return hidden_states
220
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
 
 
221
  return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
222
 
223
 
@@ -238,20 +157,59 @@ class LlamaAttention(nn.Module):
238
  self.attention_dropout = config.attention_dropout
239
  self.hidden_size = config.hidden_size
240
  self.num_heads = config.num_attention_heads
241
- self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
242
  self.num_key_value_heads = config.num_key_value_heads
243
  self.num_key_value_groups = self.num_heads // self.num_key_value_heads
244
  self.max_position_embeddings = config.max_position_embeddings
245
  self.rope_theta = config.rope_theta
246
  self.is_causal = True
247
 
248
- self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
249
- self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
250
- self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
251
- self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
- # TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
254
- self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
  def forward(
257
  self,
@@ -262,26 +220,36 @@ class LlamaAttention(nn.Module):
262
  output_attentions: bool = False,
263
  use_cache: bool = False,
264
  cache_position: Optional[torch.LongTensor] = None,
265
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
266
  **kwargs,
267
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
268
  bsz, q_len, _ = hidden_states.size()
269
 
270
  if self.config.pretraining_tp > 1:
271
- key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
 
 
272
  query_slices = self.q_proj.weight.split(
273
  (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
274
  )
275
  key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
276
  value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
277
 
278
- query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
 
 
 
279
  query_states = torch.cat(query_states, dim=-1)
280
 
281
- key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
 
 
 
282
  key_states = torch.cat(key_states, dim=-1)
283
 
284
- value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
 
 
 
285
  value_states = torch.cat(value_states, dim=-1)
286
 
287
  else:
@@ -289,38 +257,47 @@ class LlamaAttention(nn.Module):
289
  key_states = self.k_proj(hidden_states)
290
  value_states = self.v_proj(hidden_states)
291
 
292
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
293
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
294
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
295
-
296
- if position_embeddings is None:
297
- logger.warning_once(
298
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
299
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
300
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
301
- "removed and `position_embeddings` will be mandatory."
302
- )
303
- cos, sin = self.rotary_emb(value_states, position_ids)
304
- else:
305
- cos, sin = position_embeddings
306
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
307
 
308
  if past_key_value is not None:
309
  # sin and cos are specific to RoPE models; cache_position needed for the static cache
310
  cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
311
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
 
 
312
 
313
  key_states = repeat_kv(key_states, self.num_key_value_groups)
314
  value_states = repeat_kv(value_states, self.num_key_value_groups)
315
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
 
 
 
316
 
317
  if attention_mask is not None: # no matter the length, we just slice it
318
  causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
319
  attn_weights = attn_weights + causal_mask
320
 
321
  # upcast attention to fp32
322
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
323
- attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
 
 
 
 
324
  attn_output = torch.matmul(attn_weights, value_states)
325
 
326
  if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
@@ -331,12 +308,21 @@ class LlamaAttention(nn.Module):
331
 
332
  attn_output = attn_output.transpose(1, 2).contiguous()
333
 
334
- attn_output = attn_output.reshape(bsz, q_len, -1)
335
 
336
  if self.config.pretraining_tp > 1:
337
- attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
338
- o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
339
- attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
 
 
 
 
 
 
 
 
 
340
  else:
341
  attn_output = self.o_proj(attn_output)
342
 
@@ -370,15 +356,8 @@ class LlamaFlashAttention2(LlamaAttention):
370
  output_attentions: bool = False,
371
  use_cache: bool = False,
372
  cache_position: Optional[torch.LongTensor] = None,
373
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
374
- **kwargs: Unpack[FlashAttentionKwargs],
375
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
376
- if isinstance(past_key_value, StaticCache):
377
- raise ValueError(
378
- "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
379
- "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
380
- )
381
-
382
  output_attentions = False
383
 
384
  bsz, q_len, _ = hidden_states.size()
@@ -390,26 +369,29 @@ class LlamaFlashAttention2(LlamaAttention):
390
  # Flash attention requires the input to have the shape
391
  # batch_size x seq_length x head_dim x hidden_dim
392
  # therefore we just need to keep the original shape
393
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
394
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
395
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
 
 
 
 
 
 
 
 
 
 
 
396
 
397
- if position_embeddings is None:
398
- logger.warning_once(
399
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
400
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
401
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
402
- "removed and `position_embeddings` will be mandatory."
403
- )
404
- cos, sin = self.rotary_emb(value_states, position_ids)
405
- else:
406
- cos, sin = position_embeddings
407
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
408
 
409
  if past_key_value is not None:
410
  # sin and cos are specific to RoPE models; cache_position needed for the static cache
411
  cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
412
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
 
 
413
 
414
  # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
415
  # to be able to avoid many of these transpose/reshape/view.
@@ -445,21 +427,16 @@ class LlamaFlashAttention2(LlamaAttention):
445
  key_states = key_states.to(target_dtype)
446
  value_states = value_states.to(target_dtype)
447
 
448
- attn_output = _flash_attention_forward(
449
  query_states,
450
  key_states,
451
  value_states,
452
  attention_mask,
453
  q_len,
454
- position_ids=position_ids,
455
  dropout=dropout_rate,
456
- sliding_window=getattr(self, "sliding_window", None),
457
- use_top_left_mask=self._flash_attn_uses_top_left_mask,
458
- is_causal=self.is_causal,
459
- **kwargs,
460
  )
461
 
462
- attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
463
  attn_output = self.o_proj(attn_output)
464
 
465
  if not output_attentions:
@@ -467,6 +444,131 @@ class LlamaFlashAttention2(LlamaAttention):
467
 
468
  return attn_output, attn_weights, past_key_value
469
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
 
471
  class LlamaSdpaAttention(LlamaAttention):
472
  """
@@ -485,8 +587,6 @@ class LlamaSdpaAttention(LlamaAttention):
485
  output_attentions: bool = False,
486
  use_cache: bool = False,
487
  cache_position: Optional[torch.LongTensor] = None,
488
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
489
- **kwargs,
490
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
491
  if output_attentions:
492
  # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
@@ -502,7 +602,6 @@ class LlamaSdpaAttention(LlamaAttention):
502
  output_attentions=output_attentions,
503
  use_cache=use_cache,
504
  cache_position=cache_position,
505
- position_embeddings=position_embeddings,
506
  )
507
 
508
  bsz, q_len, _ = hidden_states.size()
@@ -511,26 +610,30 @@ class LlamaSdpaAttention(LlamaAttention):
511
  key_states = self.k_proj(hidden_states)
512
  value_states = self.v_proj(hidden_states)
513
 
514
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
515
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
516
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
 
 
 
 
 
 
 
 
 
 
 
517
 
518
- if position_embeddings is None:
519
- logger.warning_once(
520
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
521
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
522
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
523
- "removed and `position_embeddings` will be mandatory."
524
- )
525
- cos, sin = self.rotary_emb(value_states, position_ids)
526
- else:
527
- cos, sin = position_embeddings
528
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
529
 
530
  if past_key_value is not None:
531
  # sin and cos are specific to RoPE models; cache_position needed for the static cache
532
  cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
533
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
 
 
534
 
535
  key_states = repeat_kv(key_states, self.num_key_value_groups)
536
  value_states = repeat_kv(value_states, self.num_key_value_groups)
@@ -546,21 +649,19 @@ class LlamaSdpaAttention(LlamaAttention):
546
  key_states = key_states.contiguous()
547
  value_states = value_states.contiguous()
548
 
549
- # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
550
- # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
551
- is_causal = True if causal_mask is None and q_len > 1 else False
552
-
553
  attn_output = torch.nn.functional.scaled_dot_product_attention(
554
  query_states,
555
  key_states,
556
  value_states,
557
  attn_mask=causal_mask,
558
  dropout_p=self.attention_dropout if self.training else 0.0,
559
- is_causal=is_causal,
560
  )
561
 
562
  attn_output = attn_output.transpose(1, 2).contiguous()
563
- attn_output = attn_output.view(bsz, q_len, -1)
564
 
565
  attn_output = self.o_proj(attn_output)
566
 
@@ -579,24 +680,29 @@ class LlamaDecoderLayer(nn.Module):
579
  super().__init__()
580
  self.hidden_size = config.hidden_size
581
 
582
- self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
 
 
583
 
584
  self.mlp = LlamaMLP(config)
585
  self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
586
- self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
 
 
587
 
588
  def forward(
589
  self,
590
  hidden_states: torch.Tensor,
591
  attention_mask: Optional[torch.Tensor] = None,
592
  position_ids: Optional[torch.LongTensor] = None,
593
- past_key_value: Optional[Cache] = None,
594
  output_attentions: Optional[bool] = False,
595
  use_cache: Optional[bool] = False,
596
  cache_position: Optional[torch.LongTensor] = None,
597
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
598
  **kwargs,
599
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
 
 
600
  """
601
  Args:
602
  hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
@@ -610,15 +716,12 @@ class LlamaDecoderLayer(nn.Module):
610
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
611
  (see `past_key_values`).
612
  past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
613
- cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
614
- Indices depicting the position of the input sequence tokens in the sequence
615
- position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
616
- Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
617
- with `head_dim` being the embedding dimension of each attention head.
618
- kwargs (`dict`, *optional*):
619
- Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
620
- into the model
621
  """
 
 
 
 
 
622
  residual = hidden_states
623
 
624
  hidden_states = self.input_layernorm(hidden_states)
@@ -632,7 +735,6 @@ class LlamaDecoderLayer(nn.Module):
632
  output_attentions=output_attentions,
633
  use_cache=use_cache,
634
  cache_position=cache_position,
635
- position_embeddings=position_embeddings,
636
  **kwargs,
637
  )
638
  hidden_states = residual + hidden_states
@@ -684,8 +786,6 @@ class LlamaPreTrainedModel(PreTrainedModel):
684
  _supports_flash_attn_2 = True
685
  _supports_sdpa = True
686
  _supports_cache_class = True
687
- _supports_quantized_cache = True
688
- _supports_static_cache = True
689
 
690
  def _init_weights(self, module):
691
  std = self.config.initializer_range
@@ -698,6 +798,32 @@ class LlamaPreTrainedModel(PreTrainedModel):
698
  if module.padding_idx is not None:
699
  module.weight.data[module.padding_idx].zero_()
700
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
701
 
702
  LLAMA_INPUTS_DOCSTRING = r"""
703
  Args:
@@ -740,8 +866,7 @@ LLAMA_INPUTS_DOCSTRING = r"""
740
  returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
741
 
742
  Two formats are allowed:
743
- - a [`~cache_utils.Cache`] instance, see our
744
- [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
745
  - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
746
  shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
747
  cache format.
@@ -791,12 +916,16 @@ class LlamaModel(LlamaPreTrainedModel):
791
  self.padding_idx = config.pad_token_id
792
  self.vocab_size = config.vocab_size
793
 
794
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
 
 
795
  self.layers = nn.ModuleList(
796
- [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
 
 
 
797
  )
798
  self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
799
- self.rotary_emb = LlamaRotaryEmbedding(config=config)
800
  self.gradient_checkpointing = False
801
 
802
  # Initialize weights and apply final processing
@@ -814,24 +943,33 @@ class LlamaModel(LlamaPreTrainedModel):
814
  input_ids: torch.LongTensor = None,
815
  attention_mask: Optional[torch.Tensor] = None,
816
  position_ids: Optional[torch.LongTensor] = None,
817
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
818
  inputs_embeds: Optional[torch.FloatTensor] = None,
819
  use_cache: Optional[bool] = None,
820
  output_attentions: Optional[bool] = None,
821
  output_hidden_states: Optional[bool] = None,
822
  return_dict: Optional[bool] = None,
823
  cache_position: Optional[torch.LongTensor] = None,
824
- **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
825
  ) -> Union[Tuple, BaseModelOutputWithPast]:
826
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
 
 
 
 
827
  output_hidden_states = (
828
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
 
 
829
  )
830
  use_cache = use_cache if use_cache is not None else self.config.use_cache
831
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
 
 
832
 
833
  if (input_ids is None) ^ (inputs_embeds is not None):
834
- raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
 
 
835
 
836
  if self.gradient_checkpointing and self.training and use_cache:
837
  logger.warning_once(
@@ -842,35 +980,35 @@ class LlamaModel(LlamaPreTrainedModel):
842
  if inputs_embeds is None:
843
  inputs_embeds = self.embed_tokens(input_ids)
844
 
845
- # kept for BC (non `Cache` `past_key_values` inputs)
846
- return_legacy_cache = False
847
- if use_cache and not isinstance(past_key_values, Cache):
848
- return_legacy_cache = True
849
- if past_key_values is None:
850
- past_key_values = DynamicCache()
851
- else:
852
- past_key_values = DynamicCache.from_legacy_cache(past_key_values)
853
- logger.warning_once(
854
- "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
855
- "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
856
- "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
857
- )
858
 
859
  if cache_position is None:
860
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
 
 
 
861
  cache_position = torch.arange(
862
- past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
 
 
863
  )
 
864
  if position_ids is None:
865
  position_ids = cache_position.unsqueeze(0)
866
 
867
  causal_mask = self._update_causal_mask(
868
- attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
869
  )
870
- hidden_states = inputs_embeds
871
 
872
- # create position embeddings to be shared across the decoder layers
873
- position_embeddings = self.rotary_emb(hidden_states, position_ids)
874
 
875
  # decoder layers
876
  all_hidden_states = () if output_hidden_states else None
@@ -891,7 +1029,6 @@ class LlamaModel(LlamaPreTrainedModel):
891
  output_attentions,
892
  use_cache,
893
  cache_position,
894
- position_embeddings,
895
  )
896
  else:
897
  layer_outputs = decoder_layer(
@@ -902,8 +1039,6 @@ class LlamaModel(LlamaPreTrainedModel):
902
  output_attentions=output_attentions,
903
  use_cache=use_cache,
904
  cache_position=cache_position,
905
- position_embeddings=position_embeddings,
906
- **flash_attn_kwargs,
907
  )
908
 
909
  hidden_states = layer_outputs[0]
@@ -920,12 +1055,15 @@ class LlamaModel(LlamaPreTrainedModel):
920
  if output_hidden_states:
921
  all_hidden_states += (hidden_states,)
922
 
923
- next_cache = next_decoder_cache if use_cache else None
924
- if return_legacy_cache:
925
- next_cache = next_cache.to_legacy_cache()
926
-
927
  if not return_dict:
928
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
 
 
 
 
929
  return BaseModelOutputWithPast(
930
  last_hidden_state=hidden_states,
931
  past_key_values=next_cache,
@@ -938,127 +1076,100 @@ class LlamaModel(LlamaPreTrainedModel):
938
  attention_mask: torch.Tensor,
939
  input_tensor: torch.Tensor,
940
  cache_position: torch.Tensor,
941
- past_key_values: Cache,
942
- output_attentions: bool,
943
  ):
 
 
 
 
 
944
  if self.config._attn_implementation == "flash_attention_2":
945
  if attention_mask is not None and 0.0 in attention_mask:
946
  return attention_mask
947
  return None
948
 
949
- # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
950
- # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
951
- # to infer the attention mask.
952
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
953
- using_static_cache = isinstance(past_key_values, StaticCache)
954
-
955
- # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
956
- if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
957
  if AttentionMaskConverter._ignore_causal_mask_sdpa(
958
  attention_mask,
959
  inputs_embeds=input_tensor,
960
  past_key_values_length=past_seen_tokens,
961
- is_training=self.training,
962
  ):
963
  return None
964
 
965
  dtype, device = input_tensor.dtype, input_tensor.device
 
966
  sequence_length = input_tensor.shape[1]
967
- if using_static_cache:
968
- target_length = past_key_values.get_max_cache_shape()
969
- else:
 
 
970
  target_length = (
971
  attention_mask.shape[-1]
972
  if isinstance(attention_mask, torch.Tensor)
973
  else past_seen_tokens + sequence_length + 1
974
  )
975
 
976
- # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
977
- causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
978
- attention_mask,
979
- sequence_length=sequence_length,
980
- target_length=target_length,
981
  dtype=dtype,
982
  device=device,
983
- cache_position=cache_position,
984
- batch_size=input_tensor.shape[0],
985
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
986
 
987
  if (
988
  self.config._attn_implementation == "sdpa"
989
  and attention_mask is not None
990
  and attention_mask.device.type == "cuda"
991
- and not output_attentions
992
  ):
993
  # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
994
  # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
995
  # Details: https://github.com/pytorch/pytorch/issues/110213
996
- min_dtype = torch.finfo(dtype).min
997
- causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
998
-
999
- return causal_mask
1000
-
1001
- @staticmethod
1002
- def _prepare_4d_causal_attention_mask_with_cache_position(
1003
- attention_mask: torch.Tensor,
1004
- sequence_length: int,
1005
- target_length: int,
1006
- dtype: torch.dtype,
1007
- device: torch.device,
1008
- cache_position: torch.Tensor,
1009
- batch_size: int,
1010
- **kwargs,
1011
- ):
1012
- """
1013
- Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1014
- `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1015
-
1016
- Args:
1017
- attention_mask (`torch.Tensor`):
1018
- A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1019
- `(batch_size, 1, query_length, key_value_length)`.
1020
- sequence_length (`int`):
1021
- The sequence length being processed.
1022
- target_length (`int`):
1023
- The target length: when generating with static cache, the mask should be as long as the static cache,
1024
- to account for the 0 padding, the part of the cache that is not filled yet.
1025
- dtype (`torch.dtype`):
1026
- The dtype to use for the 4D attention mask.
1027
- device (`torch.device`):
1028
- The device to plcae the 4D attention mask on.
1029
- cache_position (`torch.Tensor`):
1030
- Indices depicting the position of the input sequence tokens in the sequence.
1031
- batch_size (`torch.Tensor`):
1032
- Batch size.
1033
- """
1034
- if attention_mask is not None and attention_mask.dim() == 4:
1035
- # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1036
- causal_mask = attention_mask
1037
- else:
1038
- min_dtype = torch.finfo(dtype).min
1039
- causal_mask = torch.full(
1040
- (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1041
  )
1042
- if sequence_length != 1:
1043
- causal_mask = torch.triu(causal_mask, diagonal=1)
1044
- causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1045
- causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1046
- if attention_mask is not None:
1047
- causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1048
- mask_length = attention_mask.shape[-1]
1049
- padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1050
- padding_mask = padding_mask == 0
1051
- causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1052
- padding_mask, min_dtype
1053
- )
1054
 
1055
  return causal_mask
1056
 
1057
 
1058
- class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
1059
-
1060
-
1061
- class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1062
  _tied_weights_keys = ["lm_head.weight"]
1063
 
1064
  def __init__(self, config):
@@ -1089,13 +1200,15 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1089
  return self.model
1090
 
1091
  @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1092
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
 
 
1093
  def forward(
1094
  self,
1095
  input_ids: torch.LongTensor = None,
1096
  attention_mask: Optional[torch.Tensor] = None,
1097
  position_ids: Optional[torch.LongTensor] = None,
1098
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1099
  inputs_embeds: Optional[torch.FloatTensor] = None,
1100
  labels: Optional[torch.LongTensor] = None,
1101
  use_cache: Optional[bool] = None,
@@ -1103,8 +1216,6 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1103
  output_hidden_states: Optional[bool] = None,
1104
  return_dict: Optional[bool] = None,
1105
  cache_position: Optional[torch.LongTensor] = None,
1106
- num_logits_to_keep: int = 0,
1107
- **kwargs: Unpack[KwargsForCausalLM],
1108
  ) -> Union[Tuple, CausalLMOutputWithPast]:
1109
  r"""
1110
  Args:
@@ -1113,11 +1224,6 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1113
  config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1114
  (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1115
 
1116
- num_logits_to_keep (`int`, *optional*):
1117
- Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1118
- `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1119
- token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1120
-
1121
  Returns:
1122
 
1123
  Example:
@@ -1136,11 +1242,19 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1136
  >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1137
  "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1138
  ```"""
1139
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
 
 
 
 
1140
  output_hidden_states = (
1141
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
 
 
 
 
 
1142
  )
1143
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1144
 
1145
  # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1146
  outputs = self.model(
@@ -1154,21 +1268,34 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1154
  output_hidden_states=output_hidden_states,
1155
  return_dict=return_dict,
1156
  cache_position=cache_position,
1157
- **kwargs,
1158
  )
1159
 
1160
  hidden_states = outputs[0]
1161
  if self.config.pretraining_tp > 1:
1162
- lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1163
- logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
 
 
 
 
 
1164
  logits = torch.cat(logits, dim=-1)
1165
  else:
1166
- # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1167
- logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1168
 
1169
  loss = None
1170
  if labels is not None:
1171
- loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
 
 
 
 
 
 
 
 
 
1172
 
1173
  if not return_dict:
1174
  output = (logits,) + outputs[1:]
@@ -1182,6 +1309,125 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1182
  attentions=outputs.attentions,
1183
  )
1184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1185
 
1186
  @add_start_docstrings(
1187
  """
@@ -1217,10 +1463,10 @@ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1217
  @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1218
  def forward(
1219
  self,
1220
- input_ids: Optional[torch.LongTensor] = None,
1221
  attention_mask: Optional[torch.Tensor] = None,
1222
  position_ids: Optional[torch.LongTensor] = None,
1223
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1224
  inputs_embeds: Optional[torch.FloatTensor] = None,
1225
  labels: Optional[torch.LongTensor] = None,
1226
  use_cache: Optional[bool] = None,
@@ -1234,7 +1480,9 @@ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1234
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1235
  `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1236
  """
1237
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
 
 
1238
 
1239
  transformer_outputs = self.model(
1240
  input_ids,
@@ -1256,24 +1504,53 @@ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1256
  batch_size = inputs_embeds.shape[0]
1257
 
1258
  if self.config.pad_token_id is None and batch_size != 1:
1259
- raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
 
 
1260
  if self.config.pad_token_id is None:
1261
  sequence_lengths = -1
1262
  else:
1263
  if input_ids is not None:
1264
  # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1265
- sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
 
 
1266
  sequence_lengths = sequence_lengths % input_ids.shape[-1]
1267
  sequence_lengths = sequence_lengths.to(logits.device)
1268
  else:
1269
  sequence_lengths = -1
1270
 
1271
- pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
 
 
1272
 
1273
  loss = None
1274
  if labels is not None:
1275
- loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1276
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1277
  if not return_dict:
1278
  output = (pooled_logits,) + transformer_outputs[1:]
1279
  return ((loss,) + output) if loss is not None else output
@@ -1318,14 +1595,13 @@ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1318
  input_ids: Optional[torch.LongTensor] = None,
1319
  attention_mask: Optional[torch.FloatTensor] = None,
1320
  position_ids: Optional[torch.LongTensor] = None,
1321
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1322
  inputs_embeds: Optional[torch.FloatTensor] = None,
1323
  start_positions: Optional[torch.LongTensor] = None,
1324
  end_positions: Optional[torch.LongTensor] = None,
1325
  output_attentions: Optional[bool] = None,
1326
  output_hidden_states: Optional[bool] = None,
1327
  return_dict: Optional[bool] = None,
1328
- **kwargs,
1329
  ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1330
  r"""
1331
  start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
@@ -1337,7 +1613,9 @@ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1337
  Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1338
  are not taken into account for computing the loss.
1339
  """
1340
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
 
 
1341
 
1342
  outputs = self.transformer(
1343
  input_ids,
@@ -1357,106 +1635,31 @@ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1357
  start_logits = start_logits.squeeze(-1).contiguous()
1358
  end_logits = end_logits.squeeze(-1).contiguous()
1359
 
1360
- loss = None
1361
  if start_positions is not None and end_positions is not None:
1362
- loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
1363
 
1364
  if not return_dict:
1365
  output = (start_logits, end_logits) + outputs[2:]
1366
- return ((loss,) + output) if loss is not None else output
1367
 
1368
  return QuestionAnsweringModelOutput(
1369
- loss=loss,
1370
  start_logits=start_logits,
1371
  end_logits=end_logits,
1372
  hidden_states=outputs.hidden_states,
1373
  attentions=outputs.attentions,
1374
  )
1375
-
1376
-
1377
- @add_start_docstrings(
1378
- """
1379
- The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1380
- output) e.g. for Named-Entity-Recognition (NER) tasks.
1381
- """,
1382
- LLAMA_START_DOCSTRING,
1383
- )
1384
- class LlamaForTokenClassification(LlamaPreTrainedModel):
1385
- def __init__(self, config):
1386
- super().__init__(config)
1387
- self.num_labels = config.num_labels
1388
- self.model = LlamaModel(config)
1389
- if getattr(config, "classifier_dropout", None) is not None:
1390
- classifier_dropout = config.classifier_dropout
1391
- elif getattr(config, "hidden_dropout", None) is not None:
1392
- classifier_dropout = config.hidden_dropout
1393
- else:
1394
- classifier_dropout = 0.1
1395
- self.dropout = nn.Dropout(classifier_dropout)
1396
- self.score = nn.Linear(config.hidden_size, config.num_labels)
1397
-
1398
- # Initialize weights and apply final processing
1399
- self.post_init()
1400
-
1401
- def get_input_embeddings(self):
1402
- return self.model.embed_tokens
1403
-
1404
- def set_input_embeddings(self, value):
1405
- self.model.embed_tokens = value
1406
-
1407
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1408
- @add_code_sample_docstrings(
1409
- checkpoint=_CHECKPOINT_FOR_DOC,
1410
- output_type=TokenClassifierOutput,
1411
- config_class=_CONFIG_FOR_DOC,
1412
- )
1413
- def forward(
1414
- self,
1415
- input_ids: Optional[torch.LongTensor] = None,
1416
- attention_mask: Optional[torch.Tensor] = None,
1417
- position_ids: Optional[torch.LongTensor] = None,
1418
- past_key_values: Optional[List[torch.FloatTensor]] = None,
1419
- inputs_embeds: Optional[torch.FloatTensor] = None,
1420
- labels: Optional[torch.LongTensor] = None,
1421
- use_cache: Optional[bool] = None,
1422
- output_attentions: Optional[bool] = None,
1423
- output_hidden_states: Optional[bool] = None,
1424
- return_dict: Optional[bool] = None,
1425
- ) -> Union[Tuple, TokenClassifierOutput]:
1426
- r"""
1427
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1428
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1429
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1430
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1431
- """
1432
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1433
-
1434
- outputs = self.model(
1435
- input_ids,
1436
- attention_mask=attention_mask,
1437
- position_ids=position_ids,
1438
- past_key_values=past_key_values,
1439
- inputs_embeds=inputs_embeds,
1440
- use_cache=use_cache,
1441
- output_attentions=output_attentions,
1442
- output_hidden_states=output_hidden_states,
1443
- return_dict=return_dict,
1444
- )
1445
- sequence_output = outputs[0]
1446
- sequence_output = self.dropout(sequence_output)
1447
- logits = self.score(sequence_output)
1448
-
1449
- loss = None
1450
- if labels is not None:
1451
- loss = self.loss_function(logits, labels, self.config)
1452
-
1453
- if not return_dict:
1454
- output = (logits,) + outputs[2:]
1455
- return ((loss,) + output) if loss is not None else output
1456
-
1457
- return TokenClassifierOutput(
1458
- loss=loss,
1459
- logits=logits,
1460
- hidden_states=outputs.hidden_states,
1461
- attentions=outputs.attentions,
1462
- )
 
17
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
  # See the License for the specific language governing permissions and
19
  # limitations under the License.
20
+ """PyTorch LLaMA model."""
21
+
22
  import math
23
+ import warnings
24
  from typing import List, Optional, Tuple, Union
25
 
26
  import torch
27
  import torch.nn.functional as F
28
  import torch.utils.checkpoint
29
  from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
 
 
32
  from transformers.activations import ACT2FN
33
  from transformers.cache_utils import Cache, DynamicCache, StaticCache
 
34
  from transformers.modeling_attn_mask_utils import AttentionMaskConverter
 
35
  from transformers.modeling_outputs import (
36
  BaseModelOutputWithPast,
37
  CausalLMOutputWithPast,
38
  QuestionAnsweringModelOutput,
39
  SequenceClassifierOutputWithPast,
 
40
  )
 
41
  from transformers.modeling_utils import PreTrainedModel
 
42
  from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
43
  from transformers.utils import (
 
 
44
  add_start_docstrings,
45
  add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
  is_flash_attn_greater_or_equal_2_10,
48
  logging,
49
  replace_return_docstrings,
50
  )
51
  from .configuration_llama import LlamaConfig
52
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm
53
+ from transformers.models.llama.modeling_llama import (
54
+ apply_rotary_pos_emb,
55
+ LlamaRotaryEmbedding,
56
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
 
 
 
 
58
 
59
+ if is_flash_attn_2_available():
60
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
61
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
 
 
 
 
 
 
 
 
62
 
 
 
 
63
 
64
+ logger = logging.get_logger(__name__)
65
 
66
+ _CONFIG_FOR_DOC = "LlamaConfig"
67
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ def _get_unpad_data(attention_mask):
70
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
71
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
72
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
73
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
74
+ return (
75
+ indices,
76
+ cu_seqlens,
77
+ max_seqlen_in_batch,
78
+ )
79
 
 
 
80
 
81
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
 
 
 
 
 
 
 
82
 
83
 
84
  class LlamaMLP(nn.Module):
 
87
  self.config = config
88
  self.hidden_size = config.hidden_size
89
  self.intermediate_size = config.intermediate_size
90
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
91
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
92
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
93
  self.act_fn = ACT2FN[config.hidden_act]
94
 
95
  def forward(self, x):
 
100
  down_proj_slices = self.down_proj.weight.split(slice, dim=1)
101
 
102
  gate_proj = torch.cat(
103
+ [
104
+ F.linear(x, gate_proj_slices[i])
105
+ for i in range(self.config.pretraining_tp)
106
+ ],
107
+ dim=-1,
108
+ )
109
+ up_proj = torch.cat(
110
+ [
111
+ F.linear(x, up_proj_slices[i])
112
+ for i in range(self.config.pretraining_tp)
113
+ ],
114
+ dim=-1,
115
  )
 
116
 
117
  intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
118
  down_proj = [
119
+ F.linear(intermediate_states[i], down_proj_slices[i])
120
+ for i in range(self.config.pretraining_tp)
121
  ]
122
  down_proj = sum(down_proj)
123
  else:
 
134
  batch, num_key_value_heads, slen, head_dim = hidden_states.shape
135
  if n_rep == 1:
136
  return hidden_states
137
+ hidden_states = hidden_states[:, :, None, :, :].expand(
138
+ batch, num_key_value_heads, n_rep, slen, head_dim
139
+ )
140
  return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
141
 
142
 
 
157
  self.attention_dropout = config.attention_dropout
158
  self.hidden_size = config.hidden_size
159
  self.num_heads = config.num_attention_heads
160
+ self.head_dim = self.hidden_size // self.num_heads
161
  self.num_key_value_heads = config.num_key_value_heads
162
  self.num_key_value_groups = self.num_heads // self.num_key_value_heads
163
  self.max_position_embeddings = config.max_position_embeddings
164
  self.rope_theta = config.rope_theta
165
  self.is_causal = True
166
 
167
+ if (self.head_dim * self.num_heads) != self.hidden_size:
168
+ raise ValueError(
169
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
170
+ f" and `num_heads`: {self.num_heads})."
171
+ )
172
+
173
+ self.q_proj = nn.Linear(
174
+ self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
175
+ )
176
+ self.k_proj = nn.Linear(
177
+ self.hidden_size,
178
+ self.num_key_value_heads * self.head_dim,
179
+ bias=config.attention_bias,
180
+ )
181
+ self.v_proj = nn.Linear(
182
+ self.hidden_size,
183
+ self.num_key_value_heads * self.head_dim,
184
+ bias=config.attention_bias,
185
+ )
186
+ self.o_proj = nn.Linear(
187
+ self.hidden_size, self.hidden_size, bias=config.attention_bias
188
+ )
189
+ self._init_rope()
190
 
191
+ def _init_rope(self):
192
+ if self.config.rope_scaling is None:
193
+ self.rotary_emb = LlamaRotaryEmbedding(self.config)
194
+ else:
195
+ scaling_type = self.config.rope_scaling["type"]
196
+ scaling_factor = self.config.rope_scaling["factor"]
197
+ if scaling_type == "linear":
198
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
199
+ self.head_dim,
200
+ max_position_embeddings=self.max_position_embeddings,
201
+ scaling_factor=scaling_factor,
202
+ base=self.rope_theta,
203
+ )
204
+ elif scaling_type == "dynamic":
205
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
206
+ self.head_dim,
207
+ max_position_embeddings=self.max_position_embeddings,
208
+ scaling_factor=scaling_factor,
209
+ base=self.rope_theta,
210
+ )
211
+ else:
212
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
213
 
214
  def forward(
215
  self,
 
220
  output_attentions: bool = False,
221
  use_cache: bool = False,
222
  cache_position: Optional[torch.LongTensor] = None,
 
223
  **kwargs,
224
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
225
  bsz, q_len, _ = hidden_states.size()
226
 
227
  if self.config.pretraining_tp > 1:
228
+ key_value_slicing = (
229
+ self.num_key_value_heads * self.head_dim
230
+ ) // self.config.pretraining_tp
231
  query_slices = self.q_proj.weight.split(
232
  (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
233
  )
234
  key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
235
  value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
236
 
237
+ query_states = [
238
+ F.linear(hidden_states, query_slices[i])
239
+ for i in range(self.config.pretraining_tp)
240
+ ]
241
  query_states = torch.cat(query_states, dim=-1)
242
 
243
+ key_states = [
244
+ F.linear(hidden_states, key_slices[i])
245
+ for i in range(self.config.pretraining_tp)
246
+ ]
247
  key_states = torch.cat(key_states, dim=-1)
248
 
249
+ value_states = [
250
+ F.linear(hidden_states, value_slices[i])
251
+ for i in range(self.config.pretraining_tp)
252
+ ]
253
  value_states = torch.cat(value_states, dim=-1)
254
 
255
  else:
 
257
  key_states = self.k_proj(hidden_states)
258
  value_states = self.v_proj(hidden_states)
259
 
260
+ query_states = query_states.view(
261
+ bsz, q_len, self.num_heads, self.head_dim
262
+ ).transpose(1, 2)
263
+ key_states = key_states.view(
264
+ bsz, q_len, self.num_key_value_heads, self.head_dim
265
+ ).transpose(1, 2)
266
+ value_states = value_states.view(
267
+ bsz, q_len, self.num_key_value_heads, self.head_dim
268
+ ).transpose(1, 2)
269
+
270
+ past_key_value = getattr(self, "past_key_value", past_key_value)
271
+ cos, sin = self.rotary_emb(value_states, position_ids)
272
+ query_states, key_states = apply_rotary_pos_emb(
273
+ query_states, key_states, cos, sin
274
+ )
275
 
276
  if past_key_value is not None:
277
  # sin and cos are specific to RoPE models; cache_position needed for the static cache
278
  cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
279
+ key_states, value_states = past_key_value.update(
280
+ key_states, value_states, self.layer_idx, cache_kwargs
281
+ )
282
 
283
  key_states = repeat_kv(key_states, self.num_key_value_groups)
284
  value_states = repeat_kv(value_states, self.num_key_value_groups)
285
+
286
+ attn_weights = torch.matmul(
287
+ query_states, key_states.transpose(2, 3)
288
+ ) / math.sqrt(self.head_dim)
289
 
290
  if attention_mask is not None: # no matter the length, we just slice it
291
  causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
292
  attn_weights = attn_weights + causal_mask
293
 
294
  # upcast attention to fp32
295
+ attn_weights = nn.functional.softmax(
296
+ attn_weights, dim=-1, dtype=torch.float32
297
+ ).to(query_states.dtype)
298
+ attn_weights = nn.functional.dropout(
299
+ attn_weights, p=self.attention_dropout, training=self.training
300
+ )
301
  attn_output = torch.matmul(attn_weights, value_states)
302
 
303
  if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
 
308
 
309
  attn_output = attn_output.transpose(1, 2).contiguous()
310
 
311
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
312
 
313
  if self.config.pretraining_tp > 1:
314
+ attn_output = attn_output.split(
315
+ self.hidden_size // self.config.pretraining_tp, dim=2
316
+ )
317
+ o_proj_slices = self.o_proj.weight.split(
318
+ self.hidden_size // self.config.pretraining_tp, dim=1
319
+ )
320
+ attn_output = sum(
321
+ [
322
+ F.linear(attn_output[i], o_proj_slices[i])
323
+ for i in range(self.config.pretraining_tp)
324
+ ]
325
+ )
326
  else:
327
  attn_output = self.o_proj(attn_output)
328
 
 
356
  output_attentions: bool = False,
357
  use_cache: bool = False,
358
  cache_position: Optional[torch.LongTensor] = None,
359
+ **kwargs,
 
360
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
 
 
 
 
 
 
361
  output_attentions = False
362
 
363
  bsz, q_len, _ = hidden_states.size()
 
369
  # Flash attention requires the input to have the shape
370
  # batch_size x seq_length x head_dim x hidden_dim
371
  # therefore we just need to keep the original shape
372
+ query_states = query_states.view(
373
+ bsz, q_len, self.num_heads, self.head_dim
374
+ ).transpose(1, 2)
375
+ key_states = key_states.view(
376
+ bsz, q_len, self.num_key_value_heads, self.head_dim
377
+ ).transpose(1, 2)
378
+ value_states = value_states.view(
379
+ bsz, q_len, self.num_key_value_heads, self.head_dim
380
+ ).transpose(1, 2)
381
+
382
+ cos, sin = self.rotary_emb(value_states, position_ids)
383
+ query_states, key_states = apply_rotary_pos_emb(
384
+ query_states, key_states, cos, sin
385
+ )
386
 
387
+ past_key_value = getattr(self, "past_key_value", past_key_value)
 
 
 
 
 
 
 
 
 
 
388
 
389
  if past_key_value is not None:
390
  # sin and cos are specific to RoPE models; cache_position needed for the static cache
391
  cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
392
+ key_states, value_states = past_key_value.update(
393
+ key_states, value_states, self.layer_idx, cache_kwargs
394
+ )
395
 
396
  # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
397
  # to be able to avoid many of these transpose/reshape/view.
 
427
  key_states = key_states.to(target_dtype)
428
  value_states = value_states.to(target_dtype)
429
 
430
+ attn_output = self._flash_attention_forward(
431
  query_states,
432
  key_states,
433
  value_states,
434
  attention_mask,
435
  q_len,
 
436
  dropout=dropout_rate,
 
 
 
 
437
  )
438
 
439
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
440
  attn_output = self.o_proj(attn_output)
441
 
442
  if not output_attentions:
 
444
 
445
  return attn_output, attn_weights, past_key_value
446
 
447
+ def _flash_attention_forward(
448
+ self,
449
+ query_states,
450
+ key_states,
451
+ value_states,
452
+ attention_mask,
453
+ query_length,
454
+ dropout=0.0,
455
+ softmax_scale=None,
456
+ ):
457
+ """
458
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
459
+ first unpad the input, then computes the attention scores and pad the final attention scores.
460
+
461
+ Args:
462
+ query_states (`torch.Tensor`):
463
+ Input query states to be passed to Flash Attention API
464
+ key_states (`torch.Tensor`):
465
+ Input key states to be passed to Flash Attention API
466
+ value_states (`torch.Tensor`):
467
+ Input value states to be passed to Flash Attention API
468
+ attention_mask (`torch.Tensor`):
469
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
470
+ position of padding tokens and 1 for the position of non-padding tokens.
471
+ dropout (`float`):
472
+ Attention dropout
473
+ softmax_scale (`float`, *optional*):
474
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
475
+ """
476
+ if not self._flash_attn_uses_top_left_mask:
477
+ causal = self.is_causal
478
+ else:
479
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
480
+ causal = self.is_causal and query_length != 1
481
+
482
+ # Contains at least one padding token in the sequence
483
+ if attention_mask is not None:
484
+ batch_size = query_states.shape[0]
485
+ (
486
+ query_states,
487
+ key_states,
488
+ value_states,
489
+ indices_q,
490
+ cu_seq_lens,
491
+ max_seq_lens,
492
+ ) = self._upad_input(
493
+ query_states, key_states, value_states, attention_mask, query_length
494
+ )
495
+
496
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
497
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
498
+
499
+ attn_output_unpad = flash_attn_varlen_func(
500
+ query_states,
501
+ key_states,
502
+ value_states,
503
+ cu_seqlens_q=cu_seqlens_q,
504
+ cu_seqlens_k=cu_seqlens_k,
505
+ max_seqlen_q=max_seqlen_in_batch_q,
506
+ max_seqlen_k=max_seqlen_in_batch_k,
507
+ dropout_p=dropout,
508
+ softmax_scale=softmax_scale,
509
+ causal=causal,
510
+ )
511
+
512
+ attn_output = pad_input(
513
+ attn_output_unpad, indices_q, batch_size, query_length
514
+ )
515
+ else:
516
+ attn_output = flash_attn_func(
517
+ query_states,
518
+ key_states,
519
+ value_states,
520
+ dropout,
521
+ softmax_scale=softmax_scale,
522
+ causal=causal,
523
+ )
524
+
525
+ return attn_output
526
+
527
+ def _upad_input(
528
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
529
+ ):
530
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
531
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
532
+
533
+ key_layer = index_first_axis(
534
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
535
+ indices_k,
536
+ )
537
+ value_layer = index_first_axis(
538
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
539
+ indices_k,
540
+ )
541
+ if query_length == kv_seq_len:
542
+ query_layer = index_first_axis(
543
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
544
+ indices_k,
545
+ )
546
+ cu_seqlens_q = cu_seqlens_k
547
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
548
+ indices_q = indices_k
549
+ elif query_length == 1:
550
+ max_seqlen_in_batch_q = 1
551
+ cu_seqlens_q = torch.arange(
552
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
553
+ ) # There is a memcpy here, that is very bad.
554
+ indices_q = cu_seqlens_q[:-1]
555
+ query_layer = query_layer.squeeze(1)
556
+ else:
557
+ # The -q_len: slice assumes left padding.
558
+ attention_mask = attention_mask[:, -query_length:]
559
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
560
+ query_layer, attention_mask
561
+ )
562
+
563
+ return (
564
+ query_layer,
565
+ key_layer,
566
+ value_layer,
567
+ indices_q,
568
+ (cu_seqlens_q, cu_seqlens_k),
569
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
570
+ )
571
+
572
 
573
  class LlamaSdpaAttention(LlamaAttention):
574
  """
 
587
  output_attentions: bool = False,
588
  use_cache: bool = False,
589
  cache_position: Optional[torch.LongTensor] = None,
 
 
590
  ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
591
  if output_attentions:
592
  # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
 
602
  output_attentions=output_attentions,
603
  use_cache=use_cache,
604
  cache_position=cache_position,
 
605
  )
606
 
607
  bsz, q_len, _ = hidden_states.size()
 
610
  key_states = self.k_proj(hidden_states)
611
  value_states = self.v_proj(hidden_states)
612
 
613
+ query_states = query_states.view(
614
+ bsz, q_len, self.num_heads, self.head_dim
615
+ ).transpose(1, 2)
616
+ key_states = key_states.view(
617
+ bsz, q_len, self.num_key_value_heads, self.head_dim
618
+ ).transpose(1, 2)
619
+ value_states = value_states.view(
620
+ bsz, q_len, self.num_key_value_heads, self.head_dim
621
+ ).transpose(1, 2)
622
+
623
+ cos, sin = self.rotary_emb(value_states, position_ids)
624
+ query_states, key_states = apply_rotary_pos_emb(
625
+ query_states, key_states, cos, sin
626
+ )
627
 
628
+ # In case static cache is used, it is an instance attribute.
629
+ past_key_value = getattr(self, "past_key_value", past_key_value)
 
 
 
 
 
 
 
 
 
630
 
631
  if past_key_value is not None:
632
  # sin and cos are specific to RoPE models; cache_position needed for the static cache
633
  cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
634
+ key_states, value_states = past_key_value.update(
635
+ key_states, value_states, self.layer_idx, cache_kwargs
636
+ )
637
 
638
  key_states = repeat_kv(key_states, self.num_key_value_groups)
639
  value_states = repeat_kv(value_states, self.num_key_value_groups)
 
649
  key_states = key_states.contiguous()
650
  value_states = value_states.contiguous()
651
 
652
+ # In case we are not compiling, we may set `causal_mask` to None, which is required to dispatch to SDPA's Flash Attention 2 backend, rather
653
+ # relying on the `is_causal` argument.
 
 
654
  attn_output = torch.nn.functional.scaled_dot_product_attention(
655
  query_states,
656
  key_states,
657
  value_states,
658
  attn_mask=causal_mask,
659
  dropout_p=self.attention_dropout if self.training else 0.0,
660
+ is_causal=causal_mask is None and q_len > 1,
661
  )
662
 
663
  attn_output = attn_output.transpose(1, 2).contiguous()
664
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
665
 
666
  attn_output = self.o_proj(attn_output)
667
 
 
680
  super().__init__()
681
  self.hidden_size = config.hidden_size
682
 
683
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](
684
+ config=config, layer_idx=layer_idx
685
+ )
686
 
687
  self.mlp = LlamaMLP(config)
688
  self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
689
+ self.post_attention_layernorm = LlamaRMSNorm(
690
+ config.hidden_size, eps=config.rms_norm_eps
691
+ )
692
 
693
  def forward(
694
  self,
695
  hidden_states: torch.Tensor,
696
  attention_mask: Optional[torch.Tensor] = None,
697
  position_ids: Optional[torch.LongTensor] = None,
698
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
699
  output_attentions: Optional[bool] = False,
700
  use_cache: Optional[bool] = False,
701
  cache_position: Optional[torch.LongTensor] = None,
 
702
  **kwargs,
703
+ ) -> Tuple[
704
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
705
+ ]:
706
  """
707
  Args:
708
  hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
 
716
  If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
717
  (see `past_key_values`).
718
  past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
 
 
 
 
 
 
 
 
719
  """
720
+ if "padding_mask" in kwargs:
721
+ warnings.warn(
722
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
723
+ )
724
+
725
  residual = hidden_states
726
 
727
  hidden_states = self.input_layernorm(hidden_states)
 
735
  output_attentions=output_attentions,
736
  use_cache=use_cache,
737
  cache_position=cache_position,
 
738
  **kwargs,
739
  )
740
  hidden_states = residual + hidden_states
 
786
  _supports_flash_attn_2 = True
787
  _supports_sdpa = True
788
  _supports_cache_class = True
 
 
789
 
790
  def _init_weights(self, module):
791
  std = self.config.initializer_range
 
798
  if module.padding_idx is not None:
799
  module.weight.data[module.padding_idx].zero_()
800
 
801
+ def _setup_cache(
802
+ self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None
803
+ ):
804
+ if (
805
+ self.config._attn_implementation == "flash_attention_2"
806
+ and cache_cls == StaticCache
807
+ ):
808
+ raise ValueError(
809
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
810
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
811
+ )
812
+
813
+ for layer in self.model.layers:
814
+ device = layer.input_layernorm.weight.device
815
+ if hasattr(self.config, "_pre_quantization_dtype"):
816
+ dtype = self.config._pre_quantization_dtype
817
+ else:
818
+ dtype = layer.self_attn.o_proj.weight.dtype
819
+ layer.self_attn.past_key_value = cache_cls(
820
+ self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
821
+ )
822
+
823
+ def _reset_cache(self):
824
+ for layer in self.model.layers:
825
+ layer.self_attn.past_key_value = None
826
+
827
 
828
  LLAMA_INPUTS_DOCSTRING = r"""
829
  Args:
 
866
  returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
867
 
868
  Two formats are allowed:
869
+ - a [`~cache_utils.Cache`] instance;
 
870
  - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
871
  shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
872
  cache format.
 
916
  self.padding_idx = config.pad_token_id
917
  self.vocab_size = config.vocab_size
918
 
919
+ self.embed_tokens = nn.Embedding(
920
+ config.vocab_size, config.hidden_size, self.padding_idx
921
+ )
922
  self.layers = nn.ModuleList(
923
+ [
924
+ LlamaDecoderLayer(config, layer_idx)
925
+ for layer_idx in range(config.num_hidden_layers)
926
+ ]
927
  )
928
  self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
 
929
  self.gradient_checkpointing = False
930
 
931
  # Initialize weights and apply final processing
 
943
  input_ids: torch.LongTensor = None,
944
  attention_mask: Optional[torch.Tensor] = None,
945
  position_ids: Optional[torch.LongTensor] = None,
946
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
947
  inputs_embeds: Optional[torch.FloatTensor] = None,
948
  use_cache: Optional[bool] = None,
949
  output_attentions: Optional[bool] = None,
950
  output_hidden_states: Optional[bool] = None,
951
  return_dict: Optional[bool] = None,
952
  cache_position: Optional[torch.LongTensor] = None,
 
953
  ) -> Union[Tuple, BaseModelOutputWithPast]:
954
+ output_attentions = (
955
+ output_attentions
956
+ if output_attentions is not None
957
+ else self.config.output_attentions
958
+ )
959
  output_hidden_states = (
960
+ output_hidden_states
961
+ if output_hidden_states is not None
962
+ else self.config.output_hidden_states
963
  )
964
  use_cache = use_cache if use_cache is not None else self.config.use_cache
965
+ return_dict = (
966
+ return_dict if return_dict is not None else self.config.use_return_dict
967
+ )
968
 
969
  if (input_ids is None) ^ (inputs_embeds is not None):
970
+ raise ValueError(
971
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
972
+ )
973
 
974
  if self.gradient_checkpointing and self.training and use_cache:
975
  logger.warning_once(
 
980
  if inputs_embeds is None:
981
  inputs_embeds = self.embed_tokens(input_ids)
982
 
983
+ past_seen_tokens = 0
984
+ if use_cache: # kept for BC (cache positions)
985
+ if past_key_values is not None and not isinstance(
986
+ past_key_values, StaticCache
987
+ ):
988
+ if not isinstance(past_key_values, DynamicCache):
989
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
990
+ past_seen_tokens = past_key_values.get_seq_length()
 
 
 
 
 
991
 
992
  if cache_position is None:
993
+ if isinstance(past_key_values, StaticCache):
994
+ raise ValueError(
995
+ "cache_position is a required argument when using StaticCache."
996
+ )
997
  cache_position = torch.arange(
998
+ past_seen_tokens,
999
+ past_seen_tokens + inputs_embeds.shape[1],
1000
+ device=inputs_embeds.device,
1001
  )
1002
+
1003
  if position_ids is None:
1004
  position_ids = cache_position.unsqueeze(0)
1005
 
1006
  causal_mask = self._update_causal_mask(
1007
+ attention_mask, inputs_embeds, cache_position, past_seen_tokens
1008
  )
 
1009
 
1010
+ # embed positions
1011
+ hidden_states = inputs_embeds
1012
 
1013
  # decoder layers
1014
  all_hidden_states = () if output_hidden_states else None
 
1029
  output_attentions,
1030
  use_cache,
1031
  cache_position,
 
1032
  )
1033
  else:
1034
  layer_outputs = decoder_layer(
 
1039
  output_attentions=output_attentions,
1040
  use_cache=use_cache,
1041
  cache_position=cache_position,
 
 
1042
  )
1043
 
1044
  hidden_states = layer_outputs[0]
 
1055
  if output_hidden_states:
1056
  all_hidden_states += (hidden_states,)
1057
 
1058
+ next_cache = None
1059
+ if use_cache:
1060
+ next_cache = next_decoder_cache
 
1061
  if not return_dict:
1062
+ return tuple(
1063
+ v
1064
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1065
+ if v is not None
1066
+ )
1067
  return BaseModelOutputWithPast(
1068
  last_hidden_state=hidden_states,
1069
  past_key_values=next_cache,
 
1076
  attention_mask: torch.Tensor,
1077
  input_tensor: torch.Tensor,
1078
  cache_position: torch.Tensor,
1079
+ past_seen_tokens: int,
 
1080
  ):
1081
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1082
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1083
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1084
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1085
+
1086
  if self.config._attn_implementation == "flash_attention_2":
1087
  if attention_mask is not None and 0.0 in attention_mask:
1088
  return attention_mask
1089
  return None
1090
 
1091
+ if self.config._attn_implementation == "sdpa":
1092
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument,
1093
+ # in order to dispatch on Flash Attention 2.
 
 
 
 
 
1094
  if AttentionMaskConverter._ignore_causal_mask_sdpa(
1095
  attention_mask,
1096
  inputs_embeds=input_tensor,
1097
  past_key_values_length=past_seen_tokens,
 
1098
  ):
1099
  return None
1100
 
1101
  dtype, device = input_tensor.dtype, input_tensor.device
1102
+ min_dtype = torch.finfo(dtype).min
1103
  sequence_length = input_tensor.shape[1]
1104
+ if hasattr(
1105
+ getattr(self.layers[0], "self_attn", {}), "past_key_value"
1106
+ ): # static cache
1107
+ target_length = self.config.max_position_embeddings
1108
+ else: # dynamic cache
1109
  target_length = (
1110
  attention_mask.shape[-1]
1111
  if isinstance(attention_mask, torch.Tensor)
1112
  else past_seen_tokens + sequence_length + 1
1113
  )
1114
 
1115
+ causal_mask = torch.full(
1116
+ (sequence_length, target_length),
1117
+ fill_value=min_dtype,
 
 
1118
  dtype=dtype,
1119
  device=device,
 
 
1120
  )
1121
+ if sequence_length != 1:
1122
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1123
+ causal_mask *= torch.arange(
1124
+ target_length, device=device
1125
+ ) > cache_position.reshape(-1, 1)
1126
+ causal_mask = causal_mask[None, None, :, :].expand(
1127
+ input_tensor.shape[0], 1, -1, -1
1128
+ )
1129
+ if attention_mask is not None:
1130
+ causal_mask = (
1131
+ causal_mask.clone()
1132
+ ) # copy to contiguous memory for in-place edit
1133
+ if attention_mask.dim() == 2:
1134
+ mask_length = attention_mask.shape[-1]
1135
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[
1136
+ :, None, None, :
1137
+ ].eq(0.0)
1138
+ causal_mask[..., :mask_length] = causal_mask[
1139
+ ..., :mask_length
1140
+ ].masked_fill(padding_mask, min_dtype)
1141
+ elif attention_mask.dim() == 4:
1142
+ # backwards compatibility: we allow passing a 4D attention mask shorter than the input length with
1143
+ # cache. In that case, the 4D attention mask attends to the newest tokens only.
1144
+ if attention_mask.shape[-2] < cache_position[0] + sequence_length:
1145
+ offset = cache_position[0]
1146
+ else:
1147
+ offset = 0
1148
+ mask_shape = attention_mask.shape
1149
+ mask_slice = (attention_mask.eq(0.0)).to(dtype=dtype) * min_dtype
1150
+ causal_mask[
1151
+ : mask_shape[0],
1152
+ : mask_shape[1],
1153
+ offset : mask_shape[2] + offset,
1154
+ : mask_shape[3],
1155
+ ] = mask_slice
1156
 
1157
  if (
1158
  self.config._attn_implementation == "sdpa"
1159
  and attention_mask is not None
1160
  and attention_mask.device.type == "cuda"
 
1161
  ):
1162
  # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1163
  # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1164
  # Details: https://github.com/pytorch/pytorch/issues/110213
1165
+ causal_mask = AttentionMaskConverter._unmask_unattended(
1166
+ causal_mask, min_dtype
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1167
  )
 
 
 
 
 
 
 
 
 
 
 
 
1168
 
1169
  return causal_mask
1170
 
1171
 
1172
+ class LlamaForCausalLM(LlamaPreTrainedModel):
 
 
 
1173
  _tied_weights_keys = ["lm_head.weight"]
1174
 
1175
  def __init__(self, config):
 
1200
  return self.model
1201
 
1202
  @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1203
+ @replace_return_docstrings(
1204
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1205
+ )
1206
  def forward(
1207
  self,
1208
  input_ids: torch.LongTensor = None,
1209
  attention_mask: Optional[torch.Tensor] = None,
1210
  position_ids: Optional[torch.LongTensor] = None,
1211
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1212
  inputs_embeds: Optional[torch.FloatTensor] = None,
1213
  labels: Optional[torch.LongTensor] = None,
1214
  use_cache: Optional[bool] = None,
 
1216
  output_hidden_states: Optional[bool] = None,
1217
  return_dict: Optional[bool] = None,
1218
  cache_position: Optional[torch.LongTensor] = None,
 
 
1219
  ) -> Union[Tuple, CausalLMOutputWithPast]:
1220
  r"""
1221
  Args:
 
1224
  config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1225
  (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1226
 
 
 
 
 
 
1227
  Returns:
1228
 
1229
  Example:
 
1242
  >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1243
  "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1244
  ```"""
1245
+ output_attentions = (
1246
+ output_attentions
1247
+ if output_attentions is not None
1248
+ else self.config.output_attentions
1249
+ )
1250
  output_hidden_states = (
1251
+ output_hidden_states
1252
+ if output_hidden_states is not None
1253
+ else self.config.output_hidden_states
1254
+ )
1255
+ return_dict = (
1256
+ return_dict if return_dict is not None else self.config.use_return_dict
1257
  )
 
1258
 
1259
  # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1260
  outputs = self.model(
 
1268
  output_hidden_states=output_hidden_states,
1269
  return_dict=return_dict,
1270
  cache_position=cache_position,
 
1271
  )
1272
 
1273
  hidden_states = outputs[0]
1274
  if self.config.pretraining_tp > 1:
1275
+ lm_head_slices = self.lm_head.weight.split(
1276
+ self.vocab_size // self.config.pretraining_tp, dim=0
1277
+ )
1278
+ logits = [
1279
+ F.linear(hidden_states, lm_head_slices[i])
1280
+ for i in range(self.config.pretraining_tp)
1281
+ ]
1282
  logits = torch.cat(logits, dim=-1)
1283
  else:
1284
+ logits = self.lm_head(hidden_states)
1285
+ logits = logits.float()
1286
 
1287
  loss = None
1288
  if labels is not None:
1289
+ # Shift so that tokens < n predict n
1290
+ shift_logits = logits[..., :-1, :].contiguous()
1291
+ shift_labels = labels[..., 1:].contiguous()
1292
+ # Flatten the tokens
1293
+ loss_fct = CrossEntropyLoss()
1294
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1295
+ shift_labels = shift_labels.view(-1)
1296
+ # Enable model parallelism
1297
+ shift_labels = shift_labels.to(shift_logits.device)
1298
+ loss = loss_fct(shift_logits, shift_labels)
1299
 
1300
  if not return_dict:
1301
  output = (logits,) + outputs[1:]
 
1309
  attentions=outputs.attentions,
1310
  )
1311
 
1312
+ def prepare_inputs_for_generation(
1313
+ self,
1314
+ input_ids,
1315
+ past_key_values=None,
1316
+ attention_mask=None,
1317
+ inputs_embeds=None,
1318
+ cache_position=None,
1319
+ **kwargs,
1320
+ ):
1321
+ # With static cache, the `past_key_values` is None
1322
+ # TODO joao: standardize interface for the different Cache classes and remove of this if
1323
+ has_static_cache = False
1324
+ if past_key_values is None:
1325
+ past_key_values = getattr(
1326
+ getattr(self.model.layers[0], "self_attn", {}), "past_key_value", None
1327
+ )
1328
+ has_static_cache = past_key_values is not None
1329
+
1330
+ past_length = 0
1331
+ if past_key_values is not None:
1332
+ if isinstance(past_key_values, Cache):
1333
+ past_length = (
1334
+ cache_position[0]
1335
+ if cache_position is not None
1336
+ else past_key_values.get_seq_length()
1337
+ )
1338
+ max_cache_length = (
1339
+ torch.tensor(
1340
+ past_key_values.get_max_cache_shape(), device=input_ids.device
1341
+ )
1342
+ if past_key_values.get_max_cache_shape() is not None
1343
+ else None
1344
+ )
1345
+ cache_length = (
1346
+ past_length
1347
+ if max_cache_length is None
1348
+ else torch.min(max_cache_length, past_length)
1349
+ )
1350
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1351
+ else:
1352
+ cache_length = past_length = past_key_values[0][0].shape[2]
1353
+ max_cache_length = None
1354
+
1355
+ # Keep only the unprocessed tokens:
1356
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1357
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1358
+ # input)
1359
+ if (
1360
+ attention_mask is not None
1361
+ and attention_mask.shape[1] > input_ids.shape[1]
1362
+ ):
1363
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1364
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1365
+ # input_ids based on the past_length.
1366
+ elif past_length < input_ids.shape[1]:
1367
+ input_ids = input_ids[:, past_length:]
1368
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1369
+
1370
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1371
+ if (
1372
+ max_cache_length is not None
1373
+ and attention_mask is not None
1374
+ and cache_length + input_ids.shape[1] > max_cache_length
1375
+ ):
1376
+ attention_mask = attention_mask[:, -max_cache_length:]
1377
+
1378
+ position_ids = kwargs.get("position_ids", None)
1379
+ if attention_mask is not None and position_ids is None:
1380
+ # create position_ids on the fly for batch generation
1381
+ position_ids = attention_mask.long().cumsum(-1) - 1
1382
+ position_ids.masked_fill_(attention_mask == 0, 1)
1383
+ if past_key_values:
1384
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1385
+
1386
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1387
+ if inputs_embeds is not None and past_key_values is None:
1388
+ model_inputs = {"inputs_embeds": inputs_embeds}
1389
+ else:
1390
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1391
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1392
+ # TODO: use `next_tokens` directly instead.
1393
+ model_inputs = {"input_ids": input_ids.contiguous()}
1394
+
1395
+ input_length = (
1396
+ position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1397
+ )
1398
+ if cache_position is None:
1399
+ cache_position = torch.arange(
1400
+ past_length, past_length + input_length, device=input_ids.device
1401
+ )
1402
+ else:
1403
+ cache_position = cache_position[-input_length:]
1404
+
1405
+ if has_static_cache:
1406
+ past_key_values = None
1407
+
1408
+ model_inputs.update(
1409
+ {
1410
+ "position_ids": position_ids,
1411
+ "cache_position": cache_position,
1412
+ "past_key_values": past_key_values,
1413
+ "use_cache": kwargs.get("use_cache"),
1414
+ "attention_mask": attention_mask,
1415
+ }
1416
+ )
1417
+ return model_inputs
1418
+
1419
+ @staticmethod
1420
+ def _reorder_cache(past_key_values, beam_idx):
1421
+ reordered_past = ()
1422
+ for layer_past in past_key_values:
1423
+ reordered_past += (
1424
+ tuple(
1425
+ past_state.index_select(0, beam_idx.to(past_state.device))
1426
+ for past_state in layer_past
1427
+ ),
1428
+ )
1429
+ return reordered_past
1430
+
1431
 
1432
  @add_start_docstrings(
1433
  """
 
1463
  @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1464
  def forward(
1465
  self,
1466
+ input_ids: torch.LongTensor = None,
1467
  attention_mask: Optional[torch.Tensor] = None,
1468
  position_ids: Optional[torch.LongTensor] = None,
1469
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1470
  inputs_embeds: Optional[torch.FloatTensor] = None,
1471
  labels: Optional[torch.LongTensor] = None,
1472
  use_cache: Optional[bool] = None,
 
1480
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1481
  `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1482
  """
1483
+ return_dict = (
1484
+ return_dict if return_dict is not None else self.config.use_return_dict
1485
+ )
1486
 
1487
  transformer_outputs = self.model(
1488
  input_ids,
 
1504
  batch_size = inputs_embeds.shape[0]
1505
 
1506
  if self.config.pad_token_id is None and batch_size != 1:
1507
+ raise ValueError(
1508
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1509
+ )
1510
  if self.config.pad_token_id is None:
1511
  sequence_lengths = -1
1512
  else:
1513
  if input_ids is not None:
1514
  # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1515
+ sequence_lengths = (
1516
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1517
+ )
1518
  sequence_lengths = sequence_lengths % input_ids.shape[-1]
1519
  sequence_lengths = sequence_lengths.to(logits.device)
1520
  else:
1521
  sequence_lengths = -1
1522
 
1523
+ pooled_logits = logits[
1524
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1525
+ ]
1526
 
1527
  loss = None
1528
  if labels is not None:
1529
+ labels = labels.to(logits.device)
1530
+ if self.config.problem_type is None:
1531
+ if self.num_labels == 1:
1532
+ self.config.problem_type = "regression"
1533
+ elif self.num_labels > 1 and (
1534
+ labels.dtype == torch.long or labels.dtype == torch.int
1535
+ ):
1536
+ self.config.problem_type = "single_label_classification"
1537
+ else:
1538
+ self.config.problem_type = "multi_label_classification"
1539
+
1540
+ if self.config.problem_type == "regression":
1541
+ loss_fct = MSELoss()
1542
+ if self.num_labels == 1:
1543
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1544
+ else:
1545
+ loss = loss_fct(pooled_logits, labels)
1546
+ elif self.config.problem_type == "single_label_classification":
1547
+ loss_fct = CrossEntropyLoss()
1548
+ loss = loss_fct(
1549
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1550
+ )
1551
+ elif self.config.problem_type == "multi_label_classification":
1552
+ loss_fct = BCEWithLogitsLoss()
1553
+ loss = loss_fct(pooled_logits, labels)
1554
  if not return_dict:
1555
  output = (pooled_logits,) + transformer_outputs[1:]
1556
  return ((loss,) + output) if loss is not None else output
 
1595
  input_ids: Optional[torch.LongTensor] = None,
1596
  attention_mask: Optional[torch.FloatTensor] = None,
1597
  position_ids: Optional[torch.LongTensor] = None,
1598
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1599
  inputs_embeds: Optional[torch.FloatTensor] = None,
1600
  start_positions: Optional[torch.LongTensor] = None,
1601
  end_positions: Optional[torch.LongTensor] = None,
1602
  output_attentions: Optional[bool] = None,
1603
  output_hidden_states: Optional[bool] = None,
1604
  return_dict: Optional[bool] = None,
 
1605
  ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1606
  r"""
1607
  start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
 
1613
  Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1614
  are not taken into account for computing the loss.
1615
  """
1616
+ return_dict = (
1617
+ return_dict if return_dict is not None else self.config.use_return_dict
1618
+ )
1619
 
1620
  outputs = self.transformer(
1621
  input_ids,
 
1635
  start_logits = start_logits.squeeze(-1).contiguous()
1636
  end_logits = end_logits.squeeze(-1).contiguous()
1637
 
1638
+ total_loss = None
1639
  if start_positions is not None and end_positions is not None:
1640
+ # If we are on multi-GPU, split add a dimension
1641
+ if len(start_positions.size()) > 1:
1642
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1643
+ if len(end_positions.size()) > 1:
1644
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1645
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1646
+ ignored_index = start_logits.size(1)
1647
+ start_positions = start_positions.clamp(0, ignored_index)
1648
+ end_positions = end_positions.clamp(0, ignored_index)
1649
+
1650
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1651
+ start_loss = loss_fct(start_logits, start_positions)
1652
+ end_loss = loss_fct(end_logits, end_positions)
1653
+ total_loss = (start_loss + end_loss) / 2
1654
 
1655
  if not return_dict:
1656
  output = (start_logits, end_logits) + outputs[2:]
1657
+ return ((total_loss,) + output) if total_loss is not None else output
1658
 
1659
  return QuestionAnsweringModelOutput(
1660
+ loss=total_loss,
1661
  start_logits=start_logits,
1662
  end_logits=end_logits,
1663
  hidden_states=outputs.hidden_states,
1664
  attentions=outputs.attentions,
1665
  )