robinzixuan commited on
Commit
6d903dd
1 Parent(s): 5c9e878

Upload 2 files

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