d-matrix commited on
Commit
221405c
1 Parent(s): e0518c3

Upload 2 files

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