robinzixuan commited on
Commit
94c71c2
1 Parent(s): 41fa746

Upload 2 files

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