robinzixuan commited on
Commit
b8c7545
1 Parent(s): d25a1db

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_opt.py +145 -0
  2. modeling_opt.py +1721 -0
configuration_opt.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Metaseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """OPT model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class OPTConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`OPTModel`]. It is used to instantiate a OPT model
27
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the OPT
29
+ [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 50272):
37
+ Vocabulary size of the OPT model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`OPTModel`]
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of decoder layers.
43
+ ffn_dim (`int`, *optional*, defaults to 3072):
44
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 12):
46
+ Number of attention heads for each attention layer in the Transformer decoder.
47
+ activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
49
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
50
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
51
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
52
+ just in case (e.g., 512 or 1024 or 2048).
53
+ do_layer_norm_before (`bool`, *optional*, defaults to `True`):
54
+ Whether to perform layer normalization before the attention block.
55
+ word_embed_proj_dim (`int`, *optional*):
56
+ `word_embed_proj_dim` can be set to down-project word embeddings, *e.g.* `opt-350m`. Defaults to
57
+ `hidden_size`.
58
+ dropout (`float`, *optional*, defaults to 0.1):
59
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
60
+ attention_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the attention probabilities.
62
+ layerdrop (`float`, *optional*, defaults to 0.0):
63
+ The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more
64
+ details.
65
+ init_std (`float`, *optional*, defaults to 0.02):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models).
69
+ enable_bias (`bool`, *optional*, defaults to `True`):
70
+ Whether or not if the linear layers in the attention blocks should use the bias term.
71
+ layer_norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
72
+ Whether or not if the layer norms should have learnable parameters.
73
+
74
+ Example:
75
+
76
+ ```python
77
+ >>> from transformers import OPTConfig, OPTModel
78
+
79
+ >>> # Initializing a OPT facebook/opt-large style configuration
80
+ >>> configuration = OPTConfig()
81
+
82
+ >>> # Initializing a model (with random weights) from the facebook/opt-large style configuration
83
+ >>> model = OPTModel(configuration)
84
+
85
+ >>> # Accessing the model configuration
86
+ >>> configuration = model.config
87
+ ```"""
88
+
89
+ model_type = "opt"
90
+ keys_to_ignore_at_inference = ["past_key_values"]
91
+
92
+ def __init__(
93
+ self,
94
+ vocab_size=50272,
95
+ hidden_size=768,
96
+ num_hidden_layers=12,
97
+ ffn_dim=3072,
98
+ max_position_embeddings=2048,
99
+ do_layer_norm_before=True,
100
+ _remove_final_layer_norm=False,
101
+ word_embed_proj_dim=None,
102
+ dropout=0.1,
103
+ attention_dropout=0.0,
104
+ num_attention_heads=12,
105
+ activation_function="relu",
106
+ layerdrop=0.0,
107
+ init_std=0.02,
108
+ use_cache=True,
109
+ pad_token_id=1,
110
+ bos_token_id=2,
111
+ eos_token_id=2,
112
+ enable_bias=True,
113
+ layer_norm_elementwise_affine=True,
114
+ attn_implementation='eager',
115
+ **kwargs,
116
+ ):
117
+ super().__init__(
118
+ pad_token_id=pad_token_id,
119
+ bos_token_id=bos_token_id,
120
+ eos_token_id=eos_token_id,
121
+ **kwargs,
122
+ )
123
+ self.vocab_size = vocab_size
124
+ self.max_position_embeddings = max_position_embeddings
125
+ self.num_attention_heads = num_attention_heads
126
+ self.word_embed_proj_dim = word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size
127
+ self.ffn_dim = ffn_dim
128
+ self.hidden_size = hidden_size
129
+ self.num_hidden_layers = num_hidden_layers
130
+ self.dropout = dropout
131
+ self.attention_dropout = attention_dropout
132
+ self.activation_function = activation_function
133
+ self.init_std = init_std
134
+ self.layerdrop = layerdrop
135
+ self.use_cache = use_cache
136
+ self.do_layer_norm_before = do_layer_norm_before
137
+ # We keep these variables at `True` for backward compatibility.
138
+ self.enable_bias = enable_bias
139
+ self.layer_norm_elementwise_affine = layer_norm_elementwise_affine
140
+
141
+ # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility
142
+ # with checkpoints that have been fine-tuned before transformers v4.20.1
143
+ # see https://github.com/facebookresearch/metaseq/pull/164
144
+ self._remove_final_layer_norm = _remove_final_layer_norm
145
+ self.attn_implementation = attn_implementation
modeling_opt.py ADDED
@@ -0,0 +1,1721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch OPT model."""
16
+
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
27
+ from ...modeling_outputs import (
28
+ BaseModelOutputWithPast,
29
+ CausalLMOutputWithPast,
30
+ QuestionAnsweringModelOutput,
31
+ SequenceClassifierOutputWithPast,
32
+ )
33
+ from ...modeling_utils import PreTrainedModel
34
+ from ...utils import (
35
+ add_code_sample_docstrings,
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from .configuration_opt import OPTConfig
44
+
45
+
46
+ if is_flash_attn_2_available():
47
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
48
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CHECKPOINT_FOR_DOC = "facebook/opt-350m"
54
+ _CONFIG_FOR_DOC = "OPTConfig"
55
+
56
+ # Base model docstring
57
+ _EXPECTED_OUTPUT_SHAPE = [1, 8, 1024]
58
+
59
+ # SequenceClassification docstring
60
+ _CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc"
61
+ _SEQ_CLASS_EXPECTED_LOSS = 1.71
62
+ _SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'"
63
+
64
+
65
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
66
+ def _get_unpad_data(attention_mask):
67
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
68
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
69
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
70
+ cu_seqlens = F.pad(torch.cumsum(
71
+ seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
72
+ return (
73
+ indices,
74
+ cu_seqlens,
75
+ max_seqlen_in_batch,
76
+ )
77
+
78
+
79
+ class OPTLearnedPositionalEmbedding(nn.Embedding):
80
+ """
81
+ This module learns positional embeddings up to a fixed maximum size.
82
+ """
83
+
84
+ def __init__(self, num_embeddings: int, embedding_dim: int):
85
+ # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2
86
+ # and adjust num_embeddings appropriately. Other models don't have this hack
87
+ self.offset = 2
88
+ super().__init__(num_embeddings + self.offset, embedding_dim)
89
+
90
+ def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0):
91
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
92
+ attention_mask = attention_mask.long()
93
+
94
+ # create positions depending on attention_mask
95
+ positions = (torch.cumsum(attention_mask, dim=1).type_as(
96
+ attention_mask) * attention_mask).long() - 1
97
+
98
+ # cut positions if `past_key_values_length` is > 0
99
+ positions = positions[:, past_key_values_length:]
100
+
101
+ return super().forward(positions + self.offset)
102
+
103
+
104
+ def softmax_n_shifted_zeros(input: torch.Tensor, n: int, dim=-1) -> torch.Tensor:
105
+ """
106
+ $\text(softmax)_n(x_i) = exp(x_i) / (n + \sum_j exp(x_j))$
107
+
108
+ Note: softmax_n, with fixed input, is _not_ shift-symmetric when n != 0
109
+ """
110
+ # compute the maxes along the last dimension
111
+ input_maxes = input.max(dim=dim, keepdim=True).values
112
+ # shift the input to prevent overflow (and underflow in the denominator)
113
+ shifted_inputs = torch.subtract(input, input_maxes)
114
+ # compute the numerator and softmax_0 denominator using the shifted input
115
+ numerator = torch.exp(shifted_inputs)
116
+ original_denominator = numerator.sum(dim=dim, keepdim=True)
117
+ # we need to shift the zeros in the same way we shifted the inputs
118
+ shifted_zeros = torch.multiply(input_maxes, -1)
119
+ # and then add this contribution to the denominator
120
+ denominator = torch.add(original_denominator,
121
+ torch.multiply(torch.exp(shifted_zeros), n))
122
+ return torch.divide(numerator, denominator)
123
+
124
+
125
+ def softmax_1(input: torch.Tensor, dim=-1, dtype=torch.float32) -> torch.Tensor:
126
+ """
127
+ $\text(softmax)_n(x_i) = exp(x_i) / (1 + \sum_j exp(x_j))$
128
+ """
129
+ return softmax_n_shifted_zeros(input, 1, dim=dim)
130
+
131
+
132
+ class OPTAttention(nn.Module):
133
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
134
+
135
+ def __init__(
136
+ self,
137
+ config: OPTConfig,
138
+ is_decoder: bool = False,
139
+ **kwargs,
140
+ ):
141
+ super().__init__()
142
+ self.config = config
143
+ self.embed_dim = config.hidden_size
144
+ self.num_heads = config.num_attention_heads
145
+ self.dropout = config.attention_dropout
146
+ self.enable_bias = config.enable_bias
147
+
148
+ self.head_dim = self.embed_dim // self.num_heads
149
+ self.is_causal = True
150
+
151
+ if (self.head_dim * self.num_heads) != self.embed_dim:
152
+ raise ValueError(
153
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {
154
+ self.embed_dim}"
155
+ f" and `num_heads`: {self.num_heads})."
156
+ )
157
+ self.scaling = self.head_dim**-0.5
158
+ self.is_decoder = is_decoder
159
+
160
+ self.k_proj = nn.Linear(
161
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
162
+ self.v_proj = nn.Linear(
163
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
164
+ self.q_proj = nn.Linear(
165
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
166
+ self.out_proj = nn.Linear(
167
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
168
+
169
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
170
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
171
+
172
+ def forward(
173
+ self,
174
+ hidden_states: torch.Tensor,
175
+ key_value_states: Optional[torch.Tensor] = None,
176
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
177
+ attention_mask: Optional[torch.Tensor] = None,
178
+ layer_head_mask: Optional[torch.Tensor] = None,
179
+ output_attentions: bool = False,
180
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
181
+ """Input shape: Batch x Time x Channel"""
182
+
183
+ # if key_value_states are provided this layer is used as a cross-attention layer
184
+ # for the decoder
185
+ is_cross_attention = key_value_states is not None
186
+
187
+ bsz, tgt_len, _ = hidden_states.size()
188
+
189
+ # get query proj
190
+ query_states = self.q_proj(hidden_states) * self.scaling
191
+ # get key, value proj
192
+ if is_cross_attention and past_key_value is not None:
193
+ # reuse k,v, cross_attentions
194
+ key_states = past_key_value[0]
195
+ value_states = past_key_value[1]
196
+ elif is_cross_attention:
197
+ # cross_attentions
198
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
199
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
200
+ elif past_key_value is not None:
201
+ # reuse k, v, self_attention
202
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
203
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
204
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
205
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
206
+ else:
207
+ # self_attention
208
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
209
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
210
+
211
+ if self.is_decoder:
212
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
213
+ # Further calls to cross_attention layer can then reuse all cross-attention
214
+ # key/value_states (first "if" case)
215
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
216
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
217
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
218
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
219
+ past_key_value = (key_states, value_states)
220
+
221
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
222
+ query_states = self._shape(
223
+ query_states, tgt_len, bsz).view(*proj_shape)
224
+ key_states = key_states.view(*proj_shape)
225
+ value_states = value_states.view(*proj_shape)
226
+
227
+ src_len = key_states.size(1)
228
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
229
+
230
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
231
+ raise ValueError(
232
+ f"Attention weights should be of size {
233
+ (bsz * self.num_heads, tgt_len, src_len)}, but is"
234
+ f" {attn_weights.size()}"
235
+ )
236
+
237
+ if attention_mask is not None:
238
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
239
+ raise ValueError(
240
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {
241
+ attention_mask.size()}"
242
+ )
243
+ attn_weights = attn_weights.view(
244
+ bsz, self.num_heads, tgt_len, src_len) + attention_mask
245
+ attn_weights = torch.max(
246
+ attn_weights, torch.tensor(torch.finfo(
247
+ attn_weights.dtype).min, device=attn_weights.device)
248
+ )
249
+ attn_weights = attn_weights.view(
250
+ bsz * self.num_heads, tgt_len, src_len)
251
+
252
+ # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
253
+ if attn_weights.dtype == torch.float16:
254
+ attn_weights = nn.functional.softmax(
255
+ attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
256
+ else:
257
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
258
+
259
+ if layer_head_mask is not None:
260
+ if layer_head_mask.size() != (self.num_heads,):
261
+ raise ValueError(
262
+ f"Head mask for a single layer should be of size {
263
+ (self.num_heads,)}, but is"
264
+ f" {layer_head_mask.size()}"
265
+ )
266
+ attn_weights = layer_head_mask.view(
267
+ 1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
268
+ attn_weights = attn_weights.view(
269
+ bsz * self.num_heads, tgt_len, src_len)
270
+
271
+ if output_attentions:
272
+ # this operation is a bit awkward, but it's required to
273
+ # make sure that attn_weights keeps its gradient.
274
+ # In order to do so, attn_weights have to be reshaped
275
+ # twice and have to be reused in the following
276
+ attn_weights_reshaped = attn_weights.view(
277
+ bsz, self.num_heads, tgt_len, src_len)
278
+ attn_weights = attn_weights_reshaped.view(
279
+ bsz * self.num_heads, tgt_len, src_len)
280
+ else:
281
+ attn_weights_reshaped = None
282
+
283
+ attn_probs = nn.functional.dropout(
284
+ attn_weights, p=self.dropout, training=self.training)
285
+
286
+ attn_output = torch.bmm(attn_probs, value_states)
287
+
288
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
289
+ raise ValueError(
290
+ f"`attn_output` should be of size {
291
+ (bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
292
+ f" {attn_output.size()}"
293
+ )
294
+
295
+ attn_output = attn_output.view(
296
+ bsz, self.num_heads, tgt_len, self.head_dim)
297
+ attn_output = attn_output.transpose(1, 2)
298
+
299
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
300
+ # partitioned aross GPUs when using tensor-parallelism.
301
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
302
+
303
+ attn_output = self.out_proj(attn_output)
304
+
305
+ return attn_output, attn_weights_reshaped, past_key_value
306
+
307
+
308
+ class OPTOutEffHop(OPTAttention):
309
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
310
+
311
+ def __init__(
312
+ self,
313
+ config: OPTConfig,
314
+ is_decoder: bool = False,
315
+ **kwargs,
316
+ ):
317
+ super().__init__()
318
+ self.config = config
319
+ self.embed_dim = config.hidden_size
320
+ self.num_heads = config.num_attention_heads
321
+ self.dropout = config.attention_dropout
322
+ self.enable_bias = config.enable_bias
323
+
324
+ self.head_dim = self.embed_dim // self.num_heads
325
+ self.is_causal = True
326
+
327
+ if (self.head_dim * self.num_heads) != self.embed_dim:
328
+ raise ValueError(
329
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {
330
+ self.embed_dim}"
331
+ f" and `num_heads`: {self.num_heads})."
332
+ )
333
+ self.scaling = self.head_dim**-0.5
334
+ self.is_decoder = is_decoder
335
+
336
+ self.k_proj = nn.Linear(
337
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
338
+ self.v_proj = nn.Linear(
339
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
340
+ self.q_proj = nn.Linear(
341
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
342
+ self.out_proj = nn.Linear(
343
+ self.embed_dim, self.embed_dim, bias=self.enable_bias)
344
+
345
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
346
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
347
+
348
+ def forward(
349
+ self,
350
+ hidden_states: torch.Tensor,
351
+ key_value_states: Optional[torch.Tensor] = None,
352
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
353
+ attention_mask: Optional[torch.Tensor] = None,
354
+ layer_head_mask: Optional[torch.Tensor] = None,
355
+ output_attentions: bool = False,
356
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
357
+ """Input shape: Batch x Time x Channel"""
358
+
359
+ # if key_value_states are provided this layer is used as a cross-attention layer
360
+ # for the decoder
361
+ is_cross_attention = key_value_states is not None
362
+
363
+ bsz, tgt_len, _ = hidden_states.size()
364
+
365
+ # get query proj
366
+ query_states = self.q_proj(hidden_states) * self.scaling
367
+ # get key, value proj
368
+ if is_cross_attention and past_key_value is not None:
369
+ # reuse k,v, cross_attentions
370
+ key_states = past_key_value[0]
371
+ value_states = past_key_value[1]
372
+ elif is_cross_attention:
373
+ # cross_attentions
374
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
375
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
376
+ elif past_key_value is not None:
377
+ # reuse k, v, self_attention
378
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
379
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
380
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
381
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
382
+ else:
383
+ # self_attention
384
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
385
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
386
+
387
+ if self.is_decoder:
388
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
389
+ # Further calls to cross_attention layer can then reuse all cross-attention
390
+ # key/value_states (first "if" case)
391
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
392
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
393
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
394
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
395
+ past_key_value = (key_states, value_states)
396
+
397
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
398
+ query_states = self._shape(
399
+ query_states, tgt_len, bsz).view(*proj_shape)
400
+ key_states = key_states.view(*proj_shape)
401
+ value_states = value_states.view(*proj_shape)
402
+
403
+ src_len = key_states.size(1)
404
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
405
+
406
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
407
+ raise ValueError(
408
+ f"Attention weights should be of size {
409
+ (bsz * self.num_heads, tgt_len, src_len)}, but is"
410
+ f" {attn_weights.size()}"
411
+ )
412
+
413
+ if attention_mask is not None:
414
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
415
+ raise ValueError(
416
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {
417
+ attention_mask.size()}"
418
+ )
419
+ attn_weights = attn_weights.view(
420
+ bsz, self.num_heads, tgt_len, src_len) + attention_mask
421
+ attn_weights = torch.max(
422
+ attn_weights, torch.tensor(torch.finfo(
423
+ attn_weights.dtype).min, device=attn_weights.device)
424
+ )
425
+ attn_weights = attn_weights.view(
426
+ bsz * self.num_heads, tgt_len, src_len)
427
+
428
+ # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
429
+ if attn_weights.dtype == torch.float16:
430
+ attn_weights = softmax_1(
431
+ attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
432
+ else:
433
+ attn_weights = softmax_1(attn_weights, dim=-1)
434
+
435
+ if layer_head_mask is not None:
436
+ if layer_head_mask.size() != (self.num_heads,):
437
+ raise ValueError(
438
+ f"Head mask for a single layer should be of size {
439
+ (self.num_heads,)}, but is"
440
+ f" {layer_head_mask.size()}"
441
+ )
442
+ attn_weights = layer_head_mask.view(
443
+ 1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
444
+ attn_weights = attn_weights.view(
445
+ bsz * self.num_heads, tgt_len, src_len)
446
+
447
+ if output_attentions:
448
+ # this operation is a bit awkward, but it's required to
449
+ # make sure that attn_weights keeps its gradient.
450
+ # In order to do so, attn_weights have to be reshaped
451
+ # twice and have to be reused in the following
452
+ attn_weights_reshaped = attn_weights.view(
453
+ bsz, self.num_heads, tgt_len, src_len)
454
+ attn_weights = attn_weights_reshaped.view(
455
+ bsz * self.num_heads, tgt_len, src_len)
456
+ else:
457
+ attn_weights_reshaped = None
458
+
459
+ attn_probs = nn.functional.dropout(
460
+ attn_weights, p=self.dropout, training=self.training)
461
+
462
+ attn_output = torch.bmm(attn_probs, value_states)
463
+
464
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
465
+ raise ValueError(
466
+ f"`attn_output` should be of size {
467
+ (bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
468
+ f" {attn_output.size()}"
469
+ )
470
+
471
+ attn_output = attn_output.view(
472
+ bsz, self.num_heads, tgt_len, self.head_dim)
473
+ attn_output = attn_output.transpose(1, 2)
474
+
475
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
476
+ # partitioned aross GPUs when using tensor-parallelism.
477
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
478
+
479
+ attn_output = self.out_proj(attn_output)
480
+
481
+ return attn_output, attn_weights_reshaped, past_key_value
482
+
483
+
484
+ class OptFlashAttention2(OPTAttention):
485
+ """
486
+ OPT flash attention module. This module inherits from `OPTAttention` as the weights of the module stays untouched.
487
+ The only required change would be on the forward pass where it needs to correctly call the public API of flash
488
+ attention and deal with padding tokens in case the input contains any of them.
489
+ """
490
+
491
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
492
+ def __init__(self, *args, **kwargs):
493
+ super().__init__(*args, **kwargs)
494
+
495
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
496
+ # 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.
497
+ # 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).
498
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
499
+
500
+ def forward(
501
+ self,
502
+ hidden_states: torch.Tensor,
503
+ key_value_states: Optional[torch.Tensor] = None,
504
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
505
+ attention_mask: Optional[torch.Tensor] = None,
506
+ layer_head_mask: Optional[torch.Tensor] = None,
507
+ output_attentions: bool = False,
508
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
509
+ """Input shape: Batch x Time x Channel"""
510
+
511
+ # if key_value_states are provided this layer is used as a cross-attention layer
512
+ # for the decoder
513
+ is_cross_attention = key_value_states is not None
514
+
515
+ bsz, _, _ = hidden_states.size()
516
+
517
+ # get query proj
518
+ query_states = self.q_proj(hidden_states)
519
+ # get key, value proj
520
+ if is_cross_attention and past_key_value is not None:
521
+ # reuse k,v, cross_attentions
522
+ key_states = past_key_value[0]
523
+ value_states = past_key_value[1]
524
+ elif is_cross_attention:
525
+ # cross_attentions
526
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
527
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
528
+ elif past_key_value is not None:
529
+ # reuse k, v, self_attention
530
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
531
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
532
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
533
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
534
+ else:
535
+ # self_attention
536
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
537
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
538
+
539
+ if self.is_decoder:
540
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
541
+ # Further calls to cross_attention layer can then reuse all cross-attention
542
+ # key/value_states (first "if" case)
543
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
544
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
545
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
546
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
547
+ past_key_value = (key_states, value_states)
548
+
549
+ query_length = query_states.shape[1]
550
+ tgt_len = key_states.shape[-2]
551
+
552
+ # Flash attention requires the input to have the shape
553
+ # batch_size x seq_length x head_dim x hidden_dim
554
+ query_states = query_states.view(
555
+ bsz, query_length, self.num_heads, self.head_dim)
556
+ key_states = key_states.transpose(1, 2).view(
557
+ bsz, tgt_len, self.num_heads, self.head_dim)
558
+ value_states = value_states.transpose(1, 2).view(
559
+ bsz, tgt_len, self.num_heads, self.head_dim)
560
+
561
+ attn_dropout = self.dropout if self.training else 0.0
562
+
563
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
564
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
565
+ # cast them back in float16 just to be sure everything works as expected.
566
+ input_dtype = query_states.dtype
567
+ if input_dtype == torch.float32:
568
+ if torch.is_autocast_enabled():
569
+ target_dtype = torch.get_autocast_gpu_dtype()
570
+ # Handle the case where the model is quantized
571
+ elif hasattr(self.config, "_pre_quantization_dtype"):
572
+ target_dtype = self.config._pre_quantization_dtype
573
+ else:
574
+ target_dtype = self.q_proj.weight.dtype
575
+
576
+ logger.warning_once(
577
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
578
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
579
+ f" {target_dtype}."
580
+ )
581
+
582
+ query_states = query_states.to(target_dtype)
583
+ key_states = key_states.to(target_dtype)
584
+ value_states = value_states.to(target_dtype)
585
+
586
+ attn_output = self._flash_attention_forward(
587
+ query_states, key_states, value_states, attention_mask, query_length, dropout=attn_dropout
588
+ )
589
+
590
+ attn_weights_reshaped = attn_output.reshape(
591
+ bsz, query_length, self.num_heads * self.head_dim)
592
+ attn_output = self.out_proj(attn_weights_reshaped)
593
+
594
+ if not output_attentions:
595
+ attn_weights_reshaped = None
596
+
597
+ return attn_output, attn_weights_reshaped, past_key_value
598
+
599
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
600
+ def _flash_attention_forward(
601
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
602
+ ):
603
+ """
604
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
605
+ first unpad the input, then computes the attention scores and pad the final attention scores.
606
+
607
+ Args:
608
+ query_states (`torch.Tensor`):
609
+ Input query states to be passed to Flash Attention API
610
+ key_states (`torch.Tensor`):
611
+ Input key states to be passed to Flash Attention API
612
+ value_states (`torch.Tensor`):
613
+ Input value states to be passed to Flash Attention API
614
+ attention_mask (`torch.Tensor`):
615
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
616
+ position of padding tokens and 1 for the position of non-padding tokens.
617
+ dropout (`float`):
618
+ Attention dropout
619
+ softmax_scale (`float`, *optional*):
620
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
621
+ """
622
+ if not self._flash_attn_uses_top_left_mask:
623
+ causal = self.is_causal
624
+ else:
625
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
626
+ causal = self.is_causal and query_length != 1
627
+
628
+ # Contains at least one padding token in the sequence
629
+ if attention_mask is not None:
630
+ batch_size = query_states.shape[0]
631
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
632
+ query_states, key_states, value_states, attention_mask, query_length
633
+ )
634
+
635
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
636
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
637
+
638
+ attn_output_unpad = flash_attn_varlen_func(
639
+ query_states,
640
+ key_states,
641
+ value_states,
642
+ cu_seqlens_q=cu_seqlens_q,
643
+ cu_seqlens_k=cu_seqlens_k,
644
+ max_seqlen_q=max_seqlen_in_batch_q,
645
+ max_seqlen_k=max_seqlen_in_batch_k,
646
+ dropout_p=dropout,
647
+ softmax_scale=softmax_scale,
648
+ causal=causal,
649
+ )
650
+
651
+ attn_output = pad_input(
652
+ attn_output_unpad, indices_q, batch_size, query_length)
653
+ else:
654
+ attn_output = flash_attn_func(
655
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
656
+ )
657
+
658
+ return attn_output
659
+
660
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
661
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
662
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(
663
+ attention_mask)
664
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
665
+
666
+ key_layer = index_first_axis(
667
+ key_layer.reshape(batch_size * kv_seq_len,
668
+ num_key_value_heads, head_dim), indices_k
669
+ )
670
+ value_layer = index_first_axis(
671
+ value_layer.reshape(batch_size * kv_seq_len,
672
+ num_key_value_heads, head_dim), indices_k
673
+ )
674
+ if query_length == kv_seq_len:
675
+ query_layer = index_first_axis(
676
+ query_layer.reshape(batch_size * kv_seq_len,
677
+ self.num_heads, head_dim), indices_k
678
+ )
679
+ cu_seqlens_q = cu_seqlens_k
680
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
681
+ indices_q = indices_k
682
+ elif query_length == 1:
683
+ max_seqlen_in_batch_q = 1
684
+ cu_seqlens_q = torch.arange(
685
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
686
+ ) # There is a memcpy here, that is very bad.
687
+ indices_q = cu_seqlens_q[:-1]
688
+ query_layer = query_layer.squeeze(1)
689
+ else:
690
+ # The -q_len: slice assumes left padding.
691
+ attention_mask = attention_mask[:, -query_length:]
692
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
693
+ query_layer, attention_mask)
694
+
695
+ return (
696
+ query_layer,
697
+ key_layer,
698
+ value_layer,
699
+ indices_q,
700
+ (cu_seqlens_q, cu_seqlens_k),
701
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
702
+ )
703
+
704
+
705
+ OPT_ATTENTION_CLASSES = {
706
+ "eager": OPTAttention,
707
+ "flash_attention_2": OptFlashAttention2,
708
+ "out_eff_hop": OPTOutEffHop,
709
+ }
710
+
711
+
712
+ class OPTDecoderLayer(nn.Module):
713
+ def __init__(self, config: OPTConfig):
714
+ super().__init__()
715
+ self.embed_dim = config.hidden_size
716
+
717
+ self.self_attn = OPT_ATTENTION_CLASSES[config._attn_implementation](
718
+ config=config, is_decoder=True)
719
+
720
+ self.do_layer_norm_before = config.do_layer_norm_before
721
+ self.dropout = config.dropout
722
+ self.activation_fn = ACT2FN[config.activation_function]
723
+
724
+ self.self_attn_layer_norm = nn.LayerNorm(
725
+ self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine
726
+ )
727
+ self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim,
728
+ bias=config.enable_bias)
729
+ self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim,
730
+ bias=config.enable_bias)
731
+ self.final_layer_norm = nn.LayerNorm(
732
+ self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine)
733
+
734
+ def forward(
735
+ self,
736
+ hidden_states: torch.Tensor,
737
+ attention_mask: Optional[torch.Tensor] = None,
738
+ layer_head_mask: Optional[torch.Tensor] = None,
739
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
740
+ output_attentions: Optional[bool] = False,
741
+ use_cache: Optional[bool] = False,
742
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
743
+ """
744
+ Args:
745
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
746
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
747
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
748
+ layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size
749
+ `(encoder_attention_heads,)`.
750
+ output_attentions (`bool`, *optional*):
751
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
752
+ returned tensors for more detail.
753
+ use_cache (`bool`, *optional*):
754
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
755
+ (see `past_key_values`).
756
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
757
+ """
758
+
759
+ residual = hidden_states
760
+
761
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
762
+ if self.do_layer_norm_before:
763
+ hidden_states = self.self_attn_layer_norm(hidden_states)
764
+
765
+ # Self Attention
766
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
767
+ hidden_states=hidden_states,
768
+ past_key_value=past_key_value,
769
+ attention_mask=attention_mask,
770
+ layer_head_mask=layer_head_mask,
771
+ output_attentions=output_attentions,
772
+ )
773
+ hidden_states = nn.functional.dropout(
774
+ hidden_states, p=self.dropout, training=self.training)
775
+ hidden_states = residual + hidden_states
776
+
777
+ # 350m applies layer norm AFTER attention
778
+ if not self.do_layer_norm_before:
779
+ hidden_states = self.self_attn_layer_norm(hidden_states)
780
+
781
+ # Fully Connected
782
+ hidden_states_shape = hidden_states.shape
783
+ hidden_states = hidden_states.reshape(-1, hidden_states.size(-1))
784
+ residual = hidden_states
785
+
786
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
787
+ if self.do_layer_norm_before:
788
+ hidden_states = self.final_layer_norm(hidden_states)
789
+
790
+ hidden_states = self.fc1(hidden_states)
791
+ hidden_states = self.activation_fn(hidden_states)
792
+
793
+ hidden_states = self.fc2(hidden_states)
794
+ hidden_states = nn.functional.dropout(
795
+ hidden_states, p=self.dropout, training=self.training)
796
+
797
+ hidden_states = (residual + hidden_states).view(hidden_states_shape)
798
+
799
+ # 350m applies layer norm AFTER attention
800
+ if not self.do_layer_norm_before:
801
+ hidden_states = self.final_layer_norm(hidden_states)
802
+
803
+ outputs = (hidden_states,)
804
+
805
+ if output_attentions:
806
+ outputs += (self_attn_weights,)
807
+
808
+ if use_cache:
809
+ outputs += (present_key_value,)
810
+
811
+ return outputs
812
+
813
+
814
+ OPT_START_DOCSTRING = r"""
815
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
816
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
817
+ etc.)
818
+
819
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
820
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
821
+ and behavior.
822
+
823
+ Parameters:
824
+ config ([`OPTConfig`]):
825
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
826
+ load the weights associated with the model, only the configuration. Check out the
827
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
828
+ """
829
+
830
+
831
+ @add_start_docstrings(
832
+ "The bare OPT Model outputting raw hidden-states without any specific head on top.",
833
+ OPT_START_DOCSTRING,
834
+ )
835
+ class OPTPreTrainedModel(PreTrainedModel):
836
+ config_class = OPTConfig
837
+ base_model_prefix = "model"
838
+ supports_gradient_checkpointing = True
839
+ _no_split_modules = ["OPTDecoderLayer"]
840
+ _supports_flash_attn_2 = True
841
+
842
+ def _init_weights(self, module):
843
+ std = self.config.init_std
844
+ if isinstance(module, nn.Linear):
845
+ module.weight.data.normal_(mean=0.0, std=std)
846
+ if module.bias is not None:
847
+ module.bias.data.zero_()
848
+ elif isinstance(module, nn.Embedding):
849
+ module.weight.data.normal_(mean=0.0, std=std)
850
+ if module.padding_idx is not None:
851
+ module.weight.data[module.padding_idx].zero_()
852
+
853
+
854
+ OPT_INPUTS_DOCSTRING = r"""
855
+ Args:
856
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
857
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
858
+ it.
859
+
860
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
861
+ [`PreTrainedTokenizer.__call__`] for details.
862
+
863
+ [What are input IDs?](../glossary#input-ids)
864
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
865
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
866
+
867
+ - 1 for tokens that are **not masked**,
868
+ - 0 for tokens that are **masked**.
869
+
870
+ [What are attention masks?](../glossary#attention-mask)
871
+
872
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
873
+ [`PreTrainedTokenizer.__call__`] for details.
874
+
875
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
876
+ `past_key_values`).
877
+
878
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
879
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
880
+ information on the default strategy.
881
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
882
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
883
+
884
+ - 1 indicates the head is **not masked**,
885
+ - 0 indicates the head is **masked**.
886
+
887
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
888
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
889
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
890
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
891
+
892
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
893
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
894
+
895
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
896
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
897
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
898
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
899
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
900
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
901
+ model's internal embedding lookup matrix.
902
+ use_cache (`bool`, *optional*):
903
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
904
+ `past_key_values`).
905
+ output_attentions (`bool`, *optional*):
906
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
907
+ tensors for more detail.
908
+ output_hidden_states (`bool`, *optional*):
909
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
910
+ more detail.
911
+ return_dict (`bool`, *optional*):
912
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
913
+ """
914
+
915
+
916
+ class OPTDecoder(OPTPreTrainedModel):
917
+ """
918
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`]
919
+
920
+ Args:
921
+ config: OPTConfig
922
+ """
923
+
924
+ def __init__(self, config: OPTConfig):
925
+ super().__init__(config)
926
+ self.dropout = config.dropout
927
+ self.layerdrop = config.layerdrop
928
+ self.padding_idx = config.pad_token_id
929
+ self.max_target_positions = config.max_position_embeddings
930
+ self.vocab_size = config.vocab_size
931
+
932
+ self.embed_tokens = nn.Embedding(
933
+ config.vocab_size, config.word_embed_proj_dim, self.padding_idx)
934
+ self.embed_positions = OPTLearnedPositionalEmbedding(
935
+ config.max_position_embeddings, config.hidden_size)
936
+
937
+ if config.word_embed_proj_dim != config.hidden_size:
938
+ self.project_out = nn.Linear(
939
+ config.hidden_size, config.word_embed_proj_dim, bias=False)
940
+ else:
941
+ self.project_out = None
942
+
943
+ if config.word_embed_proj_dim != config.hidden_size:
944
+ self.project_in = nn.Linear(
945
+ config.word_embed_proj_dim, config.hidden_size, bias=False)
946
+ else:
947
+ self.project_in = None
948
+
949
+ # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility
950
+ # with checkpoints that have been fine-tuned before transformers v4.20.1
951
+ # see https://github.com/facebookresearch/metaseq/pull/164
952
+ if config.do_layer_norm_before and not config._remove_final_layer_norm:
953
+ self.final_layer_norm = nn.LayerNorm(
954
+ config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine
955
+ )
956
+ else:
957
+ self.final_layer_norm = None
958
+
959
+ self.layers = nn.ModuleList(
960
+ [OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)])
961
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
962
+
963
+ self.gradient_checkpointing = False
964
+ # Initialize weights and apply final processing
965
+ self.post_init()
966
+
967
+ def get_input_embeddings(self):
968
+ return self.embed_tokens
969
+
970
+ def set_input_embeddings(self, value):
971
+ self.embed_tokens = value
972
+
973
+ def forward(
974
+ self,
975
+ input_ids: torch.LongTensor = None,
976
+ attention_mask: Optional[torch.Tensor] = None,
977
+ head_mask: Optional[torch.Tensor] = None,
978
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
979
+ inputs_embeds: Optional[torch.FloatTensor] = None,
980
+ use_cache: Optional[bool] = None,
981
+ output_attentions: Optional[bool] = None,
982
+ output_hidden_states: Optional[bool] = None,
983
+ return_dict: Optional[bool] = None,
984
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
985
+ r"""
986
+ Args:
987
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
988
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
989
+ provide it.
990
+
991
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
992
+ [`PreTrainedTokenizer.__call__`] for details.
993
+
994
+ [What are input IDs?](../glossary#input-ids)
995
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
996
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
997
+
998
+ - 1 for tokens that are **not masked**,
999
+ - 0 for tokens that are **masked**.
1000
+
1001
+ [What are attention masks?](../glossary#attention-mask)
1002
+ head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*):
1003
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1004
+
1005
+ - 1 indicates the head is **not masked**,
1006
+ - 0 indicates the head is **masked**.
1007
+
1008
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1009
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1010
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1011
+
1012
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1013
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1014
+
1015
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1016
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1017
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1018
+
1019
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1020
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1021
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1022
+ than the model's internal embedding lookup matrix.
1023
+ output_attentions (`bool`, *optional*):
1024
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1025
+ returned tensors for more detail.
1026
+ output_hidden_states (`bool`, *optional*):
1027
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1028
+ for more detail.
1029
+ return_dict (`bool`, *optional*):
1030
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1031
+ """
1032
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1033
+ output_hidden_states = (
1034
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1035
+ )
1036
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1037
+
1038
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1039
+
1040
+ # retrieve input_ids and inputs_embeds
1041
+ if input_ids is not None and inputs_embeds is not None:
1042
+ raise ValueError(
1043
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1044
+ elif input_ids is not None:
1045
+ input_shape = input_ids.size()
1046
+ input_ids = input_ids.view(-1, input_shape[-1])
1047
+ elif inputs_embeds is not None:
1048
+ input_shape = inputs_embeds.size()[:-1]
1049
+ else:
1050
+ raise ValueError(
1051
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds")
1052
+
1053
+ if inputs_embeds is None:
1054
+ inputs_embeds = self.embed_tokens(input_ids)
1055
+
1056
+ batch_size, seq_length = input_shape
1057
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1058
+ # required mask seq length can be calculated via length of past
1059
+ mask_seq_length = past_key_values_length + seq_length
1060
+
1061
+ # embed positions
1062
+ if self._use_flash_attention_2:
1063
+ # 2d mask is passed through the layers
1064
+ causal_attention_mask = attention_mask if (
1065
+ attention_mask is not None and 0 in attention_mask) else None
1066
+ attention_mask = (
1067
+ torch.ones(batch_size, mask_seq_length,
1068
+ device=inputs_embeds.device)
1069
+ if attention_mask is None
1070
+ else attention_mask
1071
+ )
1072
+ else:
1073
+ # 4d mask is passed through the layers
1074
+ if attention_mask is None:
1075
+ attention_mask = torch.ones(
1076
+ batch_size, mask_seq_length, device=inputs_embeds.device)
1077
+ elif attention_mask.shape[1] != mask_seq_length:
1078
+ raise ValueError(
1079
+ f"The provided attention mask has length {
1080
+ attention_mask.shape[1]}, but its length should be "
1081
+ f"{mask_seq_length} (sum of the lengths of current and past inputs)"
1082
+ )
1083
+ causal_attention_mask = _prepare_4d_causal_attention_mask(
1084
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1085
+ )
1086
+
1087
+ pos_embeds = self.embed_positions(
1088
+ attention_mask, past_key_values_length)
1089
+
1090
+ if self.project_in is not None:
1091
+ inputs_embeds = self.project_in(inputs_embeds)
1092
+
1093
+ hidden_states = inputs_embeds + pos_embeds
1094
+
1095
+ if self.gradient_checkpointing and self.training:
1096
+ if use_cache:
1097
+ logger.warning_once(
1098
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1099
+ )
1100
+ use_cache = False
1101
+
1102
+ # decoder layers
1103
+ all_hidden_states = () if output_hidden_states else None
1104
+ all_self_attns = () if output_attentions else None
1105
+ next_decoder_cache = () if use_cache else None
1106
+
1107
+ # check if head_mask has a correct number of layers specified if desired
1108
+ for attn_mask, mask_name in zip([head_mask], ["head_mask"]):
1109
+ if attn_mask is not None:
1110
+ if attn_mask.size()[0] != (len(self.layers)):
1111
+ raise ValueError(
1112
+ f"The `{mask_name}` should be specified for {
1113
+ len(self.layers)} layers, but it is for"
1114
+ f" {head_mask.size()[0]}."
1115
+ )
1116
+
1117
+ for idx, decoder_layer in enumerate(self.layers):
1118
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1119
+ if output_hidden_states:
1120
+ all_hidden_states += (hidden_states,)
1121
+
1122
+ if self.training:
1123
+ dropout_probability = torch.rand([])
1124
+ if dropout_probability < self.layerdrop:
1125
+ continue
1126
+
1127
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1128
+
1129
+ if self.gradient_checkpointing and self.training:
1130
+ layer_outputs = self._gradient_checkpointing_func(
1131
+ decoder_layer.__call__,
1132
+ hidden_states,
1133
+ causal_attention_mask,
1134
+ head_mask[idx] if head_mask is not None else None,
1135
+ None,
1136
+ output_attentions,
1137
+ use_cache,
1138
+ )
1139
+ else:
1140
+ layer_outputs = decoder_layer(
1141
+ hidden_states,
1142
+ attention_mask=causal_attention_mask,
1143
+ layer_head_mask=(
1144
+ head_mask[idx] if head_mask is not None else None),
1145
+ past_key_value=past_key_value,
1146
+ output_attentions=output_attentions,
1147
+ use_cache=use_cache,
1148
+ )
1149
+
1150
+ hidden_states = layer_outputs[0]
1151
+
1152
+ if use_cache:
1153
+ next_decoder_cache += (
1154
+ layer_outputs[2 if output_attentions else 1],)
1155
+
1156
+ if output_attentions:
1157
+ all_self_attns += (layer_outputs[1],)
1158
+
1159
+ if self.final_layer_norm is not None:
1160
+ hidden_states = self.final_layer_norm(hidden_states)
1161
+
1162
+ if self.project_out is not None:
1163
+ hidden_states = self.project_out(hidden_states)
1164
+
1165
+ # add hidden states from the last decoder layer
1166
+ if output_hidden_states:
1167
+ all_hidden_states += (hidden_states,)
1168
+
1169
+ next_cache = next_decoder_cache if use_cache else None
1170
+ if not return_dict:
1171
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1172
+ return BaseModelOutputWithPast(
1173
+ last_hidden_state=hidden_states,
1174
+ past_key_values=next_cache,
1175
+ hidden_states=all_hidden_states,
1176
+ attentions=all_self_attns,
1177
+ )
1178
+
1179
+
1180
+ @add_start_docstrings(
1181
+ "The bare OPT Model outputting raw hidden-states without any specific head on top.",
1182
+ OPT_START_DOCSTRING,
1183
+ )
1184
+ class OPTModel(OPTPreTrainedModel):
1185
+ def __init__(self, config: OPTConfig):
1186
+ super().__init__(config)
1187
+ self.decoder = OPTDecoder(config)
1188
+ # Initialize weights and apply final processing
1189
+ self.post_init()
1190
+
1191
+ def get_input_embeddings(self):
1192
+ return self.decoder.embed_tokens
1193
+
1194
+ def set_input_embeddings(self, value):
1195
+ self.decoder.embed_tokens = value
1196
+
1197
+ def get_decoder(self):
1198
+ return self.decoder
1199
+
1200
+ @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING)
1201
+ @add_code_sample_docstrings(
1202
+ checkpoint=_CHECKPOINT_FOR_DOC,
1203
+ output_type=BaseModelOutputWithPast,
1204
+ config_class=_CONFIG_FOR_DOC,
1205
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
1206
+ )
1207
+ def forward(
1208
+ self,
1209
+ input_ids: torch.LongTensor = None,
1210
+ attention_mask: Optional[torch.Tensor] = None,
1211
+ head_mask: Optional[torch.Tensor] = None,
1212
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1213
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1214
+ use_cache: Optional[bool] = None,
1215
+ output_attentions: Optional[bool] = None,
1216
+ output_hidden_states: Optional[bool] = None,
1217
+ return_dict: Optional[bool] = None,
1218
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1219
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1220
+ output_hidden_states = (
1221
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1222
+ )
1223
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1224
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1225
+
1226
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1227
+ decoder_outputs = self.decoder(
1228
+ input_ids=input_ids,
1229
+ attention_mask=attention_mask,
1230
+ head_mask=head_mask,
1231
+ past_key_values=past_key_values,
1232
+ inputs_embeds=inputs_embeds,
1233
+ use_cache=use_cache,
1234
+ output_attentions=output_attentions,
1235
+ output_hidden_states=output_hidden_states,
1236
+ return_dict=return_dict,
1237
+ )
1238
+
1239
+ if not return_dict:
1240
+ return decoder_outputs
1241
+
1242
+ return BaseModelOutputWithPast(
1243
+ last_hidden_state=decoder_outputs.last_hidden_state,
1244
+ past_key_values=decoder_outputs.past_key_values,
1245
+ hidden_states=decoder_outputs.hidden_states,
1246
+ attentions=decoder_outputs.attentions,
1247
+ )
1248
+
1249
+
1250
+ class OPTForCausalLM(OPTPreTrainedModel):
1251
+ _tied_weights_keys = ["lm_head.weight"]
1252
+
1253
+ def __init__(self, config):
1254
+ super().__init__(config)
1255
+ self.model = OPTModel(config)
1256
+
1257
+ # the lm_head weight is automatically tied to the embed tokens weight
1258
+ self.lm_head = nn.Linear(
1259
+ config.word_embed_proj_dim, config.vocab_size, bias=False)
1260
+
1261
+ # Initialize weights and apply final processing
1262
+ self.post_init()
1263
+
1264
+ def get_input_embeddings(self):
1265
+ return self.model.decoder.embed_tokens
1266
+
1267
+ def set_input_embeddings(self, value):
1268
+ self.model.decoder.embed_tokens = value
1269
+
1270
+ def get_output_embeddings(self):
1271
+ return self.lm_head
1272
+
1273
+ def set_output_embeddings(self, new_embeddings):
1274
+ self.lm_head = new_embeddings
1275
+
1276
+ def set_decoder(self, decoder):
1277
+ self.model.decoder = decoder
1278
+
1279
+ def get_decoder(self):
1280
+ return self.model.decoder
1281
+
1282
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1283
+ def forward(
1284
+ self,
1285
+ input_ids: torch.LongTensor = None,
1286
+ attention_mask: Optional[torch.Tensor] = None,
1287
+ head_mask: Optional[torch.Tensor] = None,
1288
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1289
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1290
+ labels: Optional[torch.LongTensor] = None,
1291
+ use_cache: Optional[bool] = None,
1292
+ output_attentions: Optional[bool] = None,
1293
+ output_hidden_states: Optional[bool] = None,
1294
+ return_dict: Optional[bool] = None,
1295
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1296
+ r"""
1297
+ Args:
1298
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1299
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1300
+ provide it.
1301
+
1302
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1303
+ [`PreTrainedTokenizer.__call__`] for details.
1304
+
1305
+ [What are input IDs?](../glossary#input-ids)
1306
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1307
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1308
+
1309
+ - 1 for tokens that are **not masked**,
1310
+ - 0 for tokens that are **masked**.
1311
+
1312
+ [What are attention masks?](../glossary#attention-mask)
1313
+ head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*):
1314
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1315
+
1316
+ - 1 indicates the head is **not masked**,
1317
+ - 0 indicates the head is **masked**.
1318
+
1319
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1320
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1321
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1322
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
1323
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
1324
+
1325
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1326
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1327
+
1328
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1329
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1330
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1331
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1332
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1333
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1334
+ than the model's internal embedding lookup matrix.
1335
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1336
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1337
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1338
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1339
+ use_cache (`bool`, *optional*):
1340
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1341
+ (see `past_key_values`).
1342
+ output_attentions (`bool`, *optional*):
1343
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1344
+ returned tensors for more detail.
1345
+ output_hidden_states (`bool`, *optional*):
1346
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1347
+ for more detail.
1348
+ return_dict (`bool`, *optional*):
1349
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1350
+
1351
+ Returns:
1352
+
1353
+ Example:
1354
+
1355
+ ```python
1356
+ >>> from transformers import AutoTokenizer, OPTForCausalLM
1357
+
1358
+ >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m")
1359
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
1360
+
1361
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1362
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1363
+
1364
+ >>> # Generate
1365
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1366
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1367
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious. I'm just a little bit of a weirdo."
1368
+ ```"""
1369
+
1370
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1371
+ output_hidden_states = (
1372
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1373
+ )
1374
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1375
+
1376
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1377
+ outputs = self.model.decoder(
1378
+ input_ids=input_ids,
1379
+ attention_mask=attention_mask,
1380
+ head_mask=head_mask,
1381
+ past_key_values=past_key_values,
1382
+ inputs_embeds=inputs_embeds,
1383
+ use_cache=use_cache,
1384
+ output_attentions=output_attentions,
1385
+ output_hidden_states=output_hidden_states,
1386
+ return_dict=return_dict,
1387
+ )
1388
+
1389
+ logits = self.lm_head(outputs[0]).contiguous()
1390
+
1391
+ loss = None
1392
+ if labels is not None:
1393
+ # move labels to correct device to enable model parallelism
1394
+ labels = labels.to(logits.device)
1395
+ # Shift so that tokens < n predict n
1396
+ shift_logits = logits[..., :-1, :].contiguous()
1397
+ shift_labels = labels[..., 1:].contiguous()
1398
+ # Flatten the tokens
1399
+ loss_fct = CrossEntropyLoss()
1400
+ loss = loss_fct(
1401
+ shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
1402
+
1403
+ if not return_dict:
1404
+ output = (logits,) + outputs[1:]
1405
+ return (loss,) + output if loss is not None else output
1406
+
1407
+ return CausalLMOutputWithPast(
1408
+ loss=loss,
1409
+ logits=logits,
1410
+ past_key_values=outputs.past_key_values,
1411
+ hidden_states=outputs.hidden_states,
1412
+ attentions=outputs.attentions,
1413
+ )
1414
+
1415
+ def prepare_inputs_for_generation(
1416
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1417
+ ):
1418
+ if past_key_values is not None:
1419
+ past_length = past_key_values[0][0].shape[2]
1420
+
1421
+ # Some generation methods already pass only the last input ID
1422
+ if input_ids.shape[1] > past_length:
1423
+ remove_prefix_length = past_length
1424
+ else:
1425
+ # Default to old behavior: keep only final ID
1426
+ remove_prefix_length = input_ids.shape[1] - 1
1427
+
1428
+ input_ids = input_ids[:, remove_prefix_length:]
1429
+
1430
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1431
+ if inputs_embeds is not None and past_key_values is None:
1432
+ model_inputs = {"inputs_embeds": inputs_embeds}
1433
+ else:
1434
+ model_inputs = {"input_ids": input_ids}
1435
+
1436
+ model_inputs.update(
1437
+ {
1438
+ "past_key_values": past_key_values,
1439
+ "use_cache": kwargs.get("use_cache"),
1440
+ "attention_mask": attention_mask,
1441
+ }
1442
+ )
1443
+ return model_inputs
1444
+
1445
+ @staticmethod
1446
+ def _reorder_cache(past_key_values, beam_idx):
1447
+ reordered_past = ()
1448
+ for layer_past in past_key_values:
1449
+ reordered_past += (
1450
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device))
1451
+ for past_state in layer_past),
1452
+ )
1453
+ return reordered_past
1454
+
1455
+
1456
+ @add_start_docstrings(
1457
+ """
1458
+ The OPT Model transformer with a sequence classification head on top (linear layer).
1459
+
1460
+ [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1461
+ (e.g. GPT-2) do.
1462
+
1463
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1464
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1465
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1466
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1467
+ each row of the batch).
1468
+ """,
1469
+ OPT_START_DOCSTRING,
1470
+ )
1471
+ class OPTForSequenceClassification(OPTPreTrainedModel):
1472
+ def __init__(self, config: OPTConfig):
1473
+ super().__init__(config)
1474
+ self.num_labels = config.num_labels
1475
+ self.model = OPTModel(config)
1476
+ self.score = nn.Linear(config.word_embed_proj_dim,
1477
+ self.num_labels, bias=False)
1478
+
1479
+ # Initialize weights and apply final processing
1480
+ self.post_init()
1481
+
1482
+ @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING)
1483
+ @add_code_sample_docstrings(
1484
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1485
+ output_type=SequenceClassifierOutputWithPast,
1486
+ config_class=_CONFIG_FOR_DOC,
1487
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1488
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1489
+ )
1490
+ def forward(
1491
+ self,
1492
+ input_ids: Optional[torch.LongTensor] = None,
1493
+ attention_mask: Optional[torch.FloatTensor] = None,
1494
+ head_mask: Optional[torch.FloatTensor] = None,
1495
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1496
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1497
+ labels: Optional[torch.LongTensor] = None,
1498
+ use_cache: Optional[bool] = None,
1499
+ output_attentions: Optional[bool] = None,
1500
+ output_hidden_states: Optional[bool] = None,
1501
+ return_dict: Optional[bool] = None,
1502
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1503
+ r"""
1504
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1505
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1506
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1507
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1508
+ """
1509
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1510
+
1511
+ transformer_outputs = self.model(
1512
+ input_ids,
1513
+ past_key_values=past_key_values,
1514
+ attention_mask=attention_mask,
1515
+ head_mask=head_mask,
1516
+ inputs_embeds=inputs_embeds,
1517
+ use_cache=use_cache,
1518
+ output_attentions=output_attentions,
1519
+ output_hidden_states=output_hidden_states,
1520
+ return_dict=return_dict,
1521
+ )
1522
+ hidden_states = transformer_outputs[0]
1523
+ logits = self.score(hidden_states)
1524
+
1525
+ if input_ids is not None:
1526
+ batch_size, sequence_length = input_ids.shape[:2]
1527
+ else:
1528
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1529
+
1530
+ if self.config.pad_token_id is None:
1531
+ sequence_lengths = -1
1532
+ else:
1533
+ if input_ids is not None:
1534
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1535
+ sequence_lengths = torch.eq(
1536
+ input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1537
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1538
+ sequence_lengths = sequence_lengths.to(logits.device)
1539
+ else:
1540
+ sequence_lengths = -1
1541
+ logger.warning(
1542
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1543
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1544
+ )
1545
+
1546
+ pooled_logits = logits[torch.arange(
1547
+ batch_size, device=logits.device), sequence_lengths]
1548
+
1549
+ loss = None
1550
+ if labels is not None:
1551
+ if self.config.problem_type is None:
1552
+ if self.num_labels == 1:
1553
+ self.config.problem_type = "regression"
1554
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1555
+ self.config.problem_type = "single_label_classification"
1556
+ else:
1557
+ self.config.problem_type = "multi_label_classification"
1558
+
1559
+ if self.config.problem_type == "regression":
1560
+ loss_fct = MSELoss()
1561
+ if self.num_labels == 1:
1562
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1563
+ else:
1564
+ loss = loss_fct(pooled_logits, labels)
1565
+ elif self.config.problem_type == "single_label_classification":
1566
+ loss_fct = CrossEntropyLoss()
1567
+ loss = loss_fct(
1568
+ pooled_logits.view(-1, self.num_labels), labels.view(-1))
1569
+ elif self.config.problem_type == "multi_label_classification":
1570
+ loss_fct = BCEWithLogitsLoss()
1571
+ loss = loss_fct(pooled_logits, labels)
1572
+ if not return_dict:
1573
+ output = (pooled_logits,) + transformer_outputs[1:]
1574
+ return ((loss,) + output) if loss is not None else output
1575
+
1576
+ return SequenceClassifierOutputWithPast(
1577
+ loss=loss,
1578
+ logits=pooled_logits,
1579
+ past_key_values=transformer_outputs.past_key_values,
1580
+ hidden_states=transformer_outputs.hidden_states,
1581
+ attentions=transformer_outputs.attentions,
1582
+ )
1583
+
1584
+ def get_input_embeddings(self):
1585
+ return self.model.decoder.embed_tokens
1586
+
1587
+ def set_input_embeddings(self, value):
1588
+ self.model.decoder.embed_tokens = value
1589
+
1590
+
1591
+ @add_start_docstrings(
1592
+ """
1593
+ The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD
1594
+ (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1595
+ """,
1596
+ OPT_START_DOCSTRING,
1597
+ )
1598
+ class OPTForQuestionAnswering(OPTPreTrainedModel):
1599
+ def __init__(self, config: OPTConfig):
1600
+ super().__init__(config)
1601
+ self.model = OPTModel(config)
1602
+ self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2)
1603
+
1604
+ # Initialize weights and apply final processing
1605
+ self.post_init()
1606
+
1607
+ @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING)
1608
+ @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)
1609
+ def forward(
1610
+ self,
1611
+ input_ids: Optional[torch.LongTensor] = None,
1612
+ attention_mask: Optional[torch.FloatTensor] = None,
1613
+ head_mask: Optional[torch.FloatTensor] = None,
1614
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1615
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1616
+ start_positions: Optional[torch.LongTensor] = None,
1617
+ end_positions: Optional[torch.LongTensor] = None,
1618
+ use_cache: Optional[bool] = None,
1619
+ output_attentions: Optional[bool] = None,
1620
+ output_hidden_states: Optional[bool] = None,
1621
+ return_dict: Optional[bool] = None,
1622
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1623
+ r"""
1624
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1625
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1626
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1627
+ are not taken into account for computing the loss.
1628
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1629
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1630
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1631
+ are not taken into account for computing the loss.
1632
+
1633
+ Returns:
1634
+
1635
+ Example:
1636
+
1637
+ ```python
1638
+ >>> from transformers import AutoTokenizer, OPTForQuestionAnswering
1639
+ >>> import torch
1640
+
1641
+ >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT
1642
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
1643
+
1644
+ >>> # note: we are loading a OPTForQuestionAnswering from the hub here,
1645
+ >>> # so the head will be randomly initialized, hence the predictions will be random
1646
+ >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m")
1647
+
1648
+ >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
1649
+
1650
+ >>> inputs = tokenizer(question, text, return_tensors="pt")
1651
+ >>> with torch.no_grad():
1652
+ ... outputs = model(**inputs)
1653
+
1654
+ >>> answer_start_index = outputs.start_logits.argmax()
1655
+ >>> answer_end_index = outputs.end_logits.argmax()
1656
+
1657
+ >>> answer_offset = len(tokenizer(question)[0])
1658
+
1659
+ >>> predict_answer_tokens = inputs.input_ids[
1660
+ ... 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1
1661
+ ... ]
1662
+ >>> predicted = tokenizer.decode(predict_answer_tokens)
1663
+ >>> predicted
1664
+ ' a nice puppet'
1665
+ ```"""
1666
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1667
+
1668
+ transformer_outputs = self.model(
1669
+ input_ids,
1670
+ past_key_values=past_key_values,
1671
+ attention_mask=attention_mask,
1672
+ head_mask=head_mask,
1673
+ inputs_embeds=inputs_embeds,
1674
+ use_cache=use_cache,
1675
+ output_attentions=output_attentions,
1676
+ output_hidden_states=output_hidden_states,
1677
+ return_dict=return_dict,
1678
+ )
1679
+ hidden_states = transformer_outputs[0]
1680
+
1681
+ logits = self.qa_outputs(hidden_states)
1682
+ start_logits, end_logits = logits.split(1, dim=-1)
1683
+ start_logits = start_logits.squeeze(-1).contiguous()
1684
+ end_logits = end_logits.squeeze(-1).contiguous()
1685
+
1686
+ total_loss = None
1687
+ if start_positions is not None and end_positions is not None:
1688
+ # If we are on multi-GPU, split add a dimension
1689
+ if len(start_positions.size()) > 1:
1690
+ start_positions = start_positions.squeeze(-1)
1691
+ if len(end_positions.size()) > 1:
1692
+ end_positions = end_positions.squeeze(-1)
1693
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1694
+ ignored_index = start_logits.size(1)
1695
+ start_positions = start_positions.clamp(
1696
+ 0, ignored_index).to(logits.device)
1697
+ end_positions = end_positions.clamp(
1698
+ 0, ignored_index).to(logits.device)
1699
+
1700
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1701
+ start_loss = loss_fct(start_logits, start_positions)
1702
+ end_loss = loss_fct(end_logits, end_positions)
1703
+ total_loss = (start_loss + end_loss) / 2
1704
+
1705
+ if not return_dict:
1706
+ output = (start_logits, end_logits) + transformer_outputs[2:]
1707
+ return ((total_loss,) + output) if total_loss is not None else output
1708
+
1709
+ return QuestionAnsweringModelOutput(
1710
+ loss=total_loss,
1711
+ start_logits=start_logits,
1712
+ end_logits=end_logits,
1713
+ hidden_states=transformer_outputs.hidden_states,
1714
+ attentions=transformer_outputs.attentions,
1715
+ )
1716
+
1717
+ def get_input_embeddings(self):
1718
+ return self.model.decoder.embed_tokens
1719
+
1720
+ def set_input_embeddings(self, value):
1721
+ self.model.decoder.embed_tokens = value