robinzixuan commited on
Commit
f2e980e
1 Parent(s): e3c894a

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_opt.py +143 -0
  2. modeling_opt.py +1545 -0
configuration_opt.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ **kwargs,
115
+ ):
116
+ super().__init__(
117
+ pad_token_id=pad_token_id,
118
+ bos_token_id=bos_token_id,
119
+ eos_token_id=eos_token_id,
120
+ **kwargs,
121
+ )
122
+ self.vocab_size = vocab_size
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.num_attention_heads = num_attention_heads
125
+ self.word_embed_proj_dim = word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size
126
+ self.ffn_dim = ffn_dim
127
+ self.hidden_size = hidden_size
128
+ self.num_hidden_layers = num_hidden_layers
129
+ self.dropout = dropout
130
+ self.attention_dropout = attention_dropout
131
+ self.activation_function = activation_function
132
+ self.init_std = init_std
133
+ self.layerdrop = layerdrop
134
+ self.use_cache = use_cache
135
+ self.do_layer_norm_before = do_layer_norm_before
136
+ # We keep these variables at `True` for backward compatibility.
137
+ self.enable_bias = enable_bias
138
+ self.layer_norm_elementwise_affine = layer_norm_elementwise_affine
139
+
140
+ # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility
141
+ # with checkpoints that have been fine-tuned before transformers v4.20.1
142
+ # see https://github.com/facebookresearch/metaseq/pull/164
143
+ self._remove_final_layer_norm = _remove_final_layer_norm
modeling_opt.py ADDED
@@ -0,0 +1,1545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Note: softmax_n, with fixed input, is _not_ shift-symmetric when n != 0
108
+ """
109
+ # compute the maxes along the last dimension
110
+ input_maxes = input.max(dim=dim, keepdim=True).values
111
+ # shift the input to prevent overflow (and underflow in the denominator)
112
+ shifted_inputs = torch.subtract(input, input_maxes)
113
+ # compute the numerator and softmax_0 denominator using the shifted input
114
+ numerator = torch.exp(shifted_inputs)
115
+ original_denominator = numerator.sum(dim=dim, keepdim=True)
116
+ # we need to shift the zeros in the same way we shifted the inputs
117
+ shifted_zeros = torch.multiply(input_maxes, -1)
118
+ # and then add this contribution to the denominator
119
+ denominator = torch.add(original_denominator,
120
+ torch.multiply(torch.exp(shifted_zeros), n))
121
+ return torch.divide(numerator, denominator)
122
+
123
+
124
+ def softmax_1(input: torch.Tensor, dim=-1, dtype=torch.float32) -> torch.Tensor:
125
+ """
126
+ $\text(softmax)_n(x_i) = exp(x_i) / (1 + \sum_j exp(x_j))$
127
+ """
128
+ output = softmax_n_shifted_zeros(input, 1, dim=dim)
129
+ return output if dtype is None else output.type(dtype=dtype)
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 = softmax_1(
255
+ attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
256
+ else:
257
+ attn_weights = softmax_1(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
+
309
+ class OptFlashAttention2(OPTAttention):
310
+ """
311
+ OPT flash attention module. This module inherits from `OPTAttention` as the weights of the module stays untouched.
312
+ The only required change would be on the forward pass where it needs to correctly call the public API of flash
313
+ attention and deal with padding tokens in case the input contains any of them.
314
+ """
315
+
316
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
317
+ def __init__(self, *args, **kwargs):
318
+ super().__init__(*args, **kwargs)
319
+
320
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
321
+ # 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.
322
+ # 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).
323
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
324
+
325
+ def forward(
326
+ self,
327
+ hidden_states: torch.Tensor,
328
+ key_value_states: Optional[torch.Tensor] = None,
329
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
330
+ attention_mask: Optional[torch.Tensor] = None,
331
+ layer_head_mask: Optional[torch.Tensor] = None,
332
+ output_attentions: bool = False,
333
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
334
+ """Input shape: Batch x Time x Channel"""
335
+
336
+ # if key_value_states are provided this layer is used as a cross-attention layer
337
+ # for the decoder
338
+ is_cross_attention = key_value_states is not None
339
+
340
+ bsz, _, _ = hidden_states.size()
341
+
342
+ # get query proj
343
+ query_states = self.q_proj(hidden_states)
344
+ # get key, value proj
345
+ if is_cross_attention and past_key_value is not None:
346
+ # reuse k,v, cross_attentions
347
+ key_states = past_key_value[0]
348
+ value_states = past_key_value[1]
349
+ elif is_cross_attention:
350
+ # cross_attentions
351
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
352
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
353
+ elif past_key_value is not None:
354
+ # reuse k, v, self_attention
355
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
356
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
357
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
358
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
359
+ else:
360
+ # self_attention
361
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
362
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
363
+
364
+ if self.is_decoder:
365
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
366
+ # Further calls to cross_attention layer can then reuse all cross-attention
367
+ # key/value_states (first "if" case)
368
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
369
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
370
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
371
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
372
+ past_key_value = (key_states, value_states)
373
+
374
+ query_length = query_states.shape[1]
375
+ tgt_len = key_states.shape[-2]
376
+
377
+ # Flash attention requires the input to have the shape
378
+ # batch_size x seq_length x head_dim x hidden_dim
379
+ query_states = query_states.view(
380
+ bsz, query_length, self.num_heads, self.head_dim)
381
+ key_states = key_states.transpose(1, 2).view(
382
+ bsz, tgt_len, self.num_heads, self.head_dim)
383
+ value_states = value_states.transpose(1, 2).view(
384
+ bsz, tgt_len, self.num_heads, self.head_dim)
385
+
386
+ attn_dropout = self.dropout if self.training else 0.0
387
+
388
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
389
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
390
+ # cast them back in float16 just to be sure everything works as expected.
391
+ input_dtype = query_states.dtype
392
+ if input_dtype == torch.float32:
393
+ if torch.is_autocast_enabled():
394
+ target_dtype = torch.get_autocast_gpu_dtype()
395
+ # Handle the case where the model is quantized
396
+ elif hasattr(self.config, "_pre_quantization_dtype"):
397
+ target_dtype = self.config._pre_quantization_dtype
398
+ else:
399
+ target_dtype = self.q_proj.weight.dtype
400
+
401
+ logger.warning_once(
402
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
403
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
404
+ f" {target_dtype}."
405
+ )
406
+
407
+ query_states = query_states.to(target_dtype)
408
+ key_states = key_states.to(target_dtype)
409
+ value_states = value_states.to(target_dtype)
410
+
411
+ attn_output = self._flash_attention_forward(
412
+ query_states, key_states, value_states, attention_mask, query_length, dropout=attn_dropout
413
+ )
414
+
415
+ attn_weights_reshaped = attn_output.reshape(
416
+ bsz, query_length, self.num_heads * self.head_dim)
417
+ attn_output = self.out_proj(attn_weights_reshaped)
418
+
419
+ if not output_attentions:
420
+ attn_weights_reshaped = None
421
+
422
+ return attn_output, attn_weights_reshaped, past_key_value
423
+
424
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
425
+ def _flash_attention_forward(
426
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
427
+ ):
428
+ """
429
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
430
+ first unpad the input, then computes the attention scores and pad the final attention scores.
431
+
432
+ Args:
433
+ query_states (`torch.Tensor`):
434
+ Input query states to be passed to Flash Attention API
435
+ key_states (`torch.Tensor`):
436
+ Input key states to be passed to Flash Attention API
437
+ value_states (`torch.Tensor`):
438
+ Input value states to be passed to Flash Attention API
439
+ attention_mask (`torch.Tensor`):
440
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
441
+ position of padding tokens and 1 for the position of non-padding tokens.
442
+ dropout (`float`):
443
+ Attention dropout
444
+ softmax_scale (`float`, *optional*):
445
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
446
+ """
447
+ if not self._flash_attn_uses_top_left_mask:
448
+ causal = self.is_causal
449
+ else:
450
+ # 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__.
451
+ causal = self.is_causal and query_length != 1
452
+
453
+ # Contains at least one padding token in the sequence
454
+ if attention_mask is not None:
455
+ batch_size = query_states.shape[0]
456
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
457
+ query_states, key_states, value_states, attention_mask, query_length
458
+ )
459
+
460
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
461
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
462
+
463
+ attn_output_unpad = flash_attn_varlen_func(
464
+ query_states,
465
+ key_states,
466
+ value_states,
467
+ cu_seqlens_q=cu_seqlens_q,
468
+ cu_seqlens_k=cu_seqlens_k,
469
+ max_seqlen_q=max_seqlen_in_batch_q,
470
+ max_seqlen_k=max_seqlen_in_batch_k,
471
+ dropout_p=dropout,
472
+ softmax_scale=softmax_scale,
473
+ causal=causal,
474
+ )
475
+
476
+ attn_output = pad_input(
477
+ attn_output_unpad, indices_q, batch_size, query_length)
478
+ else:
479
+ attn_output = flash_attn_func(
480
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
481
+ )
482
+
483
+ return attn_output
484
+
485
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
486
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
487
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(
488
+ attention_mask)
489
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
490
+
491
+ key_layer = index_first_axis(
492
+ key_layer.reshape(batch_size * kv_seq_len,
493
+ num_key_value_heads, head_dim), indices_k
494
+ )
495
+ value_layer = index_first_axis(
496
+ value_layer.reshape(batch_size * kv_seq_len,
497
+ num_key_value_heads, head_dim), indices_k
498
+ )
499
+ if query_length == kv_seq_len:
500
+ query_layer = index_first_axis(
501
+ query_layer.reshape(batch_size * kv_seq_len,
502
+ self.num_heads, head_dim), indices_k
503
+ )
504
+ cu_seqlens_q = cu_seqlens_k
505
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
506
+ indices_q = indices_k
507
+ elif query_length == 1:
508
+ max_seqlen_in_batch_q = 1
509
+ cu_seqlens_q = torch.arange(
510
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
511
+ ) # There is a memcpy here, that is very bad.
512
+ indices_q = cu_seqlens_q[:-1]
513
+ query_layer = query_layer.squeeze(1)
514
+ else:
515
+ # The -q_len: slice assumes left padding.
516
+ attention_mask = attention_mask[:, -query_length:]
517
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
518
+ query_layer, attention_mask)
519
+
520
+ return (
521
+ query_layer,
522
+ key_layer,
523
+ value_layer,
524
+ indices_q,
525
+ (cu_seqlens_q, cu_seqlens_k),
526
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
527
+ )
528
+
529
+
530
+ OPT_ATTENTION_CLASSES = {
531
+ "eager": OPTAttention,
532
+ "flash_attention_2": OptFlashAttention2,
533
+ }
534
+
535
+
536
+ class OPTDecoderLayer(nn.Module):
537
+ def __init__(self, config: OPTConfig):
538
+ super().__init__()
539
+ self.embed_dim = config.hidden_size
540
+
541
+ self.self_attn = OPTAttention(
542
+ config=config, is_decoder=True)
543
+
544
+ self.do_layer_norm_before = config.do_layer_norm_before
545
+ self.dropout = config.dropout
546
+ self.activation_fn = ACT2FN[config.activation_function]
547
+
548
+ self.self_attn_layer_norm = nn.LayerNorm(
549
+ self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine
550
+ )
551
+ self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim,
552
+ bias=config.enable_bias)
553
+ self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim,
554
+ bias=config.enable_bias)
555
+ self.final_layer_norm = nn.LayerNorm(
556
+ self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine)
557
+
558
+ def forward(
559
+ self,
560
+ hidden_states: torch.Tensor,
561
+ attention_mask: Optional[torch.Tensor] = None,
562
+ layer_head_mask: Optional[torch.Tensor] = None,
563
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
564
+ output_attentions: Optional[bool] = False,
565
+ use_cache: Optional[bool] = False,
566
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
567
+ """
568
+ Args:
569
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
570
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
571
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
572
+ layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size
573
+ `(encoder_attention_heads,)`.
574
+ output_attentions (`bool`, *optional*):
575
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
576
+ returned tensors for more detail.
577
+ use_cache (`bool`, *optional*):
578
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
579
+ (see `past_key_values`).
580
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
581
+ """
582
+
583
+ residual = hidden_states
584
+
585
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
586
+ if self.do_layer_norm_before:
587
+ hidden_states = self.self_attn_layer_norm(hidden_states)
588
+
589
+ # Self Attention
590
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
591
+ hidden_states=hidden_states,
592
+ past_key_value=past_key_value,
593
+ attention_mask=attention_mask,
594
+ layer_head_mask=layer_head_mask,
595
+ output_attentions=output_attentions,
596
+ )
597
+ hidden_states = nn.functional.dropout(
598
+ hidden_states, p=self.dropout, training=self.training)
599
+ hidden_states = residual + hidden_states
600
+
601
+ # 350m applies layer norm AFTER attention
602
+ if not self.do_layer_norm_before:
603
+ hidden_states = self.self_attn_layer_norm(hidden_states)
604
+
605
+ # Fully Connected
606
+ hidden_states_shape = hidden_states.shape
607
+ hidden_states = hidden_states.reshape(-1, hidden_states.size(-1))
608
+ residual = hidden_states
609
+
610
+ # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention
611
+ if self.do_layer_norm_before:
612
+ hidden_states = self.final_layer_norm(hidden_states)
613
+
614
+ hidden_states = self.fc1(hidden_states)
615
+ hidden_states = self.activation_fn(hidden_states)
616
+
617
+ hidden_states = self.fc2(hidden_states)
618
+ hidden_states = nn.functional.dropout(
619
+ hidden_states, p=self.dropout, training=self.training)
620
+
621
+ hidden_states = (residual + hidden_states).view(hidden_states_shape)
622
+
623
+ # 350m applies layer norm AFTER attention
624
+ if not self.do_layer_norm_before:
625
+ hidden_states = self.final_layer_norm(hidden_states)
626
+
627
+ outputs = (hidden_states,)
628
+
629
+ if output_attentions:
630
+ outputs += (self_attn_weights,)
631
+
632
+ if use_cache:
633
+ outputs += (present_key_value,)
634
+
635
+ return outputs
636
+
637
+
638
+ OPT_START_DOCSTRING = r"""
639
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
640
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
641
+ etc.)
642
+
643
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
644
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
645
+ and behavior.
646
+
647
+ Parameters:
648
+ config ([`OPTConfig`]):
649
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
650
+ load the weights associated with the model, only the configuration. Check out the
651
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
652
+ """
653
+
654
+
655
+ @add_start_docstrings(
656
+ "The bare OPT Model outputting raw hidden-states without any specific head on top.",
657
+ OPT_START_DOCSTRING,
658
+ )
659
+ class OPTPreTrainedModel(PreTrainedModel):
660
+ config_class = OPTConfig
661
+ base_model_prefix = "model"
662
+ supports_gradient_checkpointing = True
663
+ _no_split_modules = ["OPTDecoderLayer"]
664
+ _supports_flash_attn_2 = True
665
+
666
+ def _init_weights(self, module):
667
+ std = self.config.init_std
668
+ if isinstance(module, nn.Linear):
669
+ module.weight.data.normal_(mean=0.0, std=std)
670
+ if module.bias is not None:
671
+ module.bias.data.zero_()
672
+ elif isinstance(module, nn.Embedding):
673
+ module.weight.data.normal_(mean=0.0, std=std)
674
+ if module.padding_idx is not None:
675
+ module.weight.data[module.padding_idx].zero_()
676
+
677
+
678
+ OPT_INPUTS_DOCSTRING = r"""
679
+ Args:
680
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
681
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
682
+ it.
683
+
684
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
685
+ [`PreTrainedTokenizer.__call__`] for details.
686
+
687
+ [What are input IDs?](../glossary#input-ids)
688
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
689
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
690
+
691
+ - 1 for tokens that are **not masked**,
692
+ - 0 for tokens that are **masked**.
693
+
694
+ [What are attention masks?](../glossary#attention-mask)
695
+
696
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
697
+ [`PreTrainedTokenizer.__call__`] for details.
698
+
699
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
700
+ `past_key_values`).
701
+
702
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
703
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
704
+ information on the default strategy.
705
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
706
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
707
+
708
+ - 1 indicates the head is **not masked**,
709
+ - 0 indicates the head is **masked**.
710
+
711
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
712
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
713
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
714
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
715
+
716
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
717
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
718
+
719
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
720
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
721
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
722
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
723
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
724
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
725
+ model's internal embedding lookup matrix.
726
+ use_cache (`bool`, *optional*):
727
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
728
+ `past_key_values`).
729
+ output_attentions (`bool`, *optional*):
730
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
731
+ tensors for more detail.
732
+ output_hidden_states (`bool`, *optional*):
733
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
734
+ more detail.
735
+ return_dict (`bool`, *optional*):
736
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
737
+ """
738
+
739
+
740
+ class OPTDecoder(OPTPreTrainedModel):
741
+ """
742
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`]
743
+
744
+ Args:
745
+ config: OPTConfig
746
+ """
747
+
748
+ def __init__(self, config: OPTConfig):
749
+ super().__init__(config)
750
+ self.dropout = config.dropout
751
+ self.layerdrop = config.layerdrop
752
+ self.padding_idx = config.pad_token_id
753
+ self.max_target_positions = config.max_position_embeddings
754
+ self.vocab_size = config.vocab_size
755
+
756
+ self.embed_tokens = nn.Embedding(
757
+ config.vocab_size, config.word_embed_proj_dim, self.padding_idx)
758
+ self.embed_positions = OPTLearnedPositionalEmbedding(
759
+ config.max_position_embeddings, config.hidden_size)
760
+
761
+ if config.word_embed_proj_dim != config.hidden_size:
762
+ self.project_out = nn.Linear(
763
+ config.hidden_size, config.word_embed_proj_dim, bias=False)
764
+ else:
765
+ self.project_out = None
766
+
767
+ if config.word_embed_proj_dim != config.hidden_size:
768
+ self.project_in = nn.Linear(
769
+ config.word_embed_proj_dim, config.hidden_size, bias=False)
770
+ else:
771
+ self.project_in = None
772
+
773
+ # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility
774
+ # with checkpoints that have been fine-tuned before transformers v4.20.1
775
+ # see https://github.com/facebookresearch/metaseq/pull/164
776
+ if config.do_layer_norm_before and not config._remove_final_layer_norm:
777
+ self.final_layer_norm = nn.LayerNorm(
778
+ config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine
779
+ )
780
+ else:
781
+ self.final_layer_norm = None
782
+
783
+ self.layers = nn.ModuleList(
784
+ [OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)])
785
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
786
+
787
+ self.gradient_checkpointing = False
788
+ # Initialize weights and apply final processing
789
+ self.post_init()
790
+
791
+ def get_input_embeddings(self):
792
+ return self.embed_tokens
793
+
794
+ def set_input_embeddings(self, value):
795
+ self.embed_tokens = value
796
+
797
+ def forward(
798
+ self,
799
+ input_ids: torch.LongTensor = None,
800
+ attention_mask: Optional[torch.Tensor] = None,
801
+ head_mask: Optional[torch.Tensor] = None,
802
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
803
+ inputs_embeds: Optional[torch.FloatTensor] = None,
804
+ use_cache: Optional[bool] = None,
805
+ output_attentions: Optional[bool] = None,
806
+ output_hidden_states: Optional[bool] = None,
807
+ return_dict: Optional[bool] = None,
808
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
809
+ r"""
810
+ Args:
811
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
812
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
813
+ provide it.
814
+
815
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
816
+ [`PreTrainedTokenizer.__call__`] for details.
817
+
818
+ [What are input IDs?](../glossary#input-ids)
819
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
820
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
821
+
822
+ - 1 for tokens that are **not masked**,
823
+ - 0 for tokens that are **masked**.
824
+
825
+ [What are attention masks?](../glossary#attention-mask)
826
+ head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*):
827
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
828
+
829
+ - 1 indicates the head is **not masked**,
830
+ - 0 indicates the head is **masked**.
831
+
832
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
833
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
834
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
835
+
836
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
837
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
838
+
839
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
840
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
841
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
842
+
843
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
844
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
845
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
846
+ than the model's internal embedding lookup matrix.
847
+ output_attentions (`bool`, *optional*):
848
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
849
+ returned tensors for more detail.
850
+ output_hidden_states (`bool`, *optional*):
851
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
852
+ for more detail.
853
+ return_dict (`bool`, *optional*):
854
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
855
+ """
856
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
857
+ output_hidden_states = (
858
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
859
+ )
860
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
861
+
862
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
863
+
864
+ # retrieve input_ids and inputs_embeds
865
+ if input_ids is not None and inputs_embeds is not None:
866
+ raise ValueError(
867
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
868
+ elif input_ids is not None:
869
+ input_shape = input_ids.size()
870
+ input_ids = input_ids.view(-1, input_shape[-1])
871
+ elif inputs_embeds is not None:
872
+ input_shape = inputs_embeds.size()[:-1]
873
+ else:
874
+ raise ValueError(
875
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds")
876
+
877
+ if inputs_embeds is None:
878
+ inputs_embeds = self.embed_tokens(input_ids)
879
+
880
+ batch_size, seq_length = input_shape
881
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
882
+ # required mask seq length can be calculated via length of past
883
+ mask_seq_length = past_key_values_length + seq_length
884
+
885
+ # embed positions
886
+ if self._use_flash_attention_2:
887
+ # 2d mask is passed through the layers
888
+ causal_attention_mask = attention_mask if (
889
+ attention_mask is not None and 0 in attention_mask) else None
890
+ attention_mask = (
891
+ torch.ones(batch_size, mask_seq_length,
892
+ device=inputs_embeds.device)
893
+ if attention_mask is None
894
+ else attention_mask
895
+ )
896
+ else:
897
+ # 4d mask is passed through the layers
898
+ if attention_mask is None:
899
+ attention_mask = torch.ones(
900
+ batch_size, mask_seq_length, device=inputs_embeds.device)
901
+ elif attention_mask.shape[1] != mask_seq_length:
902
+ raise ValueError(
903
+ f"The provided attention mask has length {
904
+ attention_mask.shape[1]}, but its length should be "
905
+ f"{mask_seq_length} (sum of the lengths of current and past inputs)"
906
+ )
907
+ causal_attention_mask = _prepare_4d_causal_attention_mask(
908
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
909
+ )
910
+
911
+ pos_embeds = self.embed_positions(
912
+ attention_mask, past_key_values_length)
913
+
914
+ if self.project_in is not None:
915
+ inputs_embeds = self.project_in(inputs_embeds)
916
+
917
+ hidden_states = inputs_embeds + pos_embeds
918
+
919
+ if self.gradient_checkpointing and self.training:
920
+ if use_cache:
921
+ logger.warning_once(
922
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
923
+ )
924
+ use_cache = False
925
+
926
+ # decoder layers
927
+ all_hidden_states = () if output_hidden_states else None
928
+ all_self_attns = () if output_attentions else None
929
+ next_decoder_cache = () if use_cache else None
930
+
931
+ # check if head_mask has a correct number of layers specified if desired
932
+ for attn_mask, mask_name in zip([head_mask], ["head_mask"]):
933
+ if attn_mask is not None:
934
+ if attn_mask.size()[0] != (len(self.layers)):
935
+ raise ValueError(
936
+ f"The `{mask_name}` should be specified for {
937
+ len(self.layers)} layers, but it is for"
938
+ f" {head_mask.size()[0]}."
939
+ )
940
+
941
+ for idx, decoder_layer in enumerate(self.layers):
942
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
943
+ if output_hidden_states:
944
+ all_hidden_states += (hidden_states,)
945
+
946
+ if self.training:
947
+ dropout_probability = torch.rand([])
948
+ if dropout_probability < self.layerdrop:
949
+ continue
950
+
951
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
952
+
953
+ if self.gradient_checkpointing and self.training:
954
+ layer_outputs = self._gradient_checkpointing_func(
955
+ decoder_layer.__call__,
956
+ hidden_states,
957
+ causal_attention_mask,
958
+ head_mask[idx] if head_mask is not None else None,
959
+ None,
960
+ output_attentions,
961
+ use_cache,
962
+ )
963
+ else:
964
+ layer_outputs = decoder_layer(
965
+ hidden_states,
966
+ attention_mask=causal_attention_mask,
967
+ layer_head_mask=(
968
+ head_mask[idx] if head_mask is not None else None),
969
+ past_key_value=past_key_value,
970
+ output_attentions=output_attentions,
971
+ use_cache=use_cache,
972
+ )
973
+
974
+ hidden_states = layer_outputs[0]
975
+
976
+ if use_cache:
977
+ next_decoder_cache += (
978
+ layer_outputs[2 if output_attentions else 1],)
979
+
980
+ if output_attentions:
981
+ all_self_attns += (layer_outputs[1],)
982
+
983
+ if self.final_layer_norm is not None:
984
+ hidden_states = self.final_layer_norm(hidden_states)
985
+
986
+ if self.project_out is not None:
987
+ hidden_states = self.project_out(hidden_states)
988
+
989
+ # add hidden states from the last decoder layer
990
+ if output_hidden_states:
991
+ all_hidden_states += (hidden_states,)
992
+
993
+ next_cache = next_decoder_cache if use_cache else None
994
+ if not return_dict:
995
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
996
+ return BaseModelOutputWithPast(
997
+ last_hidden_state=hidden_states,
998
+ past_key_values=next_cache,
999
+ hidden_states=all_hidden_states,
1000
+ attentions=all_self_attns,
1001
+ )
1002
+
1003
+
1004
+ @add_start_docstrings(
1005
+ "The bare OPT Model outputting raw hidden-states without any specific head on top.",
1006
+ OPT_START_DOCSTRING,
1007
+ )
1008
+ class OPTModel(OPTPreTrainedModel):
1009
+ def __init__(self, config: OPTConfig):
1010
+ super().__init__(config)
1011
+ self.decoder = OPTDecoder(config)
1012
+ # Initialize weights and apply final processing
1013
+ self.post_init()
1014
+
1015
+ def get_input_embeddings(self):
1016
+ return self.decoder.embed_tokens
1017
+
1018
+ def set_input_embeddings(self, value):
1019
+ self.decoder.embed_tokens = value
1020
+
1021
+ def get_decoder(self):
1022
+ return self.decoder
1023
+
1024
+ @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING)
1025
+ @add_code_sample_docstrings(
1026
+ checkpoint=_CHECKPOINT_FOR_DOC,
1027
+ output_type=BaseModelOutputWithPast,
1028
+ config_class=_CONFIG_FOR_DOC,
1029
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
1030
+ )
1031
+ def forward(
1032
+ self,
1033
+ input_ids: torch.LongTensor = None,
1034
+ attention_mask: Optional[torch.Tensor] = None,
1035
+ head_mask: Optional[torch.Tensor] = None,
1036
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1037
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1038
+ use_cache: Optional[bool] = None,
1039
+ output_attentions: Optional[bool] = None,
1040
+ output_hidden_states: Optional[bool] = None,
1041
+ return_dict: Optional[bool] = None,
1042
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1043
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1044
+ output_hidden_states = (
1045
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1046
+ )
1047
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1048
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1049
+
1050
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1051
+ decoder_outputs = self.decoder(
1052
+ input_ids=input_ids,
1053
+ attention_mask=attention_mask,
1054
+ head_mask=head_mask,
1055
+ past_key_values=past_key_values,
1056
+ inputs_embeds=inputs_embeds,
1057
+ use_cache=use_cache,
1058
+ output_attentions=output_attentions,
1059
+ output_hidden_states=output_hidden_states,
1060
+ return_dict=return_dict,
1061
+ )
1062
+
1063
+ if not return_dict:
1064
+ return decoder_outputs
1065
+
1066
+ return BaseModelOutputWithPast(
1067
+ last_hidden_state=decoder_outputs.last_hidden_state,
1068
+ past_key_values=decoder_outputs.past_key_values,
1069
+ hidden_states=decoder_outputs.hidden_states,
1070
+ attentions=decoder_outputs.attentions,
1071
+ )
1072
+
1073
+
1074
+ class OPTForCausalLM(OPTPreTrainedModel):
1075
+ _tied_weights_keys = ["lm_head.weight"]
1076
+
1077
+ def __init__(self, config):
1078
+ super().__init__(config)
1079
+ self.model = OPTModel(config)
1080
+
1081
+ # the lm_head weight is automatically tied to the embed tokens weight
1082
+ self.lm_head = nn.Linear(
1083
+ config.word_embed_proj_dim, config.vocab_size, bias=False)
1084
+
1085
+ # Initialize weights and apply final processing
1086
+ self.post_init()
1087
+
1088
+ def get_input_embeddings(self):
1089
+ return self.model.decoder.embed_tokens
1090
+
1091
+ def set_input_embeddings(self, value):
1092
+ self.model.decoder.embed_tokens = value
1093
+
1094
+ def get_output_embeddings(self):
1095
+ return self.lm_head
1096
+
1097
+ def set_output_embeddings(self, new_embeddings):
1098
+ self.lm_head = new_embeddings
1099
+
1100
+ def set_decoder(self, decoder):
1101
+ self.model.decoder = decoder
1102
+
1103
+ def get_decoder(self):
1104
+ return self.model.decoder
1105
+
1106
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1107
+ def forward(
1108
+ self,
1109
+ input_ids: torch.LongTensor = None,
1110
+ attention_mask: Optional[torch.Tensor] = None,
1111
+ head_mask: Optional[torch.Tensor] = None,
1112
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1113
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1114
+ labels: Optional[torch.LongTensor] = None,
1115
+ use_cache: Optional[bool] = None,
1116
+ output_attentions: Optional[bool] = None,
1117
+ output_hidden_states: Optional[bool] = None,
1118
+ return_dict: Optional[bool] = None,
1119
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1120
+ r"""
1121
+ Args:
1122
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1123
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1124
+ provide it.
1125
+
1126
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1127
+ [`PreTrainedTokenizer.__call__`] for details.
1128
+
1129
+ [What are input IDs?](../glossary#input-ids)
1130
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1131
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1132
+
1133
+ - 1 for tokens that are **not masked**,
1134
+ - 0 for tokens that are **masked**.
1135
+
1136
+ [What are attention masks?](../glossary#attention-mask)
1137
+ head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*):
1138
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1139
+
1140
+ - 1 indicates the head is **not masked**,
1141
+ - 0 indicates the head is **masked**.
1142
+
1143
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1144
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1145
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1146
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
1147
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
1148
+
1149
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1150
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1151
+
1152
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1153
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1154
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1155
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1156
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1157
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1158
+ than the model's internal embedding lookup matrix.
1159
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1160
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1161
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1162
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1163
+ use_cache (`bool`, *optional*):
1164
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1165
+ (see `past_key_values`).
1166
+ output_attentions (`bool`, *optional*):
1167
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1168
+ returned tensors for more detail.
1169
+ output_hidden_states (`bool`, *optional*):
1170
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1171
+ for more detail.
1172
+ return_dict (`bool`, *optional*):
1173
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1174
+
1175
+ Returns:
1176
+
1177
+ Example:
1178
+
1179
+ ```python
1180
+ >>> from transformers import AutoTokenizer, OPTForCausalLM
1181
+
1182
+ >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m")
1183
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
1184
+
1185
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1186
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1187
+
1188
+ >>> # Generate
1189
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1190
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1191
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious. I'm just a little bit of a weirdo."
1192
+ ```"""
1193
+
1194
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1195
+ output_hidden_states = (
1196
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1197
+ )
1198
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1199
+
1200
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1201
+ outputs = self.model.decoder(
1202
+ input_ids=input_ids,
1203
+ attention_mask=attention_mask,
1204
+ head_mask=head_mask,
1205
+ past_key_values=past_key_values,
1206
+ inputs_embeds=inputs_embeds,
1207
+ use_cache=use_cache,
1208
+ output_attentions=output_attentions,
1209
+ output_hidden_states=output_hidden_states,
1210
+ return_dict=return_dict,
1211
+ )
1212
+
1213
+ logits = self.lm_head(outputs[0]).contiguous()
1214
+
1215
+ loss = None
1216
+ if labels is not None:
1217
+ # move labels to correct device to enable model parallelism
1218
+ labels = labels.to(logits.device)
1219
+ # Shift so that tokens < n predict n
1220
+ shift_logits = logits[..., :-1, :].contiguous()
1221
+ shift_labels = labels[..., 1:].contiguous()
1222
+ # Flatten the tokens
1223
+ loss_fct = CrossEntropyLoss()
1224
+ loss = loss_fct(
1225
+ shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
1226
+
1227
+ if not return_dict:
1228
+ output = (logits,) + outputs[1:]
1229
+ return (loss,) + output if loss is not None else output
1230
+
1231
+ return CausalLMOutputWithPast(
1232
+ loss=loss,
1233
+ logits=logits,
1234
+ past_key_values=outputs.past_key_values,
1235
+ hidden_states=outputs.hidden_states,
1236
+ attentions=outputs.attentions,
1237
+ )
1238
+
1239
+ def prepare_inputs_for_generation(
1240
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1241
+ ):
1242
+ if past_key_values is not None:
1243
+ past_length = past_key_values[0][0].shape[2]
1244
+
1245
+ # Some generation methods already pass only the last input ID
1246
+ if input_ids.shape[1] > past_length:
1247
+ remove_prefix_length = past_length
1248
+ else:
1249
+ # Default to old behavior: keep only final ID
1250
+ remove_prefix_length = input_ids.shape[1] - 1
1251
+
1252
+ input_ids = input_ids[:, remove_prefix_length:]
1253
+
1254
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1255
+ if inputs_embeds is not None and past_key_values is None:
1256
+ model_inputs = {"inputs_embeds": inputs_embeds}
1257
+ else:
1258
+ model_inputs = {"input_ids": input_ids}
1259
+
1260
+ model_inputs.update(
1261
+ {
1262
+ "past_key_values": past_key_values,
1263
+ "use_cache": kwargs.get("use_cache"),
1264
+ "attention_mask": attention_mask,
1265
+ }
1266
+ )
1267
+ return model_inputs
1268
+
1269
+ @staticmethod
1270
+ def _reorder_cache(past_key_values, beam_idx):
1271
+ reordered_past = ()
1272
+ for layer_past in past_key_values:
1273
+ reordered_past += (
1274
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device))
1275
+ for past_state in layer_past),
1276
+ )
1277
+ return reordered_past
1278
+
1279
+
1280
+ @add_start_docstrings(
1281
+ """
1282
+ The OPT Model transformer with a sequence classification head on top (linear layer).
1283
+
1284
+ [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1285
+ (e.g. GPT-2) do.
1286
+
1287
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1288
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1289
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1290
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1291
+ each row of the batch).
1292
+ """,
1293
+ OPT_START_DOCSTRING,
1294
+ )
1295
+ class OPTForSequenceClassification(OPTPreTrainedModel):
1296
+ def __init__(self, config: OPTConfig):
1297
+ super().__init__(config)
1298
+ self.num_labels = config.num_labels
1299
+ self.model = OPTModel(config)
1300
+ self.score = nn.Linear(config.word_embed_proj_dim,
1301
+ self.num_labels, bias=False)
1302
+
1303
+ # Initialize weights and apply final processing
1304
+ self.post_init()
1305
+
1306
+ @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING)
1307
+ @add_code_sample_docstrings(
1308
+ checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
1309
+ output_type=SequenceClassifierOutputWithPast,
1310
+ config_class=_CONFIG_FOR_DOC,
1311
+ expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
1312
+ expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
1313
+ )
1314
+ def forward(
1315
+ self,
1316
+ input_ids: Optional[torch.LongTensor] = None,
1317
+ attention_mask: Optional[torch.FloatTensor] = None,
1318
+ head_mask: Optional[torch.FloatTensor] = None,
1319
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1320
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1321
+ labels: Optional[torch.LongTensor] = None,
1322
+ use_cache: Optional[bool] = None,
1323
+ output_attentions: Optional[bool] = None,
1324
+ output_hidden_states: Optional[bool] = None,
1325
+ return_dict: Optional[bool] = None,
1326
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1327
+ r"""
1328
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1329
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1330
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1331
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1332
+ """
1333
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1334
+
1335
+ transformer_outputs = self.model(
1336
+ input_ids,
1337
+ past_key_values=past_key_values,
1338
+ attention_mask=attention_mask,
1339
+ head_mask=head_mask,
1340
+ inputs_embeds=inputs_embeds,
1341
+ use_cache=use_cache,
1342
+ output_attentions=output_attentions,
1343
+ output_hidden_states=output_hidden_states,
1344
+ return_dict=return_dict,
1345
+ )
1346
+ hidden_states = transformer_outputs[0]
1347
+ logits = self.score(hidden_states)
1348
+
1349
+ if input_ids is not None:
1350
+ batch_size, sequence_length = input_ids.shape[:2]
1351
+ else:
1352
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1353
+
1354
+ if self.config.pad_token_id is None:
1355
+ sequence_lengths = -1
1356
+ else:
1357
+ if input_ids is not None:
1358
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1359
+ sequence_lengths = torch.eq(
1360
+ input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1361
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1362
+ sequence_lengths = sequence_lengths.to(logits.device)
1363
+ else:
1364
+ sequence_lengths = -1
1365
+ logger.warning(
1366
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1367
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1368
+ )
1369
+
1370
+ pooled_logits = logits[torch.arange(
1371
+ batch_size, device=logits.device), sequence_lengths]
1372
+
1373
+ loss = None
1374
+ if labels is not None:
1375
+ if self.config.problem_type is None:
1376
+ if self.num_labels == 1:
1377
+ self.config.problem_type = "regression"
1378
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1379
+ self.config.problem_type = "single_label_classification"
1380
+ else:
1381
+ self.config.problem_type = "multi_label_classification"
1382
+
1383
+ if self.config.problem_type == "regression":
1384
+ loss_fct = MSELoss()
1385
+ if self.num_labels == 1:
1386
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1387
+ else:
1388
+ loss = loss_fct(pooled_logits, labels)
1389
+ elif self.config.problem_type == "single_label_classification":
1390
+ loss_fct = CrossEntropyLoss()
1391
+ loss = loss_fct(
1392
+ pooled_logits.view(-1, self.num_labels), labels.view(-1))
1393
+ elif self.config.problem_type == "multi_label_classification":
1394
+ loss_fct = BCEWithLogitsLoss()
1395
+ loss = loss_fct(pooled_logits, labels)
1396
+ if not return_dict:
1397
+ output = (pooled_logits,) + transformer_outputs[1:]
1398
+ return ((loss,) + output) if loss is not None else output
1399
+
1400
+ return SequenceClassifierOutputWithPast(
1401
+ loss=loss,
1402
+ logits=pooled_logits,
1403
+ past_key_values=transformer_outputs.past_key_values,
1404
+ hidden_states=transformer_outputs.hidden_states,
1405
+ attentions=transformer_outputs.attentions,
1406
+ )
1407
+
1408
+ def get_input_embeddings(self):
1409
+ return self.model.decoder.embed_tokens
1410
+
1411
+ def set_input_embeddings(self, value):
1412
+ self.model.decoder.embed_tokens = value
1413
+
1414
+
1415
+ @add_start_docstrings(
1416
+ """
1417
+ The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD
1418
+ (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1419
+ """,
1420
+ OPT_START_DOCSTRING,
1421
+ )
1422
+ class OPTForQuestionAnswering(OPTPreTrainedModel):
1423
+ def __init__(self, config: OPTConfig):
1424
+ super().__init__(config)
1425
+ self.model = OPTModel(config)
1426
+ self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2)
1427
+
1428
+ # Initialize weights and apply final processing
1429
+ self.post_init()
1430
+
1431
+ @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING)
1432
+ @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)
1433
+ def forward(
1434
+ self,
1435
+ input_ids: Optional[torch.LongTensor] = None,
1436
+ attention_mask: Optional[torch.FloatTensor] = None,
1437
+ head_mask: Optional[torch.FloatTensor] = None,
1438
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1439
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1440
+ start_positions: Optional[torch.LongTensor] = None,
1441
+ end_positions: Optional[torch.LongTensor] = None,
1442
+ use_cache: Optional[bool] = None,
1443
+ output_attentions: Optional[bool] = None,
1444
+ output_hidden_states: Optional[bool] = None,
1445
+ return_dict: Optional[bool] = None,
1446
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1447
+ r"""
1448
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1449
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1450
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1451
+ are not taken into account for computing the loss.
1452
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1453
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1454
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1455
+ are not taken into account for computing the loss.
1456
+
1457
+ Returns:
1458
+
1459
+ Example:
1460
+
1461
+ ```python
1462
+ >>> from transformers import AutoTokenizer, OPTForQuestionAnswering
1463
+ >>> import torch
1464
+
1465
+ >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT
1466
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
1467
+
1468
+ >>> # note: we are loading a OPTForQuestionAnswering from the hub here,
1469
+ >>> # so the head will be randomly initialized, hence the predictions will be random
1470
+ >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m")
1471
+
1472
+ >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
1473
+
1474
+ >>> inputs = tokenizer(question, text, return_tensors="pt")
1475
+ >>> with torch.no_grad():
1476
+ ... outputs = model(**inputs)
1477
+
1478
+ >>> answer_start_index = outputs.start_logits.argmax()
1479
+ >>> answer_end_index = outputs.end_logits.argmax()
1480
+
1481
+ >>> answer_offset = len(tokenizer(question)[0])
1482
+
1483
+ >>> predict_answer_tokens = inputs.input_ids[
1484
+ ... 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1
1485
+ ... ]
1486
+ >>> predicted = tokenizer.decode(predict_answer_tokens)
1487
+ >>> predicted
1488
+ ' a nice puppet'
1489
+ ```"""
1490
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1491
+
1492
+ transformer_outputs = self.model(
1493
+ input_ids,
1494
+ past_key_values=past_key_values,
1495
+ attention_mask=attention_mask,
1496
+ head_mask=head_mask,
1497
+ inputs_embeds=inputs_embeds,
1498
+ use_cache=use_cache,
1499
+ output_attentions=output_attentions,
1500
+ output_hidden_states=output_hidden_states,
1501
+ return_dict=return_dict,
1502
+ )
1503
+ hidden_states = transformer_outputs[0]
1504
+
1505
+ logits = self.qa_outputs(hidden_states)
1506
+ start_logits, end_logits = logits.split(1, dim=-1)
1507
+ start_logits = start_logits.squeeze(-1).contiguous()
1508
+ end_logits = end_logits.squeeze(-1).contiguous()
1509
+
1510
+ total_loss = None
1511
+ if start_positions is not None and end_positions is not None:
1512
+ # If we are on multi-GPU, split add a dimension
1513
+ if len(start_positions.size()) > 1:
1514
+ start_positions = start_positions.squeeze(-1)
1515
+ if len(end_positions.size()) > 1:
1516
+ end_positions = end_positions.squeeze(-1)
1517
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1518
+ ignored_index = start_logits.size(1)
1519
+ start_positions = start_positions.clamp(
1520
+ 0, ignored_index).to(logits.device)
1521
+ end_positions = end_positions.clamp(
1522
+ 0, ignored_index).to(logits.device)
1523
+
1524
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1525
+ start_loss = loss_fct(start_logits, start_positions)
1526
+ end_loss = loss_fct(end_logits, end_positions)
1527
+ total_loss = (start_loss + end_loss) / 2
1528
+
1529
+ if not return_dict:
1530
+ output = (start_logits, end_logits) + transformer_outputs[2:]
1531
+ return ((total_loss,) + output) if total_loss is not None else output
1532
+
1533
+ return QuestionAnsweringModelOutput(
1534
+ loss=total_loss,
1535
+ start_logits=start_logits,
1536
+ end_logits=end_logits,
1537
+ hidden_states=transformer_outputs.hidden_states,
1538
+ attentions=transformer_outputs.attentions,
1539
+ )
1540
+
1541
+ def get_input_embeddings(self):
1542
+ return self.model.decoder.embed_tokens
1543
+
1544
+ def set_input_embeddings(self, value):
1545
+ self.model.decoder.embed_tokens = value