zifei9 commited on
Commit
f64ed5f
·
verified ·
1 Parent(s): 9d4d38e

Update modeling_gpt2.py

Browse files

updating based on transformers==4.52.4

Files changed (1) hide show
  1. modeling_gpt2.py +573 -743
modeling_gpt2.py CHANGED
@@ -19,19 +19,18 @@ import math
19
  import os
20
  import warnings
21
  from dataclasses import dataclass
22
- from typing import Optional, Tuple, Union
23
 
24
  import torch
25
- import torch.utils.checkpoint
26
- from packaging import version
27
  from torch import nn
28
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
 
30
- from transformers.activations import ACT2FN
 
31
  from transformers.generation import GenerationMixin
32
  from transformers.modeling_attn_mask_utils import (
 
33
  _prepare_4d_attention_mask_for_sdpa,
34
- _prepare_4d_causal_attention_mask_for_sdpa,
35
  )
36
  from transformers.modeling_outputs import (
37
  BaseModelOutputWithPastAndCrossAttentions,
@@ -40,7 +39,7 @@ from transformers.modeling_outputs import (
40
  SequenceClassifierOutputWithPast,
41
  TokenClassifierOutput,
42
  )
43
- from transformers.modeling_utils import PreTrainedModel, SequenceSummary
44
  from transformers.pytorch_utils import (
45
  Conv1D,
46
  find_pruneable_heads_and_indices,
@@ -48,86 +47,21 @@ from transformers.pytorch_utils import (
48
  )
49
  from transformers.utils import (
50
  ModelOutput,
51
- add_code_sample_docstrings,
52
  add_start_docstrings,
53
- add_start_docstrings_to_model_forward,
54
- get_torch_version,
55
- is_flash_attn_2_available,
56
- is_flash_attn_greater_or_equal_2_10,
57
  logging,
58
- replace_return_docstrings,
59
  )
 
60
  from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
61
  from .configuration_gpt2 import GPT2Config
62
-
63
-
64
- if is_flash_attn_2_available():
65
- from transformers.modeling_flash_attention_utils import _flash_attention_forward
66
 
67
 
68
  logger = logging.get_logger(__name__)
69
 
70
- _CHECKPOINT_FOR_DOC = "openai-community/gpt2"
71
- _CONFIG_FOR_DOC = "GPT2Config"
72
-
73
-
74
- def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
75
- """Load tf checkpoints in a pytorch model"""
76
- try:
77
- import re
78
-
79
- import tensorflow as tf
80
- except ImportError:
81
- logger.error(
82
- "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
83
- "https://www.tensorflow.org/install/ for installation instructions."
84
- )
85
- raise
86
- tf_path = os.path.abspath(gpt2_checkpoint_path)
87
- logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
88
- # Load weights from TF model
89
- init_vars = tf.train.list_variables(tf_path)
90
- names = []
91
- arrays = []
92
- for name, shape in init_vars:
93
- logger.info(f"Loading TF weight {name} with shape {shape}")
94
- array = tf.train.load_variable(tf_path, name)
95
- names.append(name)
96
- arrays.append(array.squeeze())
97
-
98
- for name, array in zip(names, arrays):
99
- name = name[6:] # skip "model/"
100
- name = name.split("/")
101
- pointer = model
102
- for m_name in name:
103
- if re.fullmatch(r"[A-Za-z]+\d+", m_name):
104
- scope_names = re.split(r"(\d+)", m_name)
105
- else:
106
- scope_names = [m_name]
107
- if scope_names[0] == "w" or scope_names[0] == "g":
108
- pointer = getattr(pointer, "weight")
109
- elif scope_names[0] == "b":
110
- pointer = getattr(pointer, "bias")
111
- elif scope_names[0] == "wpe" or scope_names[0] == "wte":
112
- pointer = getattr(pointer, scope_names[0])
113
- pointer = getattr(pointer, "weight")
114
- else:
115
- pointer = getattr(pointer, scope_names[0])
116
- if len(scope_names) >= 2:
117
- num = int(scope_names[1])
118
- pointer = pointer[num]
119
- try:
120
- if pointer.shape != array.shape:
121
- raise ValueError(
122
- f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
123
- )
124
- except ValueError as e:
125
- e.args += (pointer.shape, array.shape)
126
- raise
127
- logger.info(f"Initialize PyTorch weight {name}")
128
- pointer.data = torch.from_numpy(array)
129
- return model
130
-
131
 
132
  class GPT2Attention(nn.Module):
133
  def __init__(self, config, is_cross_attention=False, layer_idx=None):
@@ -195,55 +129,6 @@ class GPT2Attention(nn.Module):
195
  self.num_heads = self.num_heads - len(heads)
196
  self.pruned_heads = self.pruned_heads.union(heads)
197
 
198
- def _attn(self, query, key, value, attention_mask=None, head_mask=None):
199
- attn_weights = torch.matmul(query, key.transpose(-1, -2))
200
-
201
- if self.scale_attn_weights:
202
- attn_weights = attn_weights / torch.full(
203
- [],
204
- value.size(-1) ** 0.5,
205
- dtype=attn_weights.dtype,
206
- device=attn_weights.device,
207
- )
208
-
209
- # Layer-wise attention scaling
210
- if self.scale_attn_by_inverse_layer_idx:
211
- attn_weights = attn_weights / float(self.layer_idx + 1)
212
-
213
- if not self.is_cross_attention:
214
- # if only "normal" attention layer implements causal mask
215
- query_length, key_length = query.size(-2), key.size(-2)
216
- causal_mask = self.bias[
217
- :, :, key_length - query_length : key_length, :key_length
218
- ]
219
- mask_value = torch.finfo(attn_weights.dtype).min
220
- # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
221
- # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
222
- mask_value = torch.full(
223
- [], mask_value, dtype=attn_weights.dtype, device=attn_weights.device
224
- )
225
- attn_weights = torch.where(
226
- causal_mask, attn_weights.to(attn_weights.dtype), mask_value
227
- )
228
-
229
- if attention_mask is not None:
230
- # Apply the attention mask
231
- attn_weights = attn_weights + attention_mask
232
-
233
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
234
-
235
- # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
236
- attn_weights = attn_weights.type(value.dtype)
237
- attn_weights = self.attn_dropout(attn_weights)
238
-
239
- # Mask heads if we want to
240
- if head_mask is not None:
241
- attn_weights = attn_weights * head_mask
242
-
243
- attn_output = torch.matmul(attn_weights, value)
244
-
245
- return attn_output, attn_weights
246
-
247
  def _upcast_and_reordered_attn(
248
  self, query, key, value, attention_mask=None, head_mask=None
249
  ):
@@ -287,8 +172,8 @@ class GPT2Attention(nn.Module):
287
  mask_value = torch.finfo(attn_weights.dtype).min
288
  # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
289
  # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
290
- mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(
291
- attn_weights.device
292
  )
293
  attn_weights = torch.where(causal_mask, attn_weights, mask_value)
294
 
@@ -311,321 +196,111 @@ class GPT2Attention(nn.Module):
311
  attn_weights = attn_weights * head_mask
312
 
313
  attn_output = torch.matmul(attn_weights, value)
 
314
 
315
  return attn_output, attn_weights
316
 
317
- def _split_heads(self, tensor, num_heads, attn_head_size):
318
- """
319
- Splits hidden_size dim into attn_head_size and num_heads
320
- """
321
- new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
322
- tensor = tensor.view(new_shape)
323
- return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
324
-
325
- def _merge_heads(self, tensor, num_heads, attn_head_size):
326
- """
327
- Merges attn_head_size dim and num_attn_heads dim into hidden_size
328
- """
329
- tensor = tensor.permute(0, 2, 1, 3).contiguous()
330
- new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
331
- return tensor.view(new_shape)
332
-
333
  def forward(
334
  self,
335
  hidden_states: Optional[Tuple[torch.FloatTensor]],
336
- layer_past: Optional[Tuple[torch.Tensor]] = None,
 
337
  attention_mask: Optional[torch.FloatTensor] = None,
338
  head_mask: Optional[torch.FloatTensor] = None,
339
  encoder_hidden_states: Optional[torch.Tensor] = None,
340
  encoder_attention_mask: Optional[torch.FloatTensor] = None,
341
- use_cache: Optional[bool] = False,
342
  output_attentions: Optional[bool] = False,
 
343
  ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
344
- if encoder_hidden_states is not None:
 
345
  if not hasattr(self, "q_attn"):
346
  raise ValueError(
347
  "If class is used as cross attention, the weights `q_attn` have to be defined. "
348
  "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
349
  )
350
 
351
- query = self.q_attn(hidden_states)
352
- key, value = self.c_attn(encoder_hidden_states).split(
353
  self.split_size, dim=2
354
  )
355
  attention_mask = encoder_attention_mask
356
  else:
357
- query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
358
-
359
- query = self._split_heads(query, self.num_heads, self.head_dim)
360
- key = self._split_heads(key, self.num_heads, self.head_dim)
361
- value = self._split_heads(value, self.num_heads, self.head_dim)
362
-
363
- if layer_past is not None:
364
- past_key, past_value = layer_past
365
- key = torch.cat((past_key, key), dim=-2)
366
- value = torch.cat((past_value, value), dim=-2)
367
-
368
- if use_cache is True:
369
- present = (key, value)
370
- else:
371
- present = None
372
-
373
- if self.reorder_and_upcast_attn:
374
- attn_output, attn_weights = self._upcast_and_reordered_attn(
375
- query, key, value, attention_mask, head_mask
376
- )
377
- else:
378
- attn_output, attn_weights = self._attn(
379
- query, key, value, attention_mask, head_mask
380
- )
381
-
382
- attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
383
- attn_output = self.c_proj(attn_output)
384
- attn_output = self.resid_dropout(attn_output)
385
-
386
- outputs = (attn_output, present)
387
- if output_attentions:
388
- outputs += (attn_weights,)
389
-
390
- return outputs # a, present, (attentions)
391
-
392
-
393
- class GPT2FlashAttention2(GPT2Attention):
394
- """
395
- GPT2 flash attention module. This module inherits from `GPT2Attention` as the weights of the module stays
396
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
397
- flash attention and deal with padding tokens in case the input contains any of them.
398
- """
399
-
400
- # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
401
- def __init__(self, *args, **kwargs):
402
- super().__init__(*args, **kwargs)
403
-
404
- # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
405
- # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
406
- # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
407
- self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
408
-
409
- def forward(
410
- self,
411
- hidden_states: Optional[Tuple[torch.FloatTensor]],
412
- layer_past: Optional[Tuple[torch.Tensor]] = None,
413
- attention_mask: Optional[torch.FloatTensor] = None,
414
- head_mask: Optional[torch.FloatTensor] = None,
415
- encoder_hidden_states: Optional[torch.Tensor] = None,
416
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
417
- use_cache: Optional[bool] = False,
418
- output_attentions: Optional[bool] = False,
419
- ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
420
- bsz, _, _ = hidden_states.size()
421
- if encoder_hidden_states is not None:
422
- if not hasattr(self, "q_attn"):
423
- raise ValueError(
424
- "If class is used as cross attention, the weights `q_attn` have to be defined. "
425
- "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
426
- )
427
-
428
- query = self.q_attn(hidden_states)
429
- key, value = self.c_attn(encoder_hidden_states).split(
430
  self.split_size, dim=2
431
  )
432
- attention_mask = encoder_attention_mask
433
- else:
434
- query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
435
-
436
- query = self._split_heads(query, self.num_heads, self.head_dim)
437
- key = self._split_heads(key, self.num_heads, self.head_dim)
438
- value = self._split_heads(value, self.num_heads, self.head_dim)
439
-
440
- if layer_past is not None:
441
- past_key = layer_past[0]
442
- past_value = layer_past[1]
443
- key = torch.cat((past_key, key), dim=-2)
444
- value = torch.cat((past_value, value), dim=-2)
445
 
446
- present = None
447
- if use_cache is True:
448
- present = (key, value)
449
 
450
- query_length = query.shape[2]
451
- tgt_len = key.shape[2]
 
452
 
453
- # Flash attention requires the input to have the shape
454
- # batch_size x seq_length x head_dim x hidden_dim
455
- query = query.transpose(1, 2).view(
456
- bsz, query_length, self.num_heads, self.head_dim
457
- )
458
- key = key.transpose(1, 2).view(bsz, tgt_len, self.num_heads, self.head_dim)
459
- value = value.transpose(1, 2).view(bsz, tgt_len, self.num_heads, self.head_dim)
460
-
461
- attn_dropout = self.attn_dropout.p if self.training else 0.0
462
-
463
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
464
- # therefore the input hidden states gets silently casted in float32. Hence, we need
465
- # cast them back in the correct dtype just to be sure everything works as expected.
466
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
467
- # in fp32. (LlamaRMSNorm handles it correctly)
468
-
469
- if query.dtype == torch.float32:
470
- if torch.is_autocast_enabled():
471
- target_dtype = torch.get_autocast_gpu_dtype()
472
- # Handle the case where the model is quantized
473
- elif hasattr(self.config, "_pre_quantization_dtype"):
474
- target_dtype = self.config._pre_quantization_dtype
475
- else:
476
- target_dtype = self.c_proj.weight.dtype
477
-
478
- logger.warning_once(
479
- f"The input hidden states seems to be silently casted in float32, this might be related to"
480
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
481
- f" {target_dtype}."
482
  )
483
 
484
- query = query.to(target_dtype)
485
- key = key.to(target_dtype)
486
- value = value.to(target_dtype)
487
-
488
- attn_output = _flash_attention_forward(
489
- query,
490
- key,
491
- value,
492
- attention_mask,
493
- query_length,
494
- dropout=attn_dropout,
495
- is_causal=self.is_causal,
496
- use_top_left_mask=self._flash_attn_uses_top_left_mask,
497
- )
498
-
499
- attn_weights_reshaped = attn_output.reshape(
500
- bsz, query_length, self.num_heads * self.head_dim
501
  )
502
- attn_output = self.c_proj(attn_weights_reshaped)
503
- attn_output = self.resid_dropout(attn_output)
504
-
505
- outputs = (attn_output, present)
506
- if output_attentions:
507
- outputs += (attn_weights_reshaped,)
508
-
509
- return outputs
510
-
511
-
512
- class GPT2SdpaAttention(GPT2Attention):
513
- """
514
- GPT2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
515
- `GPT2Attention` as the weights of the module stays untouched. The only changes are on the forward pass
516
- to adapt to the SDPA API.
517
- """
518
-
519
- def __init__(self, *args, **kwargs):
520
- super().__init__(*args, **kwargs)
521
-
522
- # Idea adapted from transformers.models.bert.modeling_bert.BertSdpaSelfAttention.__init__
523
- # SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
524
- # attn_mask, so we need to call `.contiguous()`. This was fixed in torch==2.2.0.
525
- # Reference: https://github.com/pytorch/pytorch/issues/112577
526
- self.require_contiguous_qkv = version.parse(
527
- get_torch_version()
528
- ) < version.parse("2.2.0")
529
-
530
- def forward(
531
- self,
532
- hidden_states: Optional[Tuple[torch.FloatTensor]],
533
- layer_past: Optional[Tuple[torch.Tensor]] = None,
534
- attention_mask: Optional[torch.FloatTensor] = None,
535
- head_mask: Optional[torch.FloatTensor] = None,
536
- encoder_hidden_states: Optional[torch.Tensor] = None,
537
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
538
- use_cache: Optional[bool] = False,
539
- output_attentions: Optional[bool] = False,
540
- ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
541
- if output_attentions or head_mask is not None:
542
- logger.warning_once(
543
- "`GPT2SdpaAttention` is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
544
- "`output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but "
545
- "specifying the manual implementation will be required from Transformers version v5.0.0 onwards. "
546
- 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
547
- )
548
- return super().forward(
549
- hidden_states=hidden_states,
550
- layer_past=layer_past,
551
- attention_mask=attention_mask,
552
- head_mask=head_mask,
553
- encoder_hidden_states=encoder_hidden_states,
554
- encoder_attention_mask=encoder_attention_mask,
555
- use_cache=use_cache,
556
- output_attentions=output_attentions,
557
- )
558
 
559
- bsz, q_len, _ = hidden_states.size()
560
-
561
- # Initial attention projections
562
- is_cross_attention = encoder_hidden_states is not None
563
- if is_cross_attention:
564
- if not hasattr(self, "q_attn"):
565
- raise ValueError(
566
- "If class is used as cross attention, the weights `q_attn` have to be defined. "
567
- "Please make sure to instantiate class with `GPT2SdpaAttention(..., is_cross_attention=True)`."
 
568
  )
 
 
 
 
 
 
 
569
 
570
- query = self.q_attn(hidden_states)
571
- key, value = self.c_attn(encoder_hidden_states).split(
572
- self.split_size, dim=2
573
  )
574
- attention_mask = encoder_attention_mask
575
  else:
576
- query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
577
-
578
- query = self._split_heads(query, self.num_heads, self.head_dim)
579
- key = self._split_heads(key, self.num_heads, self.head_dim)
580
- value = self._split_heads(value, self.num_heads, self.head_dim)
581
-
582
- # Optional kv caching
583
- if layer_past is not None:
584
- past_key = layer_past[0]
585
- past_value = layer_past[1]
586
- key = torch.cat((past_key, key), dim=-2)
587
- value = torch.cat((past_value, value), dim=-2)
588
-
589
- present = None
590
- if use_cache is True:
591
- present = (key, value)
592
-
593
- # Avoid torch==2.1.2 specific bug for the memory-efficient backend in SDPA
594
- if (
595
- self.require_contiguous_qkv
596
- and query.device.type == "cuda"
597
- and attention_mask is not None
598
- ):
599
- query = query.contiguous()
600
- key = key.contiguous()
601
- value = value.contiguous()
602
-
603
- # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
604
- # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
605
- is_causal = (
606
- True
607
- if attention_mask is None and q_len > 1 and not is_cross_attention
608
- else False
609
- )
610
-
611
- attn_output = torch.nn.functional.scaled_dot_product_attention(
612
- query,
613
- key,
614
- value,
615
- attn_mask=attention_mask,
616
- dropout_p=self.attn_dropout.p if self.training else 0.0,
617
- is_causal=is_causal,
618
- )
619
-
620
- # Reshape outputs
621
- attn_output = attn_output.transpose(1, 2).contiguous()
622
- attn_output = attn_output.view(bsz, q_len, self.embed_dim)
623
 
624
- # Final projection
625
  attn_output = self.c_proj(attn_output)
626
  attn_output = self.resid_dropout(attn_output)
627
 
628
- return attn_output, present, None
629
 
630
 
631
  class GPT2MLP(nn.Module):
@@ -647,26 +322,18 @@ class GPT2MLP(nn.Module):
647
  return hidden_states
648
 
649
 
650
- GPT2_ATTENTION_CLASSES = {
651
- "eager": GPT2Attention,
652
- "flash_attention_2": GPT2FlashAttention2,
653
- "sdpa": GPT2SdpaAttention,
654
- }
655
-
656
-
657
  class GPT2Block(nn.Module):
658
  def __init__(self, config, layer_idx=None):
659
  super().__init__()
660
  hidden_size = config.hidden_size
661
  inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
662
- attention_class = GPT2_ATTENTION_CLASSES[config._attn_implementation]
663
 
664
  self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
665
- self.attn = attention_class(config=config, layer_idx=layer_idx)
666
  self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
667
 
668
  if config.add_cross_attention:
669
- self.crossattention = attention_class(
670
  config=config, is_cross_attention=True, layer_idx=layer_idx
671
  )
672
  self.ln_cross_attn = nn.LayerNorm(
@@ -675,32 +342,40 @@ class GPT2Block(nn.Module):
675
 
676
  self.mlp = GPT2MLP(inner_dim, config)
677
 
 
 
 
 
 
 
678
  def forward(
679
  self,
680
  hidden_states: Optional[Tuple[torch.FloatTensor]],
681
- layer_past: Optional[Tuple[torch.Tensor]] = None,
 
682
  attention_mask: Optional[torch.FloatTensor] = None,
683
  head_mask: Optional[torch.FloatTensor] = None,
684
  encoder_hidden_states: Optional[torch.Tensor] = None,
685
  encoder_attention_mask: Optional[torch.FloatTensor] = None,
686
  use_cache: Optional[bool] = False,
687
  output_attentions: Optional[bool] = False,
 
688
  ) -> Union[
689
  Tuple[torch.Tensor],
690
  Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]],
691
  ]:
692
  residual = hidden_states
693
  hidden_states = self.ln_1(hidden_states)
694
- attn_outputs = self.attn(
695
  hidden_states,
696
- layer_past=layer_past,
 
697
  attention_mask=attention_mask,
698
  head_mask=head_mask,
699
  use_cache=use_cache,
700
  output_attentions=output_attentions,
 
701
  )
702
- attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
703
- outputs = attn_outputs[1:]
704
  # residual connection
705
  hidden_states = attn_output + residual
706
 
@@ -713,20 +388,17 @@ class GPT2Block(nn.Module):
713
  )
714
  residual = hidden_states
715
  hidden_states = self.ln_cross_attn(hidden_states)
716
- cross_attn_outputs = self.crossattention(
717
  hidden_states,
 
718
  attention_mask=attention_mask,
719
  head_mask=head_mask,
720
  encoder_hidden_states=encoder_hidden_states,
721
  encoder_attention_mask=encoder_attention_mask,
722
  output_attentions=output_attentions,
723
  )
724
- attn_output = cross_attn_outputs[0]
725
  # residual connection
726
- hidden_states = residual + attn_output
727
- outputs = (
728
- outputs + cross_attn_outputs[2:]
729
- ) # add cross attentions if we output attention weights
730
 
731
  residual = hidden_states
732
  hidden_states = self.ln_2(hidden_states)
@@ -734,20 +406,132 @@ class GPT2Block(nn.Module):
734
  # residual connection
735
  hidden_states = residual + feed_forward_hidden_states
736
 
737
- if use_cache:
738
- outputs = (hidden_states,) + outputs
739
- else:
740
- outputs = (hidden_states,) + outputs[1:]
 
741
 
742
- return outputs # hidden_states, present, (attentions, cross_attentions)
743
 
744
 
745
- class GPT2PreTrainedModel(PreTrainedModel):
746
- """
747
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
748
- models.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
  """
750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
751
  config_class = GPT2Config
752
  load_tf_weights = load_tf_weights_in_gpt2
753
  base_model_prefix = "transformer"
@@ -757,6 +541,9 @@ class GPT2PreTrainedModel(PreTrainedModel):
757
  _skip_keys_device_placement = "past_key_values"
758
  _supports_flash_attn_2 = True
759
  _supports_sdpa = True
 
 
 
760
 
761
  def __init__(self, *inputs, **kwargs):
762
  super().__init__(*inputs, **kwargs)
@@ -830,96 +617,13 @@ class GPT2DoubleHeadsModelOutput(ModelOutput):
830
 
831
  loss: Optional[torch.FloatTensor] = None
832
  mc_loss: Optional[torch.FloatTensor] = None
833
- logits: torch.FloatTensor = None
834
- mc_logits: torch.FloatTensor = None
835
  past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
836
  hidden_states: Optional[Tuple[torch.FloatTensor]] = None
837
  attentions: Optional[Tuple[torch.FloatTensor]] = None
838
 
839
 
840
- GPT2_START_DOCSTRING = r"""
841
-
842
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
843
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
844
- etc.)
845
-
846
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
847
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
848
- and behavior.
849
-
850
- Parameters:
851
- config ([`GPT2Config`]): Model configuration class with all the parameters of the model.
852
- Initializing with a config file does not load the weights associated with the model, only the
853
- configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
854
- """
855
-
856
- GPT2_INPUTS_DOCSTRING = r"""
857
- Args:
858
- input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
859
- `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
860
- `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
861
- sequence tokens in the vocabulary.
862
-
863
- If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
864
- `input_ids`.
865
-
866
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
867
- [`PreTrainedTokenizer.__call__`] for details.
868
-
869
- [What are input IDs?](../glossary#input-ids)
870
- past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
871
- Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
872
- `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
873
- their past given to this model should not be passed as `input_ids` as they have already been computed.
874
- attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
875
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
876
-
877
- - 1 for tokens that are **not masked**,
878
- - 0 for tokens that are **masked**.
879
-
880
- If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
881
- `past_key_values`. In other words, the `attention_mask` always has to have the length:
882
- `len(past_key_values) + len(input_ids)`
883
-
884
- [What are attention masks?](../glossary#attention-mask)
885
- token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
886
- Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
887
- 1]`:
888
-
889
- - 0 corresponds to a *sentence A* token,
890
- - 1 corresponds to a *sentence B* token.
891
-
892
- [What are token type IDs?](../glossary#token-type-ids)
893
- position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
894
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
895
- config.max_position_embeddings - 1]`.
896
-
897
- [What are position IDs?](../glossary#position-ids)
898
- head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
899
- Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
900
-
901
- - 1 indicates the head is **not masked**,
902
- - 0 indicates the head is **masked**.
903
-
904
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
905
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
906
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
907
- model's internal embedding lookup matrix.
908
-
909
- If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
910
- `past_key_values`).
911
- use_cache (`bool`, *optional*):
912
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
913
- `past_key_values`).
914
- output_attentions (`bool`, *optional*):
915
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
916
- tensors for more detail.
917
- output_hidden_states (`bool`, *optional*):
918
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
919
- more detail.
920
- return_dict (`bool`, *optional*):
921
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
922
- """
923
  PARALLELIZE_DOCSTRING = r"""
924
  This is an experimental feature and is a subject to change at a moment's notice.
925
 
@@ -972,10 +676,7 @@ DEPARALLELIZE_DOCSTRING = r"""
972
  """
973
 
974
 
975
- @add_start_docstrings(
976
- "The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.",
977
- GPT2_START_DOCSTRING,
978
- )
979
  class GPT2Model(GPT2PreTrainedModel):
980
  _supports_param_buffer_assignment = False
981
 
@@ -1065,16 +766,12 @@ class GPT2Model(GPT2PreTrainedModel):
1065
  for layer, heads in heads_to_prune.items():
1066
  self.h[layer].attn.prune_heads(heads)
1067
 
1068
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1069
- @add_code_sample_docstrings(
1070
- checkpoint=_CHECKPOINT_FOR_DOC,
1071
- output_type=BaseModelOutputWithPastAndCrossAttentions,
1072
- config_class=_CONFIG_FOR_DOC,
1073
- )
1074
  def forward(
1075
  self,
1076
  input_ids: Optional[torch.LongTensor] = None,
1077
- past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
 
1078
  attention_mask: Optional[torch.FloatTensor] = None,
1079
  token_type_ids: Optional[torch.LongTensor] = None,
1080
  position_ids: Optional[torch.LongTensor] = None,
@@ -1086,7 +783,22 @@ class GPT2Model(GPT2PreTrainedModel):
1086
  output_attentions: Optional[bool] = None,
1087
  output_hidden_states: Optional[bool] = None,
1088
  return_dict: Optional[bool] = None,
 
1089
  ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1090
  output_attentions = (
1091
  output_attentions
1092
  if output_attentions is not None
@@ -1122,68 +834,70 @@ class GPT2Model(GPT2PreTrainedModel):
1122
  if token_type_ids is not None:
1123
  token_type_ids = token_type_ids.view(-1, input_shape[-1])
1124
 
1125
- if past_key_values is None:
1126
- past_length = 0
1127
- past_key_values = tuple([None] * len(self.h))
1128
- else:
1129
- past_length = past_key_values[0][0].size(-2)
1130
- if position_ids is None:
1131
- position_ids = torch.arange(
1132
- past_length,
1133
- input_shape[-1] + past_length,
1134
- dtype=torch.long,
1135
- device=device,
1136
- )
1137
- position_ids = position_ids.unsqueeze(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
1138
 
1139
  if inputs_embeds is None:
1140
  inputs_embeds = self.wte(input_ids)
 
 
 
 
 
 
 
 
 
 
 
 
 
1141
  position_embeds = self.wpe(position_ids)
1142
- hidden_states = inputs_embeds + position_embeds
1143
 
1144
  # Attention mask.
 
 
 
 
 
 
 
 
 
 
 
 
 
1145
  _use_sdpa = (
1146
  self._attn_implementation == "sdpa"
1147
  and output_attentions is False
1148
  and head_mask is None
1149
  )
1150
- attention_mask = (
1151
- attention_mask.view(batch_size, -1) if attention_mask is not None else None
1152
- )
1153
- if self._attn_implementation == "flash_attention_2":
1154
- attention_mask = (
1155
- attention_mask
1156
- if (attention_mask is not None and 0 in attention_mask)
1157
- else None
1158
- )
1159
- elif _use_sdpa:
1160
- attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1161
- attention_mask=attention_mask,
1162
- input_shape=(batch_size, input_shape[-1]),
1163
- inputs_embeds=inputs_embeds,
1164
- past_key_values_length=past_length,
1165
- )
1166
- else:
1167
- if attention_mask is not None:
1168
- # We create a 3D attention mask from a 2D tensor mask.
1169
- # Sizes are [batch_size, 1, 1, to_seq_length]
1170
- # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
1171
- # this attention mask is more simple than the triangular masking of causal attention
1172
- # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
1173
- attention_mask = attention_mask[:, None, None, :]
1174
-
1175
- # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
1176
- # masked positions, this operation will create a tensor which is 0.0 for
1177
- # positions we want to attend and the dtype's smallest value for masked positions.
1178
- # Since we are adding it to the raw scores before the softmax, this is
1179
- # effectively the same as removing these entirely.
1180
- attention_mask = attention_mask.to(
1181
- dtype=self.dtype
1182
- ) # fp16 compatibility
1183
- attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
1184
-
1185
- # If a 2D or 3D attention mask is provided for the cross-attention
1186
- # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1187
  if self.config.add_cross_attention and encoder_hidden_states is not None:
1188
  encoder_batch_size, encoder_sequence_length, _ = (
1189
  encoder_hidden_states.size()
@@ -1218,29 +932,15 @@ class GPT2Model(GPT2PreTrainedModel):
1218
 
1219
  output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
1220
 
1221
- if self.gradient_checkpointing and self.training:
1222
- if use_cache:
1223
- logger.warning_once(
1224
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1225
- )
1226
- use_cache = False
1227
-
1228
- presents = () if use_cache else None
1229
  all_self_attentions = () if output_attentions else None
1230
  all_cross_attentions = (
1231
  () if output_attentions and self.config.add_cross_attention else None
1232
  )
1233
  all_hidden_states = () if output_hidden_states else None
1234
- for i in range(len(self.h)):
1235
- block, layer_past = self.h[i], past_key_values[i]
1236
  # Model parallel
1237
  if self.model_parallel:
1238
  torch.cuda.set_device(hidden_states.device)
1239
- # Ensure layer_past is on same device as hidden_states (might not be correct)
1240
- if layer_past is not None:
1241
- layer_past = tuple(
1242
- past_state.to(hidden_states.device) for past_state in layer_past
1243
- )
1244
  # Ensure that attention_mask is always on the same device as hidden_states
1245
  if attention_mask is not None:
1246
  attention_mask = attention_mask.to(hidden_states.device)
@@ -1253,8 +953,9 @@ class GPT2Model(GPT2PreTrainedModel):
1253
  outputs = self._gradient_checkpointing_func(
1254
  block.__call__,
1255
  hidden_states,
1256
- None,
1257
- attention_mask,
 
1258
  head_mask[i],
1259
  encoder_hidden_states,
1260
  encoder_attention_mask,
@@ -1264,27 +965,23 @@ class GPT2Model(GPT2PreTrainedModel):
1264
  else:
1265
  outputs = block(
1266
  hidden_states,
1267
- layer_past=layer_past,
1268
- attention_mask=attention_mask,
 
1269
  head_mask=head_mask[i],
1270
  encoder_hidden_states=encoder_hidden_states,
1271
  encoder_attention_mask=encoder_attention_mask,
1272
  use_cache=use_cache,
1273
  output_attentions=output_attentions,
 
1274
  )
1275
 
1276
  hidden_states = outputs[0]
1277
- if use_cache is True:
1278
- presents = presents + (outputs[1],)
1279
 
1280
  if output_attentions:
1281
- all_self_attentions = all_self_attentions + (
1282
- outputs[2 if use_cache else 1],
1283
- )
1284
  if self.config.add_cross_attention:
1285
- all_cross_attentions = all_cross_attentions + (
1286
- outputs[3 if use_cache else 2],
1287
- )
1288
 
1289
  # Model Parallel: If it's the last layer for that device, put things on the next device
1290
  if self.model_parallel:
@@ -1299,12 +996,19 @@ class GPT2Model(GPT2PreTrainedModel):
1299
  if output_hidden_states:
1300
  all_hidden_states = all_hidden_states + (hidden_states,)
1301
 
 
 
 
 
 
 
 
1302
  if not return_dict:
1303
  return tuple(
1304
  v
1305
  for v in [
1306
  hidden_states,
1307
- presents,
1308
  all_hidden_states,
1309
  all_self_attentions,
1310
  all_cross_attentions,
@@ -1314,19 +1018,153 @@ class GPT2Model(GPT2PreTrainedModel):
1314
 
1315
  return BaseModelOutputWithPastAndCrossAttentions(
1316
  last_hidden_state=hidden_states,
1317
- past_key_values=presents,
1318
  hidden_states=all_hidden_states,
1319
  attentions=all_self_attentions,
1320
  cross_attentions=all_cross_attentions,
1321
  )
1322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1323
 
1324
- @add_start_docstrings(
1325
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1326
  The GPT2 Model transformer with a language modeling head on top (linear layer with weights tied to the input
1327
  embeddings).
1328
- """,
1329
- GPT2_START_DOCSTRING,
1330
  )
1331
  class GPT2LMHeadModel(GPT2PreTrainedModel, GenerationMixin):
1332
  _tied_weights_keys = ["lm_head.weight"]
@@ -1380,16 +1218,12 @@ class GPT2LMHeadModel(GPT2PreTrainedModel, GenerationMixin):
1380
  def set_output_embeddings(self, new_embeddings):
1381
  self.lm_head = new_embeddings
1382
 
1383
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1384
- @add_code_sample_docstrings(
1385
- checkpoint=_CHECKPOINT_FOR_DOC,
1386
- output_type=CausalLMOutputWithCrossAttentions,
1387
- config_class=_CONFIG_FOR_DOC,
1388
- )
1389
  def forward(
1390
  self,
1391
  input_ids: Optional[torch.LongTensor] = None,
1392
  past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
 
1393
  attention_mask: Optional[torch.FloatTensor] = None,
1394
  token_type_ids: Optional[torch.LongTensor] = None,
1395
  position_ids: Optional[torch.LongTensor] = None,
@@ -1402,9 +1236,22 @@ class GPT2LMHeadModel(GPT2PreTrainedModel, GenerationMixin):
1402
  output_attentions: Optional[bool] = None,
1403
  output_hidden_states: Optional[bool] = None,
1404
  return_dict: Optional[bool] = None,
 
1405
  ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1406
  r"""
1407
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
 
 
 
 
 
 
 
 
 
 
 
 
1408
  Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1409
  `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1410
  are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
@@ -1417,6 +1264,7 @@ class GPT2LMHeadModel(GPT2PreTrainedModel, GenerationMixin):
1417
  input_ids,
1418
  past_key_values=past_key_values,
1419
  attention_mask=attention_mask,
 
1420
  token_type_ids=token_type_ids,
1421
  position_ids=position_ids,
1422
  head_mask=head_mask,
@@ -1439,15 +1287,12 @@ class GPT2LMHeadModel(GPT2PreTrainedModel, GenerationMixin):
1439
 
1440
  loss = None
1441
  if labels is not None:
1442
- # move labels to correct device to enable model parallelism
1443
- labels = labels.to(lm_logits.device)
1444
- # Shift so that tokens < n predict n
1445
- shift_logits = lm_logits[..., :-1, :].contiguous()
1446
- shift_labels = labels[..., 1:].contiguous()
1447
  # Flatten the tokens
1448
- loss_fct = CrossEntropyLoss()
1449
- loss = loss_fct(
1450
- shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
 
 
1451
  )
1452
 
1453
  if not return_dict:
@@ -1463,32 +1308,14 @@ class GPT2LMHeadModel(GPT2PreTrainedModel, GenerationMixin):
1463
  cross_attentions=transformer_outputs.cross_attentions,
1464
  )
1465
 
1466
- @staticmethod
1467
- def _reorder_cache(
1468
- past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1469
- ) -> Tuple[Tuple[torch.Tensor]]:
1470
- """
1471
- This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1472
- [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1473
- beam_idx at every generation step.
1474
- """
1475
- return tuple(
1476
- tuple(
1477
- past_state.index_select(0, beam_idx.to(past_state.device))
1478
- for past_state in layer_past
1479
- )
1480
- for layer_past in past_key_values
1481
- )
1482
-
1483
 
1484
- @add_start_docstrings(
 
 
 
 
 
1485
  """
1486
- The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1487
- RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1488
- input embeddings, the classification head takes as input the input of a specified classification token index in the
1489
- input sequence).
1490
- """,
1491
- GPT2_START_DOCSTRING,
1492
  )
1493
  class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1494
  _tied_weights_keys = ["lm_head.weight"]
@@ -1498,7 +1325,7 @@ class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1498
  config.num_labels = 1
1499
  self.transformer = GPT2Model(config)
1500
  self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1501
- self.multiple_choice_head = SequenceSummary(config)
1502
 
1503
  # Model parallel
1504
  self.model_parallel = False
@@ -1548,14 +1375,12 @@ class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1548
  def set_output_embeddings(self, new_embeddings):
1549
  self.lm_head = new_embeddings
1550
 
1551
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1552
- @replace_return_docstrings(
1553
- output_type=GPT2DoubleHeadsModelOutput, config_class=_CONFIG_FOR_DOC
1554
- )
1555
  def forward(
1556
  self,
1557
  input_ids: Optional[torch.LongTensor] = None,
1558
  past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
 
1559
  attention_mask: Optional[torch.FloatTensor] = None,
1560
  token_type_ids: Optional[torch.LongTensor] = None,
1561
  position_ids: Optional[torch.LongTensor] = None,
@@ -1571,10 +1396,22 @@ class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1571
  **kwargs,
1572
  ) -> Union[Tuple, GPT2DoubleHeadsModelOutput]:
1573
  r"""
 
 
 
 
 
 
 
 
 
 
 
 
1574
  mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
1575
  Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
1576
  1]`.
1577
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1578
  Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1579
  `labels = input_ids`. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to
1580
  `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`
@@ -1582,8 +1419,6 @@ class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1582
  Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1583
  where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
1584
 
1585
- Return:
1586
-
1587
  Example:
1588
 
1589
  ```python
@@ -1616,6 +1451,7 @@ class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1616
  transformer_outputs = self.transformer(
1617
  input_ids,
1618
  past_key_values=past_key_values,
 
1619
  attention_mask=attention_mask,
1620
  token_type_ids=token_type_ids,
1621
  position_ids=position_ids,
@@ -1687,8 +1523,8 @@ class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1687
  )
1688
 
1689
 
1690
- @add_start_docstrings(
1691
- """
1692
  The GPT2 Model transformer with a sequence classification head on top (linear layer).
1693
 
1694
  [`GPT2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
@@ -1699,8 +1535,7 @@ class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1699
  no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1700
  padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1701
  each row of the batch).
1702
- """,
1703
- GPT2_START_DOCSTRING,
1704
  )
1705
  class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1706
  def __init__(self, config):
@@ -1716,12 +1551,7 @@ class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1716
  # Initialize weights and apply final processing
1717
  self.post_init()
1718
 
1719
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1720
- @add_code_sample_docstrings(
1721
- checkpoint="microsoft/DialogRPT-updown",
1722
- output_type=SequenceClassifierOutputWithPast,
1723
- config_class=_CONFIG_FOR_DOC,
1724
- )
1725
  def forward(
1726
  self,
1727
  input_ids: Optional[torch.LongTensor] = None,
@@ -1738,6 +1568,18 @@ class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1738
  return_dict: Optional[bool] = None,
1739
  ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1740
  r"""
 
 
 
 
 
 
 
 
 
 
 
 
1741
  labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1742
  Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1743
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
@@ -1768,28 +1610,30 @@ class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1768
  else:
1769
  batch_size, sequence_length = inputs_embeds.shape[:2]
1770
 
1771
- assert (
1772
- self.config.pad_token_id is not None or batch_size == 1
1773
- ), "Cannot handle batch sizes > 1 if no padding token is defined."
 
1774
  if self.config.pad_token_id is None:
1775
- sequence_lengths = -1
 
 
 
 
 
 
 
 
 
1776
  else:
1777
- if input_ids is not None:
1778
- # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1779
- sequence_lengths = (
1780
- torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1781
- )
1782
- sequence_lengths = sequence_lengths % input_ids.shape[-1]
1783
- sequence_lengths = sequence_lengths.to(logits.device)
1784
- else:
1785
- sequence_lengths = -1
1786
- logger.warning_once(
1787
- f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1788
- "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1789
- )
1790
 
1791
  pooled_logits = logits[
1792
- torch.arange(batch_size, device=logits.device), sequence_lengths
1793
  ]
1794
 
1795
  loss = None
@@ -1831,13 +1675,7 @@ class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1831
  )
1832
 
1833
 
1834
- @add_start_docstrings(
1835
- """
1836
- GPT2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1837
- Named-Entity-Recognition (NER) tasks.
1838
- """,
1839
- GPT2_START_DOCSTRING,
1840
- )
1841
  class GPT2ForTokenClassification(GPT2PreTrainedModel):
1842
  def __init__(self, config):
1843
  super().__init__(config)
@@ -1863,29 +1701,7 @@ class GPT2ForTokenClassification(GPT2PreTrainedModel):
1863
  # Initialize weights and apply final processing
1864
  self.post_init()
1865
 
1866
- @add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
1867
- # fmt: off
1868
- @add_code_sample_docstrings(
1869
- checkpoint="brad1141/gpt2-finetuned-comp2",
1870
- output_type=TokenClassifierOutput,
1871
- config_class=_CONFIG_FOR_DOC,
1872
- expected_loss=0.25,
1873
- expected_output=[
1874
- "Lead",
1875
- "Lead",
1876
- "Lead",
1877
- "Position",
1878
- "Lead",
1879
- "Lead",
1880
- "Lead",
1881
- "Lead",
1882
- "Lead",
1883
- "Lead",
1884
- "Lead",
1885
- "Lead",
1886
- ],
1887
- )
1888
- # fmt: on
1889
  def forward(
1890
  self,
1891
  input_ids: Optional[torch.LongTensor] = None,
@@ -1902,6 +1718,18 @@ class GPT2ForTokenClassification(GPT2PreTrainedModel):
1902
  return_dict: Optional[bool] = None,
1903
  ) -> Union[Tuple, TokenClassifierOutput]:
1904
  r"""
 
 
 
 
 
 
 
 
 
 
 
 
1905
  labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1906
  Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1907
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
@@ -1947,13 +1775,7 @@ class GPT2ForTokenClassification(GPT2PreTrainedModel):
1947
  )
1948
 
1949
 
1950
- @add_start_docstrings(
1951
- """
1952
- The GPT-2 Model transformer with a span classification head on top for extractive question-answering tasks like
1953
- SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1954
- """,
1955
- GPT2_START_DOCSTRING,
1956
- )
1957
  class GPT2ForQuestionAnswering(GPT2PreTrainedModel):
1958
  def __init__(self, config):
1959
  super().__init__(config)
@@ -1968,15 +1790,7 @@ class GPT2ForQuestionAnswering(GPT2PreTrainedModel):
1968
  # Initialize weights and apply final processing
1969
  self.post_init()
1970
 
1971
- @add_start_docstrings_to_model_forward(
1972
- GPT2_INPUTS_DOCSTRING.format("batch_size, sequence_length")
1973
- )
1974
- @add_code_sample_docstrings(
1975
- checkpoint=_CHECKPOINT_FOR_DOC,
1976
- output_type=QuestionAnsweringModelOutput,
1977
- config_class=_CONFIG_FOR_DOC,
1978
- real_checkpoint=_CHECKPOINT_FOR_DOC,
1979
- )
1980
  def forward(
1981
  self,
1982
  input_ids: Optional[torch.LongTensor] = None,
@@ -1992,14 +1806,18 @@ class GPT2ForQuestionAnswering(GPT2PreTrainedModel):
1992
  return_dict: Optional[bool] = None,
1993
  ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1994
  r"""
1995
- start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1996
- Labels for position (index) of the start of the labelled span for computing the token classification loss.
1997
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1998
- are not taken into account for computing the loss.
1999
- end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2000
- Labels for position (index) of the end of the labelled span for computing the token classification loss.
2001
- Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
2002
- are not taken into account for computing the loss.
 
 
 
 
2003
  """
2004
  return_dict = (
2005
  return_dict if return_dict is not None else self.config.use_return_dict
@@ -2052,3 +1870,15 @@ class GPT2ForQuestionAnswering(GPT2PreTrainedModel):
2052
  hidden_states=outputs.hidden_states,
2053
  attentions=outputs.attentions,
2054
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  import os
20
  import warnings
21
  from dataclasses import dataclass
22
+ from typing import Callable, Optional, Tuple, Union
23
 
24
  import torch
 
 
25
  from torch import nn
26
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
 
28
+ from transformers.activations import ACT2FN, get_activation
29
+ from transformers.cache_utils import Cache, DynamicCache, EncoderDecoderCache, StaticCache
30
  from transformers.generation import GenerationMixin
31
  from transformers.modeling_attn_mask_utils import (
32
+ AttentionMaskConverter,
33
  _prepare_4d_attention_mask_for_sdpa,
 
34
  )
35
  from transformers.modeling_outputs import (
36
  BaseModelOutputWithPastAndCrossAttentions,
 
39
  SequenceClassifierOutputWithPast,
40
  TokenClassifierOutput,
41
  )
42
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
  from transformers.pytorch_utils import (
44
  Conv1D,
45
  find_pruneable_heads_and_indices,
 
47
  )
48
  from transformers.utils import (
49
  ModelOutput,
 
50
  add_start_docstrings,
51
+ auto_docstring,
 
 
 
52
  logging,
 
53
  )
54
+ from transformers.utils.deprecation import deprecate_kwarg
55
  from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
56
  from .configuration_gpt2 import GPT2Config
57
+ from transformers.models.gpt2.modeling_gpt2 import (
58
+ load_tf_weights_in_gpt2,
59
+ eager_attention_forward,
60
+ )
61
 
62
 
63
  logger = logging.get_logger(__name__)
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
  class GPT2Attention(nn.Module):
67
  def __init__(self, config, is_cross_attention=False, layer_idx=None):
 
129
  self.num_heads = self.num_heads - len(heads)
130
  self.pruned_heads = self.pruned_heads.union(heads)
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def _upcast_and_reordered_attn(
133
  self, query, key, value, attention_mask=None, head_mask=None
134
  ):
 
172
  mask_value = torch.finfo(attn_weights.dtype).min
173
  # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
174
  # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
175
+ mask_value = torch.tensor(
176
+ mask_value, dtype=attn_weights.dtype, device=attn_weights.device
177
  )
178
  attn_weights = torch.where(causal_mask, attn_weights, mask_value)
179
 
 
196
  attn_weights = attn_weights * head_mask
197
 
198
  attn_output = torch.matmul(attn_weights, value)
199
+ attn_output = attn_output.transpose(1, 2)
200
 
201
  return attn_output, attn_weights
202
 
203
+ @deprecate_kwarg(
204
+ "layer_past",
205
+ new_name="past_key_value",
206
+ version="4.53.0",
207
+ raise_if_both_names=True,
208
+ )
 
 
 
 
 
 
 
 
 
 
209
  def forward(
210
  self,
211
  hidden_states: Optional[Tuple[torch.FloatTensor]],
212
+ past_key_value: Optional[Cache] = None,
213
+ cache_position: Optional[torch.LongTensor] = None,
214
  attention_mask: Optional[torch.FloatTensor] = None,
215
  head_mask: Optional[torch.FloatTensor] = None,
216
  encoder_hidden_states: Optional[torch.Tensor] = None,
217
  encoder_attention_mask: Optional[torch.FloatTensor] = None,
 
218
  output_attentions: Optional[bool] = False,
219
+ **kwargs,
220
  ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
221
+ is_cross_attention = encoder_hidden_states is not None
222
+ if is_cross_attention:
223
  if not hasattr(self, "q_attn"):
224
  raise ValueError(
225
  "If class is used as cross attention, the weights `q_attn` have to be defined. "
226
  "Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
227
  )
228
 
229
+ query_states = self.q_attn(hidden_states)
230
+ key_states, value_states = self.c_attn(encoder_hidden_states).split(
231
  self.split_size, dim=2
232
  )
233
  attention_mask = encoder_attention_mask
234
  else:
235
+ query_states, key_states, value_states = self.c_attn(hidden_states).split(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  self.split_size, dim=2
237
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
+ shape_q = (query_states.shape[0],query_states.shape[1], -1, self.head_dim)
240
+ shape_kv = (key_states.shape[0], key_states.shape[1],-1, self.head_dim)
 
241
 
242
+ query_states = query_states.view(shape_q).transpose(1, 2)
243
+ key_states = key_states.view(shape_kv).transpose(1, 2)
244
+ value_states = value_states.view(shape_kv).transpose(1, 2)
245
 
246
+ if past_key_value is not None:
247
+ if isinstance(past_key_value, EncoderDecoderCache):
248
+ if is_cross_attention:
249
+ past_key_value = past_key_value.cross_attention_cache
250
+ else:
251
+ past_key_value = past_key_value.self_attention_cache
252
+ cache_kwargs = {"cache_position": cache_position}
253
+ key_states, value_states = past_key_value.update(
254
+ key_states, value_states, self.layer_idx, cache_kwargs=cache_kwargs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  )
256
 
257
+ is_causal = (
258
+ attention_mask is None
259
+ and query_states.shape[-2] > 1
260
+ and not is_cross_attention
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
+ using_eager = self.config._attn_implementation == "eager"
264
+ attention_interface: Callable = eager_attention_forward
265
+ if self.config._attn_implementation != "eager":
266
+ if self.config._attn_implementation == "sdpa" and (
267
+ output_attentions or head_mask is not None
268
+ ):
269
+ using_eager = True
270
+ logger.warning_once(
271
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
272
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
273
  )
274
+ else:
275
+ # Attention functions are consistent with previous equivalent attention classes, however they do not support some options
276
+ # (e.g. layer scaling, head mask) that eager supports. These implementations are thus equivalent to previous code, but
277
+ # not necessarily to eager (if mentioned options are provided).
278
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
279
+ self.config._attn_implementation
280
+ ]
281
 
282
+ if using_eager and self.reorder_and_upcast_attn:
283
+ attn_output, attn_weights = self._upcast_and_reordered_attn(
284
+ query_states, key_states, value_states, attention_mask, head_mask
285
  )
 
286
  else:
287
+ attn_output, attn_weights = attention_interface(
288
+ self,
289
+ query_states,
290
+ key_states,
291
+ value_states,
292
+ attention_mask,
293
+ head_mask=head_mask,
294
+ dropout=self.attn_dropout.p if self.training else 0.0,
295
+ is_causal=is_causal,
296
+ **kwargs,
297
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
+ attn_output = attn_output.reshape(attn_output.shape[0],attn_output.shape[1], -1).contiguous()
300
  attn_output = self.c_proj(attn_output)
301
  attn_output = self.resid_dropout(attn_output)
302
 
303
+ return attn_output, attn_weights
304
 
305
 
306
  class GPT2MLP(nn.Module):
 
322
  return hidden_states
323
 
324
 
 
 
 
 
 
 
 
325
  class GPT2Block(nn.Module):
326
  def __init__(self, config, layer_idx=None):
327
  super().__init__()
328
  hidden_size = config.hidden_size
329
  inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
 
330
 
331
  self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
332
+ self.attn = GPT2Attention(config=config, layer_idx=layer_idx)
333
  self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
334
 
335
  if config.add_cross_attention:
336
+ self.crossattention = GPT2Attention(
337
  config=config, is_cross_attention=True, layer_idx=layer_idx
338
  )
339
  self.ln_cross_attn = nn.LayerNorm(
 
342
 
343
  self.mlp = GPT2MLP(inner_dim, config)
344
 
345
+ @deprecate_kwarg(
346
+ "layer_past",
347
+ new_name="past_key_value",
348
+ version="4.53.0",
349
+ raise_if_both_names=True,
350
+ )
351
  def forward(
352
  self,
353
  hidden_states: Optional[Tuple[torch.FloatTensor]],
354
+ past_key_value: Optional[Cache] = None,
355
+ cache_position: Optional[torch.LongTensor] = None,
356
  attention_mask: Optional[torch.FloatTensor] = None,
357
  head_mask: Optional[torch.FloatTensor] = None,
358
  encoder_hidden_states: Optional[torch.Tensor] = None,
359
  encoder_attention_mask: Optional[torch.FloatTensor] = None,
360
  use_cache: Optional[bool] = False,
361
  output_attentions: Optional[bool] = False,
362
+ **kwargs,
363
  ) -> Union[
364
  Tuple[torch.Tensor],
365
  Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]],
366
  ]:
367
  residual = hidden_states
368
  hidden_states = self.ln_1(hidden_states)
369
+ attn_output, self_attn_weights = self.attn(
370
  hidden_states,
371
+ past_key_value=past_key_value,
372
+ cache_position=cache_position,
373
  attention_mask=attention_mask,
374
  head_mask=head_mask,
375
  use_cache=use_cache,
376
  output_attentions=output_attentions,
377
+ **kwargs,
378
  )
 
 
379
  # residual connection
380
  hidden_states = attn_output + residual
381
 
 
388
  )
389
  residual = hidden_states
390
  hidden_states = self.ln_cross_attn(hidden_states)
391
+ cross_attn_output, cross_attn_weights = self.crossattention(
392
  hidden_states,
393
+ past_key_value=past_key_value,
394
  attention_mask=attention_mask,
395
  head_mask=head_mask,
396
  encoder_hidden_states=encoder_hidden_states,
397
  encoder_attention_mask=encoder_attention_mask,
398
  output_attentions=output_attentions,
399
  )
 
400
  # residual connection
401
+ hidden_states = residual + cross_attn_output
 
 
 
402
 
403
  residual = hidden_states
404
  hidden_states = self.ln_2(hidden_states)
 
406
  # residual connection
407
  hidden_states = residual + feed_forward_hidden_states
408
 
409
+ outputs = (hidden_states,)
410
+ if output_attentions:
411
+ outputs += (self_attn_weights,)
412
+ if encoder_hidden_states is not None:
413
+ outputs += (cross_attn_weights,)
414
 
415
+ return outputs
416
 
417
 
418
+ # Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->GPT2
419
+ class GPT2SequenceSummary(nn.Module):
420
+ r"""
421
+ Compute a single vector summary of a sequence hidden states.
422
+
423
+ Args:
424
+ config ([`GPT2Config`]):
425
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
426
+ config class of your model for the default values it uses):
427
+
428
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
429
+
430
+ - `"last"` -- Take the last token hidden state (like XLNet)
431
+ - `"first"` -- Take the first token hidden state (like Bert)
432
+ - `"mean"` -- Take the mean of all tokens hidden states
433
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
434
+ - `"attn"` -- Not implemented now, use multi-head attention
435
+
436
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
437
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
438
+ (otherwise to `config.hidden_size`).
439
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
440
+ another string or `None` will add no activation.
441
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
442
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
443
  """
444
 
445
+ def __init__(self, config: GPT2Config):
446
+ super().__init__()
447
+
448
+ self.summary_type = getattr(config, "summary_type", "last")
449
+ if self.summary_type == "attn":
450
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
451
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
452
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
453
+ raise NotImplementedError
454
+
455
+ self.summary = nn.Identity()
456
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
457
+ if (
458
+ hasattr(config, "summary_proj_to_labels")
459
+ and config.summary_proj_to_labels
460
+ and config.num_labels > 0
461
+ ):
462
+ num_classes = config.num_labels
463
+ else:
464
+ num_classes = config.hidden_size
465
+ self.summary = nn.Linear(config.hidden_size, num_classes)
466
+
467
+ activation_string = getattr(config, "summary_activation", None)
468
+ self.activation: Callable = (
469
+ get_activation(activation_string) if activation_string else nn.Identity()
470
+ )
471
+
472
+ self.first_dropout = nn.Identity()
473
+ if (
474
+ hasattr(config, "summary_first_dropout")
475
+ and config.summary_first_dropout > 0
476
+ ):
477
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
478
+
479
+ self.last_dropout = nn.Identity()
480
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
481
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
482
+
483
+ def forward(
484
+ self,
485
+ hidden_states: torch.FloatTensor,
486
+ cls_index: Optional[torch.LongTensor] = None,
487
+ ) -> torch.FloatTensor:
488
+ """
489
+ Compute a single vector summary of a sequence hidden states.
490
+
491
+ Args:
492
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
493
+ The hidden states of the last layer.
494
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
495
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
496
+
497
+ Returns:
498
+ `torch.FloatTensor`: The summary of the sequence hidden states.
499
+ """
500
+ if self.summary_type == "last":
501
+ output = hidden_states[:, -1]
502
+ elif self.summary_type == "first":
503
+ output = hidden_states[:, 0]
504
+ elif self.summary_type == "mean":
505
+ output = hidden_states.mean(dim=1)
506
+ elif self.summary_type == "cls_index":
507
+ if cls_index is None:
508
+ cls_index = torch.full_like(
509
+ hidden_states[..., :1, :],
510
+ hidden_states.shape[-2] - 1,
511
+ dtype=torch.long,
512
+ )
513
+ else:
514
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
515
+ cls_index = cls_index.expand(
516
+ (-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),)
517
+ )
518
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
519
+ output = hidden_states.gather(-2, cls_index).squeeze(
520
+ -2
521
+ ) # shape (bsz, XX, hidden_size)
522
+ elif self.summary_type == "attn":
523
+ raise NotImplementedError
524
+
525
+ output = self.first_dropout(output)
526
+ output = self.summary(output)
527
+ output = self.activation(output)
528
+ output = self.last_dropout(output)
529
+
530
+ return output
531
+
532
+
533
+ @auto_docstring
534
+ class GPT2PreTrainedModel(PreTrainedModel):
535
  config_class = GPT2Config
536
  load_tf_weights = load_tf_weights_in_gpt2
537
  base_model_prefix = "transformer"
 
541
  _skip_keys_device_placement = "past_key_values"
542
  _supports_flash_attn_2 = True
543
  _supports_sdpa = True
544
+ _supports_attention_backend = True
545
+ _supports_cache_class = True
546
+ _supports_static_cache = True
547
 
548
  def __init__(self, *inputs, **kwargs):
549
  super().__init__(*inputs, **kwargs)
 
617
 
618
  loss: Optional[torch.FloatTensor] = None
619
  mc_loss: Optional[torch.FloatTensor] = None
620
+ logits: Optional[torch.FloatTensor] = None
621
+ mc_logits: Optional[torch.FloatTensor] = None
622
  past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
623
  hidden_states: Optional[Tuple[torch.FloatTensor]] = None
624
  attentions: Optional[Tuple[torch.FloatTensor]] = None
625
 
626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
  PARALLELIZE_DOCSTRING = r"""
628
  This is an experimental feature and is a subject to change at a moment's notice.
629
 
 
676
  """
677
 
678
 
679
+ @auto_docstring
 
 
 
680
  class GPT2Model(GPT2PreTrainedModel):
681
  _supports_param_buffer_assignment = False
682
 
 
766
  for layer, heads in heads_to_prune.items():
767
  self.h[layer].attn.prune_heads(heads)
768
 
769
+ @auto_docstring
 
 
 
 
 
770
  def forward(
771
  self,
772
  input_ids: Optional[torch.LongTensor] = None,
773
+ past_key_values: Optional[Union[Tuple[Tuple[torch.Tensor]], Cache]] = None,
774
+ cache_position: Optional[torch.LongTensor] = None,
775
  attention_mask: Optional[torch.FloatTensor] = None,
776
  token_type_ids: Optional[torch.LongTensor] = None,
777
  position_ids: Optional[torch.LongTensor] = None,
 
783
  output_attentions: Optional[bool] = None,
784
  output_hidden_states: Optional[bool] = None,
785
  return_dict: Optional[bool] = None,
786
+ **kwargs,
787
  ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
788
+ r"""
789
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
790
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
791
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
792
+ sequence tokens in the vocabulary.
793
+
794
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
795
+ `input_ids`.
796
+
797
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
798
+ [`PreTrainedTokenizer.__call__`] for details.
799
+
800
+ [What are input IDs?](../glossary#input-ids)
801
+ """
802
  output_attentions = (
803
  output_attentions
804
  if output_attentions is not None
 
834
  if token_type_ids is not None:
835
  token_type_ids = token_type_ids.view(-1, input_shape[-1])
836
 
837
+ if self.gradient_checkpointing and self.training:
838
+ if use_cache:
839
+ logger.warning_once(
840
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
841
+ )
842
+ use_cache = False
843
+
844
+ # based on pattern from src/transformers/models/whisper/modeling_whisper.py::WhisperDecoder
845
+ return_legacy_cache = False
846
+ if use_cache:
847
+ if past_key_values is None:
848
+ return_legacy_cache = True
849
+ past_key_values = DynamicCache()
850
+ elif not isinstance(past_key_values, Cache):
851
+ return_legacy_cache = True
852
+ logger.warning_once(
853
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.53.0. "
854
+ "You should pass an instance of `Cache` instead, e.g. "
855
+ "`past_key_values=DynamicCache.from_legacy_cache(past_key_values)`."
856
+ )
857
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
858
+
859
+ if self.config.add_cross_attention and not isinstance(
860
+ past_key_values, EncoderDecoderCache
861
+ ):
862
+ past_key_values = EncoderDecoderCache(past_key_values, DynamicCache())
863
 
864
  if inputs_embeds is None:
865
  inputs_embeds = self.wte(input_ids)
866
+
867
+ if cache_position is None:
868
+ past_seen_tokens = (
869
+ past_key_values.get_seq_length() if past_key_values is not None else 0
870
+ )
871
+ cache_position = torch.arange(
872
+ past_seen_tokens,
873
+ past_seen_tokens + inputs_embeds.shape[1],
874
+ device=inputs_embeds.device,
875
+ )
876
+ if position_ids is None:
877
+ position_ids = cache_position.unsqueeze(0)
878
+
879
  position_embeds = self.wpe(position_ids)
880
+ hidden_states = inputs_embeds + position_embeds.to(inputs_embeds.device)
881
 
882
  # Attention mask.
883
+ # ._update_causal_mask() and ._prepare_4d_causal_attention_mask_with_cache_position() copied from LlamaModel
884
+ if attention_mask is not None and attention_mask.ndim < 4:
885
+ attention_mask = attention_mask.view(batch_size, -1)
886
+ causal_mask = self._update_causal_mask(
887
+ attention_mask,
888
+ inputs_embeds,
889
+ cache_position,
890
+ past_key_values,
891
+ output_attentions,
892
+ )
893
+
894
+ # If a 2D or 3D attention mask is provided for the cross-attention
895
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
896
  _use_sdpa = (
897
  self._attn_implementation == "sdpa"
898
  and output_attentions is False
899
  and head_mask is None
900
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
901
  if self.config.add_cross_attention and encoder_hidden_states is not None:
902
  encoder_batch_size, encoder_sequence_length, _ = (
903
  encoder_hidden_states.size()
 
932
 
933
  output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
934
 
 
 
 
 
 
 
 
 
935
  all_self_attentions = () if output_attentions else None
936
  all_cross_attentions = (
937
  () if output_attentions and self.config.add_cross_attention else None
938
  )
939
  all_hidden_states = () if output_hidden_states else None
940
+ for i, block in enumerate(self.h):
 
941
  # Model parallel
942
  if self.model_parallel:
943
  torch.cuda.set_device(hidden_states.device)
 
 
 
 
 
944
  # Ensure that attention_mask is always on the same device as hidden_states
945
  if attention_mask is not None:
946
  attention_mask = attention_mask.to(hidden_states.device)
 
953
  outputs = self._gradient_checkpointing_func(
954
  block.__call__,
955
  hidden_states,
956
+ past_key_values,
957
+ cache_position,
958
+ causal_mask,
959
  head_mask[i],
960
  encoder_hidden_states,
961
  encoder_attention_mask,
 
965
  else:
966
  outputs = block(
967
  hidden_states,
968
+ past_key_value=past_key_values,
969
+ cache_position=cache_position,
970
+ attention_mask=causal_mask,
971
  head_mask=head_mask[i],
972
  encoder_hidden_states=encoder_hidden_states,
973
  encoder_attention_mask=encoder_attention_mask,
974
  use_cache=use_cache,
975
  output_attentions=output_attentions,
976
+ **kwargs,
977
  )
978
 
979
  hidden_states = outputs[0]
 
 
980
 
981
  if output_attentions:
982
+ all_self_attentions = all_self_attentions + (outputs[1],)
 
 
983
  if self.config.add_cross_attention:
984
+ all_cross_attentions = all_cross_attentions + (outputs[2],)
 
 
985
 
986
  # Model Parallel: If it's the last layer for that device, put things on the next device
987
  if self.model_parallel:
 
996
  if output_hidden_states:
997
  all_hidden_states = all_hidden_states + (hidden_states,)
998
 
999
+ past_key_values = past_key_values if use_cache else None
1000
+ if return_legacy_cache:
1001
+ past_key_values = (
1002
+ past_key_values.self_attention_cache.to_legacy_cache()
1003
+ if self.config.add_cross_attention
1004
+ else past_key_values.to_legacy_cache()
1005
+ )
1006
  if not return_dict:
1007
  return tuple(
1008
  v
1009
  for v in [
1010
  hidden_states,
1011
+ past_key_values,
1012
  all_hidden_states,
1013
  all_self_attentions,
1014
  all_cross_attentions,
 
1018
 
1019
  return BaseModelOutputWithPastAndCrossAttentions(
1020
  last_hidden_state=hidden_states,
1021
+ past_key_values=past_key_values,
1022
  hidden_states=all_hidden_states,
1023
  attentions=all_self_attentions,
1024
  cross_attentions=all_cross_attentions,
1025
  )
1026
 
1027
+ def _update_causal_mask(
1028
+ self,
1029
+ attention_mask: torch.Tensor,
1030
+ input_tensor: torch.Tensor,
1031
+ cache_position: torch.Tensor,
1032
+ past_key_values: Cache,
1033
+ output_attentions: bool,
1034
+ ):
1035
+ if self.config._attn_implementation == "flash_attention_2":
1036
+ if attention_mask is not None and 0.0 in attention_mask:
1037
+ return attention_mask
1038
+ return None
1039
+
1040
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1041
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1042
+ # to infer the attention mask.
1043
+ past_seen_tokens = (
1044
+ past_key_values.get_seq_length() if past_key_values is not None else 0
1045
+ )
1046
+ using_static_cache = isinstance(past_key_values, StaticCache)
1047
 
1048
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1049
+ if (
1050
+ self.config._attn_implementation == "sdpa"
1051
+ and not using_static_cache
1052
+ and not output_attentions
1053
+ ):
1054
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1055
+ attention_mask,
1056
+ inputs_embeds=input_tensor,
1057
+ past_key_values_length=past_seen_tokens,
1058
+ is_training=self.training,
1059
+ ):
1060
+ return None
1061
+
1062
+ dtype = input_tensor.dtype
1063
+ sequence_length = input_tensor.shape[1]
1064
+ if using_static_cache:
1065
+ target_length = past_key_values.get_max_cache_shape()
1066
+ else:
1067
+ target_length = (
1068
+ attention_mask.shape[-1]
1069
+ if isinstance(attention_mask, torch.Tensor)
1070
+ else past_seen_tokens + sequence_length + 1
1071
+ )
1072
+
1073
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1074
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1075
+ attention_mask,
1076
+ sequence_length=sequence_length,
1077
+ target_length=target_length,
1078
+ dtype=dtype,
1079
+ cache_position=cache_position,
1080
+ batch_size=input_tensor.shape[0],
1081
+ )
1082
+
1083
+ if (
1084
+ self.config._attn_implementation == "sdpa"
1085
+ and attention_mask is not None
1086
+ and attention_mask.device.type == "cuda"
1087
+ and not output_attentions
1088
+ ):
1089
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1090
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1091
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1092
+ min_dtype = torch.finfo(dtype).min
1093
+ causal_mask = AttentionMaskConverter._unmask_unattended(
1094
+ causal_mask, min_dtype
1095
+ )
1096
+
1097
+ return causal_mask
1098
+
1099
+ @staticmethod
1100
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1101
+ attention_mask: torch.Tensor,
1102
+ sequence_length: int,
1103
+ target_length: int,
1104
+ dtype: torch.dtype,
1105
+ cache_position: torch.Tensor,
1106
+ batch_size: int,
1107
+ **kwargs,
1108
+ ):
1109
+ """
1110
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1111
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1112
+
1113
+ Args:
1114
+ attention_mask (`torch.Tensor`):
1115
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1116
+ `(batch_size, 1, query_length, key_value_length)`.
1117
+ sequence_length (`int`):
1118
+ The sequence length being processed.
1119
+ target_length (`int`):
1120
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1121
+ to account for the 0 padding, the part of the cache that is not filled yet.
1122
+ dtype (`torch.dtype`):
1123
+ The dtype to use for the 4D attention mask.
1124
+ cache_position (`torch.Tensor`):
1125
+ Indices depicting the position of the input sequence tokens in the sequence.
1126
+ batch_size (`torch.Tensor`):
1127
+ Batch size.
1128
+ """
1129
+ if attention_mask is not None and attention_mask.dim() == 4:
1130
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1131
+ causal_mask = attention_mask
1132
+ else:
1133
+ min_dtype = torch.finfo(dtype).min
1134
+ causal_mask = torch.full(
1135
+ (sequence_length, target_length),
1136
+ fill_value=min_dtype,
1137
+ dtype=dtype,
1138
+ device=cache_position.device,
1139
+ )
1140
+ if sequence_length != 1:
1141
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1142
+ causal_mask *= torch.arange(
1143
+ target_length, device=cache_position.device
1144
+ ) > cache_position.reshape(-1, 1)
1145
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1146
+ if attention_mask is not None:
1147
+ causal_mask = (
1148
+ causal_mask.clone()
1149
+ ) # copy to contiguous memory for in-place edit
1150
+ mask_length = attention_mask.shape[-1]
1151
+ padding_mask = (
1152
+ causal_mask[:, :, :, :mask_length]
1153
+ + attention_mask[:, None, None, :]
1154
+ )
1155
+ padding_mask = padding_mask == 0
1156
+ causal_mask[:, :, :, :mask_length] = causal_mask[
1157
+ :, :, :, :mask_length
1158
+ ].masked_fill(padding_mask, min_dtype)
1159
+
1160
+ return causal_mask
1161
+
1162
+
1163
+ @auto_docstring(
1164
+ custom_intro="""
1165
  The GPT2 Model transformer with a language modeling head on top (linear layer with weights tied to the input
1166
  embeddings).
1167
+ """
 
1168
  )
1169
  class GPT2LMHeadModel(GPT2PreTrainedModel, GenerationMixin):
1170
  _tied_weights_keys = ["lm_head.weight"]
 
1218
  def set_output_embeddings(self, new_embeddings):
1219
  self.lm_head = new_embeddings
1220
 
1221
+ @auto_docstring
 
 
 
 
 
1222
  def forward(
1223
  self,
1224
  input_ids: Optional[torch.LongTensor] = None,
1225
  past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1226
+ cache_position: Optional[torch.LongTensor] = None,
1227
  attention_mask: Optional[torch.FloatTensor] = None,
1228
  token_type_ids: Optional[torch.LongTensor] = None,
1229
  position_ids: Optional[torch.LongTensor] = None,
 
1236
  output_attentions: Optional[bool] = None,
1237
  output_hidden_states: Optional[bool] = None,
1238
  return_dict: Optional[bool] = None,
1239
+ **kwargs,
1240
  ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1241
  r"""
1242
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
1243
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
1244
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
1245
+ sequence tokens in the vocabulary.
1246
+
1247
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
1248
+ `input_ids`.
1249
+
1250
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1251
+ [`PreTrainedTokenizer.__call__`] for details.
1252
+
1253
+ [What are input IDs?](../glossary#input-ids)
1254
+ labels (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
1255
  Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1256
  `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1257
  are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
 
1264
  input_ids,
1265
  past_key_values=past_key_values,
1266
  attention_mask=attention_mask,
1267
+ cache_position=cache_position,
1268
  token_type_ids=token_type_ids,
1269
  position_ids=position_ids,
1270
  head_mask=head_mask,
 
1287
 
1288
  loss = None
1289
  if labels is not None:
 
 
 
 
 
1290
  # Flatten the tokens
1291
+ loss = self.loss_function(
1292
+ lm_logits,
1293
+ labels,
1294
+ vocab_size=self.config.vocab_size,
1295
+ **kwargs,
1296
  )
1297
 
1298
  if not return_dict:
 
1308
  cross_attentions=transformer_outputs.cross_attentions,
1309
  )
1310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1311
 
1312
+ @auto_docstring(
1313
+ custom_intro="""
1314
+ The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1315
+ RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1316
+ input embeddings, the classification head takes as input the input of a specified classification token index in the
1317
+ input sequence).
1318
  """
 
 
 
 
 
 
1319
  )
1320
  class GPT2DoubleHeadsModel(GPT2PreTrainedModel, GenerationMixin):
1321
  _tied_weights_keys = ["lm_head.weight"]
 
1325
  config.num_labels = 1
1326
  self.transformer = GPT2Model(config)
1327
  self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1328
+ self.multiple_choice_head = GPT2SequenceSummary(config)
1329
 
1330
  # Model parallel
1331
  self.model_parallel = False
 
1375
  def set_output_embeddings(self, new_embeddings):
1376
  self.lm_head = new_embeddings
1377
 
1378
+ @auto_docstring
 
 
 
1379
  def forward(
1380
  self,
1381
  input_ids: Optional[torch.LongTensor] = None,
1382
  past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1383
+ cache_position: Optional[torch.LongTensor] = None,
1384
  attention_mask: Optional[torch.FloatTensor] = None,
1385
  token_type_ids: Optional[torch.LongTensor] = None,
1386
  position_ids: Optional[torch.LongTensor] = None,
 
1396
  **kwargs,
1397
  ) -> Union[Tuple, GPT2DoubleHeadsModelOutput]:
1398
  r"""
1399
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
1400
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
1401
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
1402
+ sequence tokens in the vocabulary.
1403
+
1404
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
1405
+ `input_ids`.
1406
+
1407
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1408
+ [`PreTrainedTokenizer.__call__`] for details.
1409
+
1410
+ [What are input IDs?](../glossary#input-ids)
1411
  mc_token_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`, *optional*, default to index of the last token of the input):
1412
  Index of the classification token in each input sequence. Selected in the range `[0, input_ids.size(-1) -
1413
  1]`.
1414
+ labels (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
1415
  Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1416
  `labels = input_ids`. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to
1417
  `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size - 1]`
 
1419
  Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1420
  where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
1421
 
 
 
1422
  Example:
1423
 
1424
  ```python
 
1451
  transformer_outputs = self.transformer(
1452
  input_ids,
1453
  past_key_values=past_key_values,
1454
+ cache_position=cache_position,
1455
  attention_mask=attention_mask,
1456
  token_type_ids=token_type_ids,
1457
  position_ids=position_ids,
 
1523
  )
1524
 
1525
 
1526
+ @auto_docstring(
1527
+ custom_intro="""
1528
  The GPT2 Model transformer with a sequence classification head on top (linear layer).
1529
 
1530
  [`GPT2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
 
1535
  no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1536
  padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1537
  each row of the batch).
1538
+ """
 
1539
  )
1540
  class GPT2ForSequenceClassification(GPT2PreTrainedModel):
1541
  def __init__(self, config):
 
1551
  # Initialize weights and apply final processing
1552
  self.post_init()
1553
 
1554
+ @auto_docstring
 
 
 
 
 
1555
  def forward(
1556
  self,
1557
  input_ids: Optional[torch.LongTensor] = None,
 
1568
  return_dict: Optional[bool] = None,
1569
  ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1570
  r"""
1571
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
1572
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
1573
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
1574
+ sequence tokens in the vocabulary.
1575
+
1576
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
1577
+ `input_ids`.
1578
+
1579
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1580
+ [`PreTrainedTokenizer.__call__`] for details.
1581
+
1582
+ [What are input IDs?](../glossary#input-ids)
1583
  labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1584
  Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1585
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
 
1610
  else:
1611
  batch_size, sequence_length = inputs_embeds.shape[:2]
1612
 
1613
+ if self.config.pad_token_id is None and batch_size != 1:
1614
+ raise ValueError(
1615
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1616
+ )
1617
  if self.config.pad_token_id is None:
1618
+ last_non_pad_token = -1
1619
+ elif input_ids is not None:
1620
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1621
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(
1622
+ logits.device, torch.int32
1623
+ )
1624
+ token_indices = torch.arange(
1625
+ input_ids.shape[-1], device=logits.device, dtype=torch.int32
1626
+ )
1627
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1628
  else:
1629
+ last_non_pad_token = -1
1630
+ logger.warning_once(
1631
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1632
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1633
+ )
 
 
 
 
 
 
 
 
1634
 
1635
  pooled_logits = logits[
1636
+ torch.arange(batch_size, device=logits.device), last_non_pad_token
1637
  ]
1638
 
1639
  loss = None
 
1675
  )
1676
 
1677
 
1678
+ @auto_docstring
 
 
 
 
 
 
1679
  class GPT2ForTokenClassification(GPT2PreTrainedModel):
1680
  def __init__(self, config):
1681
  super().__init__(config)
 
1701
  # Initialize weights and apply final processing
1702
  self.post_init()
1703
 
1704
+ @auto_docstring
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1705
  def forward(
1706
  self,
1707
  input_ids: Optional[torch.LongTensor] = None,
 
1718
  return_dict: Optional[bool] = None,
1719
  ) -> Union[Tuple, TokenClassifierOutput]:
1720
  r"""
1721
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
1722
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
1723
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
1724
+ sequence tokens in the vocabulary.
1725
+
1726
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
1727
+ `input_ids`.
1728
+
1729
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1730
+ [`PreTrainedTokenizer.__call__`] for details.
1731
+
1732
+ [What are input IDs?](../glossary#input-ids)
1733
  labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1734
  Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1735
  config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
 
1775
  )
1776
 
1777
 
1778
+ @auto_docstring
 
 
 
 
 
 
1779
  class GPT2ForQuestionAnswering(GPT2PreTrainedModel):
1780
  def __init__(self, config):
1781
  super().__init__(config)
 
1790
  # Initialize weights and apply final processing
1791
  self.post_init()
1792
 
1793
+ @auto_docstring
 
 
 
 
 
 
 
 
1794
  def forward(
1795
  self,
1796
  input_ids: Optional[torch.LongTensor] = None,
 
1806
  return_dict: Optional[bool] = None,
1807
  ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1808
  r"""
1809
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
1810
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
1811
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
1812
+ sequence tokens in the vocabulary.
1813
+
1814
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
1815
+ `input_ids`.
1816
+
1817
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1818
+ [`PreTrainedTokenizer.__call__`] for details.
1819
+
1820
+ [What are input IDs?](../glossary#input-ids)
1821
  """
1822
  return_dict = (
1823
  return_dict if return_dict is not None else self.config.use_return_dict
 
1870
  hidden_states=outputs.hidden_states,
1871
  attentions=outputs.attentions,
1872
  )
1873
+
1874
+
1875
+ __all__ = [
1876
+ "GPT2DoubleHeadsModel",
1877
+ "GPT2ForQuestionAnswering",
1878
+ "GPT2ForSequenceClassification",
1879
+ "GPT2ForTokenClassification",
1880
+ "GPT2LMHeadModel",
1881
+ "GPT2Model",
1882
+ "GPT2PreTrainedModel",
1883
+ "load_tf_weights_in_gpt2",
1884
+ ]