mrapacz commited on
Commit
5974ab8
·
verified ·
1 Parent(s): 0e6184a

Upload MorphT5AutoForConditionalGeneration

Browse files
Files changed (2) hide show
  1. config.json +3 -5
  2. modeling_morph_t5_auto.py +1991 -0
config.json CHANGED
@@ -4,10 +4,8 @@
4
  "MorphT5AutoForConditionalGeneration"
5
  ],
6
  "auto_map": {
7
- "AutoConfig": "morpht5.models.modeling_morph_t5_auto.MorphT5AutoConfig",
8
- "AutoModel": "morpht5.models.modeling_morph_t5_auto.MorphT5AutoModel",
9
- "AutoModelForSeq2SeqLM": "morpht5.models.modeling_morph_t5_auto.MorphT5AutoForConditionalGeneration",
10
- "AutoTokenizer": "MorphT5Tokenizer"
11
  },
12
  "d_ff": 2048,
13
  "d_kv": 64,
@@ -33,7 +31,7 @@
33
  "relative_attention_max_distance": 128,
34
  "relative_attention_num_buckets": 32,
35
  "tie_word_embeddings": false,
36
- "tokenizer_class": "MorphT5Tokenizer",
37
  "torch_dtype": "float32",
38
  "transformers_version": "4.31.0",
39
  "use_cache": true,
 
4
  "MorphT5AutoForConditionalGeneration"
5
  ],
6
  "auto_map": {
7
+ "AutoConfig": "modeling_morph_t5_auto.MorphT5AutoConfig",
8
+ "AutoModel": "modeling_morph_t5_auto.MorphT5AutoForConditionalGeneration"
 
 
9
  },
10
  "d_ff": 2048,
11
  "d_kv": 64,
 
31
  "relative_attention_max_distance": 128,
32
  "relative_attention_num_buckets": 32,
33
  "tie_word_embeddings": false,
34
+ "tokenizer_class": "morpht5.tokenizer.morph_t5_tokenizer.MorphT5Tokenizer",
35
  "torch_dtype": "float32",
36
  "transformers_version": "4.31.0",
37
  "use_cache": true,
modeling_morph_t5_auto.py ADDED
@@ -0,0 +1,1991 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ PyTorch MorphT5Auto model.
16
+
17
+ Copied from transformers.morph.mt5 and adapted for morphological analysis.
18
+ """
19
+
20
+ import copy
21
+ import math
22
+ import os
23
+ import warnings
24
+
25
+ import torch
26
+ from torch import nn
27
+ from torch.nn import CrossEntropyLoss
28
+ from torch.utils.checkpoint import checkpoint
29
+ from transformers import PreTrainedModel, T5Config, add_start_docstrings
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutput,
33
+ BaseModelOutputWithPastAndCrossAttentions,
34
+ Seq2SeqLMOutput,
35
+ Seq2SeqModelOutput,
36
+ )
37
+ from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
38
+ from transformers.utils import (
39
+ DUMMY_INPUTS,
40
+ DUMMY_MASK,
41
+ add_start_docstrings_to_model_forward,
42
+ is_torch_fx_proxy,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ _CONFIG_FOR_DOC = "MorphT5AutoConfig"
51
+ _CHECKPOINT_FOR_DOC = "mt5-small"
52
+
53
+
54
+ PARALLELIZE_DOCSTRING = r"""
55
+ This is an experimental feature and is a subject to change at a moment's notice.
56
+
57
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
58
+ it will evenly distribute blocks across all devices.
59
+
60
+ Args:
61
+ device_map (`Dict[int, list]`, optional, defaults to None):
62
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
63
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
64
+ have fewer attention modules mapped to it than other devices. For reference, the morph t5 morph have the
65
+ following number of attention modules:
66
+
67
+ - mt5-small: 6
68
+ - mt5-base: 12
69
+ - mt5-large: 24
70
+ - mt5-xl: 24
71
+ - mt5-xxl: 24
72
+
73
+ Example:
74
+
75
+ ```python
76
+ # Here is an example of a device map on a machine with 4 GPUs using mt5-xl, which has a total of 24 attention modules:
77
+ model = MorphT5AutoForConditionalGeneration.from_pretrained("mt5-xl")
78
+ device_map = {
79
+ 0: [0, 1, 2],
80
+ 1: [3, 4, 5, 6, 7, 8, 9],
81
+ 2: [10, 11, 12, 13, 14, 15, 16],
82
+ 3: [17, 18, 19, 20, 21, 22, 23],
83
+ }
84
+ model.parallelize(device_map)
85
+ ```
86
+ """
87
+ DEPARALLELIZE_DOCSTRING = r"""
88
+ Moves the model to cpu from a model parallel state.
89
+
90
+ Example:
91
+
92
+ ```python
93
+ # On a 4 GPU machine with mt5-xl:
94
+ model = MorphT5AutoForConditionalGeneration.from_pretrained("Mt5-xl")
95
+ device_map = {
96
+ 0: [0, 1, 2],
97
+ 1: [3, 4, 5, 6, 7, 8, 9],
98
+ 2: [10, 11, 12, 13, 14, 15, 16],
99
+ 3: [17, 18, 19, 20, 21, 22, 23],
100
+ }
101
+ model.parallelize(device_map) # Splits the model across several devices
102
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
103
+ ```
104
+ """
105
+
106
+
107
+ class MorphT5AutoConfig(T5Config):
108
+ model_type = "morph-t5-auto"
109
+
110
+ def __init__(
111
+ self,
112
+ morph_vocabulary_size: int = ...,
113
+ morph_compressed_embedding_size: int = ...,
114
+ **kwargs,
115
+ ):
116
+ super().__init__(**kwargs)
117
+ self.morph_vocabulary_size = morph_vocabulary_size
118
+ self.morph_compressed_embedding_size = morph_compressed_embedding_size
119
+ # Use the full import path
120
+ self.tokenizer_class = "morpht5.tokenizer.morph_t5_tokenizer.MorphT5Tokenizer"
121
+
122
+
123
+ # Copied from transformers.morph.t5.modeling_t5.T5LayerNorm with T5->MorphT5Auto
124
+ class MorphT5AutoLayerNorm(nn.Module):
125
+ def __init__(self, hidden_size, eps=1e-6):
126
+ """
127
+ Construct a layernorm module in the MorphT5Auto style.
128
+
129
+ No bias and no subtraction of mean.
130
+ """
131
+ super().__init__()
132
+ self.weight = nn.Parameter(torch.ones(hidden_size))
133
+ self.variance_epsilon = eps
134
+
135
+ def forward(self, hidden_states):
136
+ # MorphT5Auto uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
137
+ # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus varience is calculated
138
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
139
+ # half-precision inputs is done in fp32
140
+
141
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
142
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
143
+
144
+ # convert into half-precision if necessary
145
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
146
+ hidden_states = hidden_states.to(self.weight.dtype)
147
+
148
+ return self.weight * hidden_states
149
+
150
+
151
+ # Copied from transformers.morph.t5.modeling_t5.T5DenseActDense with T5->MorphT5Auto
152
+ class MorphT5AutoDenseActDense(nn.Module):
153
+ def __init__(self, config: MorphT5AutoConfig):
154
+ super().__init__()
155
+ self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
156
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
157
+ self.dropout = nn.Dropout(config.dropout_rate)
158
+ self.act = ACT2FN[config.dense_act_fn]
159
+
160
+ def forward(self, hidden_states):
161
+ hidden_states = self.wi(hidden_states)
162
+ hidden_states = self.act(hidden_states)
163
+ hidden_states = self.dropout(hidden_states)
164
+ if hidden_states.dtype != self.wo.weight.dtype and self.wo.weight.dtype != torch.int8:
165
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
166
+ hidden_states = self.wo(hidden_states)
167
+ return hidden_states
168
+
169
+
170
+ # Copied from transformers.morph.t5.modeling_t5.T5DenseGatedActDense with T5->MorphT5Auto
171
+ class MorphT5AutoDenseGatedActDense(nn.Module):
172
+ def __init__(self, config: MorphT5AutoConfig):
173
+ super().__init__()
174
+ self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
175
+ self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
176
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
177
+ self.dropout = nn.Dropout(config.dropout_rate)
178
+ self.act = ACT2FN[config.dense_act_fn]
179
+
180
+ def forward(self, hidden_states):
181
+ hidden_gelu = self.act(self.wi_0(hidden_states))
182
+ hidden_linear = self.wi_1(hidden_states)
183
+ hidden_states = hidden_gelu * hidden_linear
184
+ hidden_states = self.dropout(hidden_states)
185
+
186
+ # To make 8bit quantization work for google/flan-t5-xxl, self.wo is kept in float32.
187
+ # See https://github.com/huggingface/transformers/issues/20287
188
+ # we also make sure the weights are not in `int8` in case users will force `_keep_in_fp32_modules` to be `None``
189
+ if hidden_states.dtype != self.wo.weight.dtype and self.wo.weight.dtype != torch.int8:
190
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
191
+
192
+ hidden_states = self.wo(hidden_states)
193
+ return hidden_states
194
+
195
+
196
+ # Copied from transformers.morph.t5.modeling_t5.T5LayerFF with T5->MorphT5Auto
197
+ class MorphT5AutoLayerFF(nn.Module):
198
+ def __init__(self, config: MorphT5AutoConfig):
199
+ super().__init__()
200
+ if config.is_gated_act:
201
+ self.DenseReluDense = MorphT5AutoDenseGatedActDense(config)
202
+ else:
203
+ self.DenseReluDense = MorphT5AutoDenseActDense(config)
204
+
205
+ self.layer_norm = MorphT5AutoLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
206
+ self.dropout = nn.Dropout(config.dropout_rate)
207
+
208
+ def forward(self, hidden_states):
209
+ forwarded_states = self.layer_norm(hidden_states)
210
+ forwarded_states = self.DenseReluDense(forwarded_states)
211
+ hidden_states = hidden_states + self.dropout(forwarded_states)
212
+ return hidden_states
213
+
214
+
215
+ # Copied from transformers.morph.t5.modeling_t5.T5Attention with T5->MorphT5Auto
216
+ class MorphT5AutoAttention(nn.Module):
217
+ def __init__(self, config: MorphT5AutoConfig, has_relative_attention_bias=False):
218
+ super().__init__()
219
+ self.is_decoder = config.is_decoder
220
+ self.has_relative_attention_bias = has_relative_attention_bias
221
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
222
+ self.relative_attention_max_distance = config.relative_attention_max_distance
223
+ self.d_model = config.d_model
224
+ self.key_value_proj_dim = config.d_kv
225
+ self.n_heads = config.num_heads
226
+ self.dropout = config.dropout_rate
227
+ self.inner_dim = self.n_heads * self.key_value_proj_dim
228
+
229
+ # Mesh TensorFlow initialization to avoid scaling before softmax
230
+ self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)
231
+ self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)
232
+ self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)
233
+ self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)
234
+
235
+ if self.has_relative_attention_bias:
236
+ self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
237
+ self.pruned_heads: set[int] = set()
238
+ self.gradient_checkpointing = False
239
+
240
+ def prune_heads(self, heads: list[int]) -> None:
241
+ if len(heads) == 0:
242
+ return
243
+ heads, index = find_pruneable_heads_and_indices(heads, self.n_heads, self.key_value_proj_dim, self.pruned_heads)
244
+ # Prune linear layers
245
+ self.q = prune_linear_layer(self.q, index)
246
+ self.k = prune_linear_layer(self.k, index)
247
+ self.v = prune_linear_layer(self.v, index)
248
+ self.o = prune_linear_layer(self.o, index, dim=1)
249
+ # Update hyper params
250
+ self.n_heads = self.n_heads - len(heads)
251
+ self.inner_dim = self.key_value_proj_dim * self.n_heads
252
+ self.pruned_heads = self.pruned_heads.union(heads)
253
+
254
+ @staticmethod
255
+ def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
256
+ """
257
+ Adapted from Mesh Tensorflow: https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorfl
258
+ ow/transformer/transformer_layers.py#L593.
259
+
260
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
261
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
262
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
263
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
264
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
265
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
266
+
267
+ Args:
268
+ relative_position: an int32 Tensor
269
+ bidirectional: a boolean - whether the attention is bidirectional
270
+ num_buckets: an integer
271
+ max_distance: an integer
272
+
273
+ Returns:
274
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
275
+
276
+ """
277
+ relative_buckets = 0
278
+ if bidirectional:
279
+ num_buckets //= 2
280
+ relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
281
+ relative_position = torch.abs(relative_position)
282
+ else:
283
+ relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
284
+ # now relative_position is in the range [0, inf)
285
+
286
+ # half of the buckets are for exact increments in positions
287
+ max_exact = num_buckets // 2
288
+ is_small = relative_position < max_exact
289
+
290
+ # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
291
+ relative_position_if_large = max_exact + (
292
+ torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact)
293
+ ).to(torch.long)
294
+ relative_position_if_large = torch.min(
295
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
296
+ )
297
+
298
+ relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
299
+ return relative_buckets
300
+
301
+ def compute_bias(self, query_length, key_length, device=None):
302
+ """Compute binned relative position bias."""
303
+ if device is None:
304
+ device = self.relative_attention_bias.weight.device
305
+ context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
306
+ memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
307
+ relative_position = memory_position - context_position # shape (query_length, key_length)
308
+ relative_position_bucket = self._relative_position_bucket(
309
+ relative_position, # shape (query_length, key_length)
310
+ bidirectional=(not self.is_decoder),
311
+ num_buckets=self.relative_attention_num_buckets,
312
+ max_distance=self.relative_attention_max_distance,
313
+ )
314
+ values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
315
+ values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
316
+ return values
317
+
318
+ def forward(
319
+ self,
320
+ hidden_states,
321
+ mask=None,
322
+ key_value_states=None,
323
+ position_bias=None,
324
+ past_key_value=None,
325
+ layer_head_mask=None,
326
+ query_length=None,
327
+ use_cache=False,
328
+ output_attentions=False,
329
+ ):
330
+ """Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states)."""
331
+ # Input is (batch_size, seq_length, dim)
332
+ # Mask is (batch_size, key_length) (non-causal) or (batch_size, key_length, key_length)
333
+ # past_key_value[0] is (batch_size, n_heads, q_len - 1, dim_per_head)
334
+ batch_size, seq_length = hidden_states.shape[:2]
335
+
336
+ real_seq_length = seq_length
337
+
338
+ if past_key_value is not None:
339
+ assert (
340
+ len(past_key_value) == 2
341
+ ), f"past_key_value should have 2 past states: keys and values. Got {len(past_key_value)} past states"
342
+ real_seq_length += past_key_value[0].shape[2] if query_length is None else query_length
343
+
344
+ key_length = real_seq_length if key_value_states is None else key_value_states.shape[1]
345
+
346
+ def shape(states):
347
+ """Projection."""
348
+ return states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
349
+
350
+ def unshape(states):
351
+ """Reshape."""
352
+ return states.transpose(1, 2).contiguous().view(batch_size, -1, self.inner_dim)
353
+
354
+ def project(hidden_states, proj_layer, key_value_states, past_key_value):
355
+ """Projects hidden states correctly to key/query states."""
356
+ if key_value_states is None:
357
+ # self-attn
358
+ # (batch_size, n_heads, seq_length, dim_per_head)
359
+ hidden_states = shape(proj_layer(hidden_states))
360
+ elif past_key_value is None:
361
+ # cross-attn
362
+ # (batch_size, n_heads, seq_length, dim_per_head)
363
+ hidden_states = shape(proj_layer(key_value_states))
364
+
365
+ if past_key_value is not None:
366
+ if key_value_states is None:
367
+ # self-attn
368
+ # (batch_size, n_heads, key_length, dim_per_head)
369
+ hidden_states = torch.cat([past_key_value, hidden_states], dim=2)
370
+ elif past_key_value.shape[2] != key_value_states.shape[1]:
371
+ # checking that the `sequence_length` of the `past_key_value` is the same as
372
+ # the provided `key_value_states` to support prefix tuning
373
+ # cross-attn
374
+ # (batch_size, n_heads, seq_length, dim_per_head)
375
+ hidden_states = shape(proj_layer(key_value_states))
376
+ else:
377
+ # cross-attn
378
+ hidden_states = past_key_value
379
+ return hidden_states
380
+
381
+ # get query states
382
+ query_states = shape(self.q(hidden_states)) # (batch_size, n_heads, seq_length, dim_per_head)
383
+
384
+ # get key/value states
385
+ key_states = project(hidden_states, self.k, key_value_states, past_key_value[0] if past_key_value is not None else None)
386
+ value_states = project(hidden_states, self.v, key_value_states, past_key_value[1] if past_key_value is not None else None)
387
+
388
+ # compute scores
389
+ scores = torch.matmul(
390
+ query_states, key_states.transpose(3, 2)
391
+ ) # equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
392
+
393
+ if position_bias is None:
394
+ if not self.has_relative_attention_bias:
395
+ position_bias = torch.zeros(
396
+ (1, self.n_heads, real_seq_length, key_length), device=scores.device, dtype=scores.dtype
397
+ )
398
+ if self.gradient_checkpointing and self.training:
399
+ position_bias.requires_grad = True
400
+ else:
401
+ position_bias = self.compute_bias(real_seq_length, key_length, device=scores.device)
402
+
403
+ # if key and values are already calculated
404
+ # we want only the last query position bias
405
+ if past_key_value is not None:
406
+ position_bias = position_bias[:, :, -hidden_states.size(1) :, :]
407
+
408
+ if mask is not None:
409
+ position_bias = position_bias + mask # (batch_size, n_heads, seq_length, key_length)
410
+
411
+ if self.pruned_heads:
412
+ mask = torch.ones(position_bias.shape[1])
413
+ mask[list(self.pruned_heads)] = 0
414
+ position_bias_masked = position_bias[:, mask.bool()]
415
+ else:
416
+ position_bias_masked = position_bias
417
+
418
+ scores += position_bias_masked
419
+ attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(
420
+ scores
421
+ ) # (batch_size, n_heads, seq_length, key_length)
422
+ attn_weights = nn.functional.dropout(
423
+ attn_weights, p=self.dropout, training=self.training
424
+ ) # (batch_size, n_heads, seq_length, key_length)
425
+
426
+ # Mask heads if we want to
427
+ if layer_head_mask is not None:
428
+ attn_weights = attn_weights * layer_head_mask
429
+
430
+ attn_output = unshape(torch.matmul(attn_weights, value_states)) # (batch_size, seq_length, dim)
431
+ attn_output = self.o(attn_output)
432
+
433
+ present_key_value_state = (key_states, value_states) if (self.is_decoder and use_cache) else None
434
+ outputs = (attn_output,) + (present_key_value_state,) + (position_bias,)
435
+
436
+ if output_attentions:
437
+ outputs = outputs + (attn_weights,)
438
+ return outputs
439
+
440
+
441
+ # Copied from transformers.morph.t5.modeling_t5.T5LayerSelfAttention with T5->MorphT5Auto
442
+ class MorphT5AutoLayerSelfAttention(nn.Module):
443
+ def __init__(self, config: MorphT5AutoConfig, has_relative_attention_bias=False):
444
+ super().__init__()
445
+ self.SelfAttention = MorphT5AutoAttention(config, has_relative_attention_bias=has_relative_attention_bias)
446
+ self.layer_norm = MorphT5AutoLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
447
+ self.dropout = nn.Dropout(config.dropout_rate)
448
+
449
+ def forward(
450
+ self,
451
+ hidden_states,
452
+ attention_mask=None,
453
+ position_bias=None,
454
+ layer_head_mask=None,
455
+ past_key_value=None,
456
+ use_cache=False,
457
+ output_attentions=False,
458
+ ):
459
+ normed_hidden_states = self.layer_norm(hidden_states)
460
+ attention_output = self.SelfAttention(
461
+ normed_hidden_states,
462
+ mask=attention_mask,
463
+ position_bias=position_bias,
464
+ layer_head_mask=layer_head_mask,
465
+ past_key_value=past_key_value,
466
+ use_cache=use_cache,
467
+ output_attentions=output_attentions,
468
+ )
469
+ hidden_states = hidden_states + self.dropout(attention_output[0])
470
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
471
+ return outputs
472
+
473
+
474
+ # Copied from transformers.morph.t5.modeling_t5.T5LayerCrossAttention with T5->MorphT5Auto
475
+ class MorphT5AutoLayerCrossAttention(nn.Module):
476
+ def __init__(self, config):
477
+ super().__init__()
478
+ self.EncDecAttention = MorphT5AutoAttention(config, has_relative_attention_bias=False)
479
+ self.layer_norm = MorphT5AutoLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
480
+ self.dropout = nn.Dropout(config.dropout_rate)
481
+
482
+ def forward(
483
+ self,
484
+ hidden_states,
485
+ key_value_states,
486
+ attention_mask=None,
487
+ position_bias=None,
488
+ layer_head_mask=None,
489
+ past_key_value=None,
490
+ use_cache=False,
491
+ query_length=None,
492
+ output_attentions=False,
493
+ ):
494
+ normed_hidden_states = self.layer_norm(hidden_states)
495
+ attention_output = self.EncDecAttention(
496
+ normed_hidden_states,
497
+ mask=attention_mask,
498
+ key_value_states=key_value_states,
499
+ position_bias=position_bias,
500
+ layer_head_mask=layer_head_mask,
501
+ past_key_value=past_key_value,
502
+ use_cache=use_cache,
503
+ query_length=query_length,
504
+ output_attentions=output_attentions,
505
+ )
506
+ layer_output = hidden_states + self.dropout(attention_output[0])
507
+ outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
508
+ return outputs
509
+
510
+
511
+ # Copied from transformers.morph.t5.modeling_t5.T5Block with T5->MorphT5Auto
512
+ class MorphT5AutoBlock(nn.Module):
513
+ def __init__(self, config: MorphT5AutoConfig, has_relative_attention_bias=False):
514
+ super().__init__()
515
+ self.is_decoder = config.is_decoder
516
+ self.layer = nn.ModuleList()
517
+ self.layer.append(MorphT5AutoLayerSelfAttention(config, has_relative_attention_bias=has_relative_attention_bias))
518
+ if self.is_decoder:
519
+ self.layer.append(MorphT5AutoLayerCrossAttention(config))
520
+
521
+ self.layer.append(MorphT5AutoLayerFF(config))
522
+
523
+ def forward(
524
+ self,
525
+ hidden_states,
526
+ attention_mask=None,
527
+ position_bias=None,
528
+ encoder_hidden_states=None,
529
+ encoder_attention_mask=None,
530
+ encoder_decoder_position_bias=None,
531
+ layer_head_mask=None,
532
+ cross_attn_layer_head_mask=None,
533
+ past_key_value=None,
534
+ use_cache=False,
535
+ output_attentions=False,
536
+ return_dict=True,
537
+ ):
538
+ if past_key_value is not None:
539
+ if not self.is_decoder:
540
+ logger.warning("`past_key_values` is passed to the encoder. Please make sure this is intended.")
541
+ expected_num_past_key_values = 2 if encoder_hidden_states is None else 4
542
+
543
+ if len(past_key_value) != expected_num_past_key_values:
544
+ raise ValueError(
545
+ f"There should be {expected_num_past_key_values} past states. "
546
+ f"{'2 (past / key) for cross attention. ' if expected_num_past_key_values == 4 else ''}"
547
+ f"Got {len(past_key_value)} past key / value states"
548
+ )
549
+
550
+ self_attn_past_key_value = past_key_value[:2]
551
+ cross_attn_past_key_value = past_key_value[2:]
552
+ else:
553
+ self_attn_past_key_value, cross_attn_past_key_value = None, None
554
+
555
+ self_attention_outputs = self.layer[0](
556
+ hidden_states,
557
+ attention_mask=attention_mask,
558
+ position_bias=position_bias,
559
+ layer_head_mask=layer_head_mask,
560
+ past_key_value=self_attn_past_key_value,
561
+ use_cache=use_cache,
562
+ output_attentions=output_attentions,
563
+ )
564
+ hidden_states, present_key_value_state = self_attention_outputs[:2]
565
+ attention_outputs = self_attention_outputs[2:] # Keep self-attention outputs and relative position weights
566
+
567
+ # clamp inf values to enable fp16 training
568
+ if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
569
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
570
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
571
+
572
+ do_cross_attention = self.is_decoder and encoder_hidden_states is not None
573
+ if do_cross_attention:
574
+ # the actual query length is unknown for cross attention
575
+ # if using past key value states. Need to inject it here
576
+ if present_key_value_state is not None:
577
+ query_length = present_key_value_state[0].shape[2]
578
+ else:
579
+ query_length = None
580
+
581
+ cross_attention_outputs = self.layer[1](
582
+ hidden_states,
583
+ key_value_states=encoder_hidden_states,
584
+ attention_mask=encoder_attention_mask,
585
+ position_bias=encoder_decoder_position_bias,
586
+ layer_head_mask=cross_attn_layer_head_mask,
587
+ past_key_value=cross_attn_past_key_value,
588
+ query_length=query_length,
589
+ use_cache=use_cache,
590
+ output_attentions=output_attentions,
591
+ )
592
+ hidden_states = cross_attention_outputs[0]
593
+
594
+ # clamp inf values to enable fp16 training
595
+ if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
596
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
597
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
598
+
599
+ # Combine self attn and cross attn key value states
600
+ if present_key_value_state is not None:
601
+ present_key_value_state = present_key_value_state + cross_attention_outputs[1]
602
+
603
+ # Keep cross-attention outputs and relative position weights
604
+ attention_outputs = attention_outputs + cross_attention_outputs[2:]
605
+
606
+ # Apply Feed Forward layer
607
+ hidden_states = self.layer[-1](hidden_states)
608
+
609
+ # clamp inf values to enable fp16 training
610
+ if hidden_states.dtype == torch.float16 and torch.isinf(hidden_states).any():
611
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
612
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
613
+
614
+ outputs = (hidden_states,)
615
+
616
+ if use_cache:
617
+ outputs = outputs + (present_key_value_state,) + attention_outputs
618
+ else:
619
+ outputs = outputs + attention_outputs
620
+
621
+ return outputs # hidden-states, present_key_value_states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
622
+
623
+
624
+ def load_tf_weights_in_morph_t5_auto(model, config: MorphT5AutoConfig, tf_checkpoint_path: str):
625
+ """Load tf checkpoints in a pytorch model."""
626
+ try:
627
+ import re
628
+
629
+ import numpy as np
630
+ import tensorflow as tf
631
+ except ImportError:
632
+ logger.error(
633
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
634
+ "https://www.tensorflow.org/install/ for installation instructions."
635
+ )
636
+ raise
637
+ tf_path = os.path.abspath(tf_checkpoint_path)
638
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
639
+ # Load weights from TF model
640
+ init_vars = tf.train.list_variables(tf_path)
641
+ names = []
642
+ tf_weights = {}
643
+ for name, shape in init_vars:
644
+ logger.info(f"Loading TF weight {name} with shape {shape}")
645
+ array = tf.train.load_variable(tf_path, name)
646
+ names.append(name)
647
+ tf_weights[name] = array
648
+
649
+ for txt_name in names:
650
+ name = txt_name.split("/")
651
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
652
+ # which are not required for using pretrained model
653
+ if any(n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name):
654
+ logger.info(f"Skipping {'/'.join(name)}")
655
+ tf_weights.pop(txt_name, None)
656
+ continue
657
+ if "_slot_" in name[-1]:
658
+ logger.info(f"Skipping {'/'.join(name)}")
659
+ tf_weights.pop(txt_name, None)
660
+ continue
661
+ pointer = model
662
+ array = tf_weights[txt_name]
663
+
664
+ for m_name in name:
665
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
666
+ scope_names = re.split(r"_(\d+)", m_name)
667
+ else:
668
+ scope_names = [m_name]
669
+ if scope_names[0] in ["kernel", "scale", "embedding"]:
670
+ pointer = getattr(pointer, "weight")
671
+ elif scope_names[0] == "self_attention":
672
+ pointer = getattr(pointer, "layer")
673
+ pointer = pointer[0]
674
+ elif scope_names[0] == "enc_dec_attention":
675
+ pointer = getattr(pointer, "layer")
676
+ pointer = pointer[1]
677
+ elif scope_names[0] == "dense_relu_dense":
678
+ pointer = getattr(pointer, "layer")
679
+ pointer = pointer[2]
680
+ elif scope_names[0] == "rms_norm":
681
+ if hasattr(pointer, "layer_norm"):
682
+ pointer = getattr(pointer, "layer_norm")
683
+ elif hasattr(pointer, "final_layer_norm"):
684
+ pointer = getattr(pointer, "final_layer_norm")
685
+ elif scope_names[0] == "scale":
686
+ pointer = getattr(pointer, "weight")
687
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
688
+ pointer = getattr(pointer, "bias")
689
+ elif scope_names[0] == "squad":
690
+ pointer = getattr(pointer, "classifier")
691
+ elif scope_names[0] == "decoder" and name[1] == "logits":
692
+ continue
693
+ elif scope_names[0] == "logits":
694
+ pointer = getattr(pointer, "lm_head")
695
+ elif scope_names[0] == "wi" and len(scope_names) > 1 and scope_names[1].isdigit():
696
+ pointer = getattr(pointer, f"wi_{scope_names[1]}")
697
+ continue
698
+ else:
699
+ try:
700
+ pointer = getattr(pointer, scope_names[0])
701
+ except AttributeError:
702
+ logger.info(f"Skipping {'/'.join(name)}")
703
+ continue
704
+ if len(scope_names) >= 2:
705
+ num = int(scope_names[1])
706
+ pointer = pointer[num]
707
+ if scope_names[0] not in ["kernel", "scale", "embedding"]:
708
+ pointer = getattr(pointer, "weight")
709
+ if scope_names[0] != "embedding":
710
+ logger.info(f"Transposing numpy weight of shape {array.shape} for {name}")
711
+ array = np.transpose(array)
712
+ try:
713
+ assert pointer.shape == array.shape, f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
714
+ except AssertionError as e:
715
+ e.args += (pointer.shape, array.shape)
716
+ raise
717
+ logger.info(f"Initialize PyTorch weight {name}")
718
+ pointer.data = torch.from_numpy(array.astype(np.float32))
719
+ tf_weights.pop(txt_name, None)
720
+
721
+ logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}.")
722
+ return model
723
+
724
+
725
+ # Copied from transformers.morph.t5.modeling_t5.T5PreTrainedModel with T5->MorphT5Auto, t5->morph_t5_auto
726
+ class MorphT5AutoPreTrainedModel(PreTrainedModel):
727
+ """An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained morph."""
728
+
729
+ config_class = MorphT5AutoConfig
730
+ load_tf_weights = load_tf_weights_in_morph_t5_auto
731
+ base_model_prefix = "transformer"
732
+ is_parallelizable = True
733
+ supports_gradient_checkpointing = True
734
+ _no_split_modules = ["MorphT5AutoBlock"]
735
+ _keep_in_fp32_modules = ["wo"]
736
+
737
+ @property
738
+ def dummy_inputs(self):
739
+ input_ids = torch.tensor(DUMMY_INPUTS)
740
+ input_mask = torch.tensor(DUMMY_MASK)
741
+ dummy_inputs = {
742
+ "decoder_input_ids": input_ids,
743
+ "input_ids": input_ids,
744
+ "decoder_attention_mask": input_mask,
745
+ }
746
+ return dummy_inputs
747
+
748
+ def _init_weights(self, module):
749
+ """Initialize the weights."""
750
+ factor = self.config.initializer_factor # Used for testing weights initialization
751
+ if isinstance(module, MorphT5AutoLayerNorm):
752
+ module.weight.data.fill_(factor * 1.0)
753
+ elif isinstance(module, (MorphT5AutoModel, MorphT5AutoForConditionalGeneration, MorphT5AutoEncoderModel)):
754
+ # Mesh TensorFlow embeddings initialization
755
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
756
+ module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
757
+ # Morph
758
+ for layer_name, layer in module.encoder.__dict__.items():
759
+ if layer_name.startswith("morph_"):
760
+ layer.weight.data.normal_(mean=0.0, std=factor * 1.0)
761
+
762
+ if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
763
+ module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
764
+ elif isinstance(module, MorphT5AutoDenseActDense):
765
+ # Mesh TensorFlow FF initialization
766
+ # See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
767
+ # and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
768
+ module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
769
+ if hasattr(module.wi, "bias") and module.wi.bias is not None:
770
+ module.wi.bias.data.zero_()
771
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
772
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
773
+ module.wo.bias.data.zero_()
774
+ elif isinstance(module, MorphT5AutoDenseGatedActDense):
775
+ module.wi_0.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
776
+ if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
777
+ module.wi_0.bias.data.zero_()
778
+ module.wi_1.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
779
+ if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
780
+ module.wi_1.bias.data.zero_()
781
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
782
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
783
+ module.wo.bias.data.zero_()
784
+ elif isinstance(module, MorphT5AutoAttention):
785
+ # Mesh TensorFlow attention initialization to avoid scaling before softmax
786
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
787
+ d_model = self.config.d_model
788
+ key_value_proj_dim = self.config.d_kv
789
+ n_heads = self.config.num_heads
790
+ module.q.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
791
+ module.k.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
792
+ module.v.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
793
+ module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
794
+ if module.has_relative_attention_bias:
795
+ module.relative_attention_bias.weight.data.normal_(mean=0.0, std=factor * ((d_model) ** -0.5))
796
+
797
+ def _set_gradient_checkpointing(self, module, value=False):
798
+ if isinstance(module, (MorphT5AutoAttention, MorphT5AutoStack)):
799
+ module.gradient_checkpointing = value
800
+
801
+ def _shift_right(self, input_ids):
802
+ decoder_start_token_id = self.config.decoder_start_token_id
803
+ pad_token_id = self.config.pad_token_id
804
+
805
+ assert decoder_start_token_id is not None, (
806
+ "self.model.config.decoder_start_token_id has to be defined. In MorphT5Auto it is usually set to the pad_token_id."
807
+ " See MorphT5Auto docs for more information"
808
+ )
809
+
810
+ # shift inputs to the right
811
+ if is_torch_fx_proxy(input_ids):
812
+ # Item assignment is not supported natively for proxies.
813
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), decoder_start_token_id)
814
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
815
+ else:
816
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
817
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
818
+ shifted_input_ids[..., 0] = decoder_start_token_id
819
+
820
+ assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined."
821
+ # replace possible -100 values in labels by `pad_token_id`
822
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
823
+
824
+ return shifted_input_ids
825
+
826
+
827
+ # Copied from transformers.morph.t5.modeling_t5.T5Stack with T5->MorphT5Auto
828
+ class MorphT5AutoStack(MorphT5AutoPreTrainedModel):
829
+ def __init__(self, config: MorphT5AutoConfig, embed_tokens=None):
830
+ super().__init__(config)
831
+
832
+ self.embed_tokens = embed_tokens
833
+ self.is_decoder = config.is_decoder
834
+ if not self.is_decoder:
835
+ # Morphs
836
+ self.morph_compress_morphs = nn.Embedding(
837
+ num_embeddings=config.morph_vocabulary_size,
838
+ embedding_dim=config.morph_compressed_embedding_size,
839
+ )
840
+ self.morph_decompress_morphs = nn.Linear(
841
+ config.morph_compressed_embedding_size,
842
+ config.d_model,
843
+ )
844
+
845
+ self.block = nn.ModuleList(
846
+ [MorphT5AutoBlock(config, has_relative_attention_bias=bool(i == 0)) for i in range(config.num_layers)]
847
+ )
848
+ self.final_layer_norm = MorphT5AutoLayerNorm(config.d_model, eps=config.layer_norm_epsilon)
849
+ self.dropout = nn.Dropout(config.dropout_rate)
850
+
851
+ # Initialize weights and apply final processing
852
+ self.post_init()
853
+ # Model parallel
854
+ self.model_parallel = False
855
+ self.device_map = None
856
+ self.gradient_checkpointing = False
857
+
858
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
859
+ def parallelize(self, device_map=None):
860
+ # Check validity of device_map
861
+ self.device_map = get_device_map(len(self.block), range(torch.cuda.device_count())) if device_map is None else device_map
862
+ assert_device_map(self.device_map, len(self.block))
863
+ self.model_parallel = True
864
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
865
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
866
+ # Load onto devices
867
+ for k, v in self.device_map.items():
868
+ for layer in v:
869
+ cuda_device = "cuda:" + str(k)
870
+ self.block[layer] = self.block[layer].to(cuda_device)
871
+
872
+ ### New Embeddings ###
873
+ # Set embed_tokens to first layer
874
+ self.embed_tokens = self.embed_tokens.to(self.first_device)
875
+
876
+ # Morph
877
+ for attr, value in self.__dict__.items():
878
+ if attr.startswith("morph_"):
879
+ logger.info(f"Moving {attr} to {self.first_device}...")
880
+ setattr(self, attr, value.to(self.first_device))
881
+
882
+ # Set final layer norm to last device
883
+ self.final_layer_norm = self.final_layer_norm.to(self.last_device)
884
+
885
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
886
+ def deparallelize(self):
887
+ self.model_parallel = False
888
+ self.device_map = None
889
+ self.first_device = "cpu"
890
+ self.last_device = "cpu"
891
+ for i in range(len(self.block)):
892
+ self.block[i] = self.block[i].to("cpu")
893
+
894
+ ### New Embeddings ###
895
+ self.embed_tokens = self.embed_tokens.to("cpu")
896
+
897
+ # Morph
898
+ for attr, value in self.__dict__.items():
899
+ if attr.startswith("morph_"):
900
+ logger.info(f"Moving {attr} to cpu...")
901
+ setattr(self, attr, value.to("cpu"))
902
+
903
+ self.final_layer_norm = self.final_layer_norm.to("cpu")
904
+ torch.cuda.empty_cache()
905
+
906
+ def get_input_embeddings(self):
907
+ return self.embed_tokens
908
+
909
+ def set_input_embeddings(self, new_embeddings):
910
+ self.embed_tokens = new_embeddings
911
+
912
+ def forward(
913
+ self,
914
+ input_ids: torch.Tensor | None = None,
915
+ input_morphs: torch.Tensor | None = None,
916
+ attention_mask: torch.Tensor | None = None,
917
+ encoder_hidden_states=None,
918
+ encoder_attention_mask=None,
919
+ inputs_embeds=None,
920
+ head_mask=None,
921
+ cross_attn_head_mask=None,
922
+ past_key_values=None,
923
+ use_cache: bool | None = None,
924
+ output_attentions: bool | None = None,
925
+ output_hidden_states: bool | None = None,
926
+ return_dict: bool | None = None,
927
+ ):
928
+ # Model parallel
929
+ if self.model_parallel:
930
+ torch.cuda.set_device(self.first_device)
931
+ self.embed_tokens = self.embed_tokens.to(self.first_device)
932
+
933
+ # Morph
934
+ for attr, value in self.__dict__.items():
935
+ if attr.startswith("morph_"):
936
+ logger.info(f"Moving {attr} to {self.first_device}...")
937
+ setattr(self, attr, value.to(self.first_device))
938
+
939
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
940
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
941
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
942
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
943
+
944
+ if input_ids is not None and inputs_embeds is not None:
945
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
946
+ raise ValueError(
947
+ f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
948
+ )
949
+ elif input_ids is not None:
950
+ if self.is_decoder:
951
+ input_shape = input_ids.size()
952
+ input_ids = input_ids.view(-1, input_shape[-1])
953
+ else:
954
+ input_shape = input_ids.size()
955
+ input_ids = input_ids.view(-1, input_shape[-1])
956
+
957
+ # Morph
958
+ input_morphs = input_morphs.view(-1, input_shape[-1]) # type: ignore[union-attr]
959
+
960
+ elif inputs_embeds is not None:
961
+ input_shape = inputs_embeds.size()[:-1]
962
+ else:
963
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
964
+ raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
965
+
966
+ if inputs_embeds is None:
967
+ assert self.embed_tokens is not None, "You have to initialize the model with valid token embeddings"
968
+ inputs_embeds = self.embed_tokens(input_ids)
969
+ if not self.is_decoder:
970
+ assert input_morphs is not None
971
+ # Morph
972
+ compressed_morphs = self.morph_compress_morphs(input_morphs)
973
+ decompressed_morphs = self.morph_decompress_morphs(compressed_morphs)
974
+ inputs_embeds += decompressed_morphs
975
+ batch_size, seq_length = input_shape
976
+
977
+ # required mask seq length can be calculated via length of past
978
+ mask_seq_length = past_key_values[0][0].shape[2] + seq_length if past_key_values is not None else seq_length
979
+
980
+ if use_cache is True:
981
+ assert self.is_decoder, f"`use_cache` can only be set to `True` if {self} is used as a decoder"
982
+
983
+ if attention_mask is None:
984
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
985
+ if self.is_decoder and encoder_attention_mask is None and encoder_hidden_states is not None:
986
+ encoder_seq_length = encoder_hidden_states.shape[1]
987
+ encoder_attention_mask = torch.ones(batch_size, encoder_seq_length, device=inputs_embeds.device, dtype=torch.long)
988
+
989
+ # initialize past_key_values with `None` if past does not exist
990
+ if past_key_values is None:
991
+ past_key_values = [None] * len(self.block)
992
+
993
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
994
+ # ourselves in which case we just need to make it broadcastable to all heads.
995
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
996
+
997
+ # If a 2D or 3D attention mask is provided for the cross-attention
998
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
999
+ if self.is_decoder and encoder_hidden_states is not None:
1000
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1001
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1002
+ if encoder_attention_mask is None:
1003
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=inputs_embeds.device)
1004
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1005
+ else:
1006
+ encoder_extended_attention_mask = None
1007
+
1008
+ # Prepare head mask if needed
1009
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
1010
+ cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)
1011
+ present_key_value_states = () if use_cache else None
1012
+ all_hidden_states = () if output_hidden_states else None
1013
+ all_attentions = () if output_attentions else None
1014
+ all_cross_attentions = () if (output_attentions and self.is_decoder) else None
1015
+ position_bias = None
1016
+ encoder_decoder_position_bias = None
1017
+
1018
+ hidden_states = self.dropout(inputs_embeds)
1019
+
1020
+ for i, (layer_module, past_key_value) in enumerate(zip(self.block, past_key_values)):
1021
+ layer_head_mask = head_mask[i]
1022
+ cross_attn_layer_head_mask = cross_attn_head_mask[i]
1023
+ # Model parallel
1024
+ if self.model_parallel:
1025
+ torch.cuda.set_device(hidden_states.device)
1026
+ # Ensure that attention_mask is always on the same device as hidden_states
1027
+ if attention_mask is not None:
1028
+ attention_mask = attention_mask.to(hidden_states.device)
1029
+ if position_bias is not None:
1030
+ position_bias = position_bias.to(hidden_states.device)
1031
+ if encoder_hidden_states is not None:
1032
+ encoder_hidden_states = encoder_hidden_states.to(hidden_states.device)
1033
+ if encoder_extended_attention_mask is not None:
1034
+ encoder_extended_attention_mask = encoder_extended_attention_mask.to(hidden_states.device)
1035
+ if encoder_decoder_position_bias is not None:
1036
+ encoder_decoder_position_bias = encoder_decoder_position_bias.to(hidden_states.device)
1037
+ if layer_head_mask is not None:
1038
+ layer_head_mask = layer_head_mask.to(hidden_states.device)
1039
+ if cross_attn_layer_head_mask is not None:
1040
+ cross_attn_layer_head_mask = cross_attn_layer_head_mask.to(hidden_states.device)
1041
+ if output_hidden_states:
1042
+ all_hidden_states = all_hidden_states + (hidden_states,) # type: ignore
1043
+
1044
+ if self.gradient_checkpointing and self.training:
1045
+ if use_cache:
1046
+ logger.warning("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
1047
+ use_cache = False
1048
+
1049
+ def create_custom_forward(module):
1050
+ def custom_forward(*inputs):
1051
+ return tuple(module(*inputs, use_cache, output_attentions))
1052
+
1053
+ return custom_forward
1054
+
1055
+ layer_outputs = checkpoint(
1056
+ create_custom_forward(layer_module),
1057
+ hidden_states,
1058
+ extended_attention_mask,
1059
+ position_bias,
1060
+ encoder_hidden_states,
1061
+ encoder_extended_attention_mask,
1062
+ encoder_decoder_position_bias,
1063
+ layer_head_mask,
1064
+ cross_attn_layer_head_mask,
1065
+ None, # past_key_value is always None with gradient checkpointing
1066
+ )
1067
+ else:
1068
+ layer_outputs = layer_module(
1069
+ hidden_states,
1070
+ attention_mask=extended_attention_mask,
1071
+ position_bias=position_bias,
1072
+ encoder_hidden_states=encoder_hidden_states,
1073
+ encoder_attention_mask=encoder_extended_attention_mask,
1074
+ encoder_decoder_position_bias=encoder_decoder_position_bias,
1075
+ layer_head_mask=layer_head_mask,
1076
+ cross_attn_layer_head_mask=cross_attn_layer_head_mask,
1077
+ past_key_value=past_key_value,
1078
+ use_cache=use_cache,
1079
+ output_attentions=output_attentions,
1080
+ )
1081
+
1082
+ # layer_outputs is a tuple with:
1083
+ # hidden-states, key-value-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
1084
+ if use_cache is False:
1085
+ layer_outputs = layer_outputs[:1] + (None,) + layer_outputs[1:]
1086
+
1087
+ hidden_states, present_key_value_state = layer_outputs[:2]
1088
+
1089
+ # We share the position biases between the layers - the first layer store them
1090
+ # layer_outputs = hidden-states, key-value-states (self-attention position bias), (self-attention weights),
1091
+ # (cross-attention position bias), (cross-attention weights)
1092
+ position_bias = layer_outputs[2]
1093
+ if self.is_decoder and encoder_hidden_states is not None:
1094
+ encoder_decoder_position_bias = layer_outputs[4 if output_attentions else 3]
1095
+ # append next layer key value states
1096
+ if use_cache:
1097
+ present_key_value_states = present_key_value_states + (present_key_value_state,) # type: ignore
1098
+
1099
+ if output_attentions:
1100
+ all_attentions = all_attentions + (layer_outputs[3],) # type: ignore
1101
+ if self.is_decoder:
1102
+ all_cross_attentions = all_cross_attentions + (layer_outputs[5],) # type: ignore
1103
+
1104
+ # Model Parallel: If it's the last layer for that device, put things on the next device
1105
+ if self.model_parallel:
1106
+ for k, v in self.device_map.items():
1107
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
1108
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1109
+
1110
+ hidden_states = self.final_layer_norm(hidden_states)
1111
+ hidden_states = self.dropout(hidden_states)
1112
+
1113
+ # Add last layer
1114
+ if output_hidden_states:
1115
+ all_hidden_states = all_hidden_states + (hidden_states,) # type: ignore
1116
+
1117
+ if not return_dict:
1118
+ return tuple(
1119
+ v
1120
+ for v in [
1121
+ hidden_states,
1122
+ present_key_value_states,
1123
+ all_hidden_states,
1124
+ all_attentions,
1125
+ all_cross_attentions,
1126
+ ]
1127
+ if v is not None
1128
+ )
1129
+ return BaseModelOutputWithPastAndCrossAttentions(
1130
+ last_hidden_state=hidden_states,
1131
+ past_key_values=present_key_value_states,
1132
+ hidden_states=all_hidden_states,
1133
+ attentions=all_attentions,
1134
+ cross_attentions=all_cross_attentions,
1135
+ )
1136
+
1137
+
1138
+ MorphT5Auto_START_DOCSTRING = r"""
1139
+
1140
+ The MorphT5Auto model was proposed in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text
1141
+ Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan
1142
+ Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu. It's an encoder decoder transformer pre-trained in a
1143
+ text-to-text denoising generative setting.
1144
+
1145
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1146
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1147
+ etc.)
1148
+
1149
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1150
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1151
+ and behavior.
1152
+
1153
+ Parameters:
1154
+ config ([`MorphT5AutoConfig`]): Model configuration class with all the parameters of the model.
1155
+ Initializing with a config file does not load the weights associated with the model, only the
1156
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1157
+ """
1158
+
1159
+ MORPH_T5_AUTO_INPUTS_DOCSTRING = r"""
1160
+ Args:
1161
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1162
+ Indices of input sequence tokens in the vocabulary. MorphT5Auto is a model with relative position embeddings so you
1163
+ should be able to pad the inputs on both the right and the left.
1164
+
1165
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1166
+ [`PreTrainedTokenizer.__call__`] for detail.
1167
+
1168
+ [What are input IDs?](../glossary#input-ids)
1169
+
1170
+ To know more on how to prepare `input_ids` for pretraining take a look a [MorphT5Auto Training](./morph_t5_auto#training).
1171
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1172
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1173
+
1174
+ - 1 for tokens that are **not masked**,
1175
+ - 0 for tokens that are **masked**.
1176
+
1177
+ [What are attention masks?](../glossary#attention-mask)
1178
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1179
+ Indices of decoder input sequence tokens in the vocabulary.
1180
+
1181
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1182
+ [`PreTrainedTokenizer.__call__`] for details.
1183
+
1184
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1185
+
1186
+ MorphT5Auto uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1187
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1188
+
1189
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [MorphT5Auto
1190
+ Training](./morph_t5_auto#training).
1191
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1192
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1193
+ be used by default.
1194
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1195
+ Mask to nullify selected heads of the self-attention modules in the encoder. Mask values selected in `[0,
1196
+ 1]`:
1197
+
1198
+ - 1 indicates the head is **not masked**,
1199
+ - 0 indicates the head is **masked**.
1200
+
1201
+ decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1202
+ Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
1203
+ 1]`:
1204
+
1205
+ - 1 indicates the head is **not masked**,
1206
+ - 0 indicates the head is **masked**.
1207
+
1208
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1209
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
1210
+ `[0, 1]`:
1211
+
1212
+ - 1 indicates the head is **not masked**,
1213
+ - 0 indicates the head is **masked**.
1214
+
1215
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
1216
+ Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
1217
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
1218
+ the output of the last layer of the encoder. Used in the cross-attention of the decoder.
1219
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1220
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1221
+
1222
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1223
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1224
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1225
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1226
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1227
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1228
+ model's internal embedding lookup matrix.
1229
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
1230
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
1231
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
1232
+ input (see `past_key_values`). This is useful if you want more control over how to convert
1233
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
1234
+
1235
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
1236
+ of `inputs_embeds`.
1237
+
1238
+ use_cache (`bool`, *optional*):
1239
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1240
+ `past_key_values`).
1241
+
1242
+ output_attentions (`bool`, *optional*):
1243
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1244
+ tensors for more detail.
1245
+ output_hidden_states (`bool`, *optional*):
1246
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1247
+ more detail.
1248
+ return_dict (`bool`, *optional*):
1249
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1250
+ """
1251
+
1252
+ MORPH_T5_AUTO_ENCODER_INPUTS_DOCSTRING = r"""
1253
+ Args:
1254
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1255
+ Indices of input sequence tokens in the vocabulary. MorphT5Auto is a model with relative position embeddings so you
1256
+ should be able to pad the inputs on both the right and the left.
1257
+
1258
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1259
+ [`PreTrainedTokenizer.__call__`] for detail.
1260
+
1261
+ To know more on how to prepare `input_ids` for pretraining take a look a [MorphT5Auto Training](./morph_t5_auto#training).
1262
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1263
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1264
+
1265
+ - 1 for tokens that are **not masked**,
1266
+ - 0 for tokens that are **masked**.
1267
+
1268
+ [What are attention masks?](../glossary#attention-mask)
1269
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1270
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1271
+
1272
+ - 1 indicates the head is **not masked**,
1273
+ - 0 indicates the head is **masked**.
1274
+
1275
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1276
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1277
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1278
+ model's internal embedding lookup matrix.
1279
+ output_attentions (`bool`, *optional*):
1280
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1281
+ tensors for more detail.
1282
+ output_hidden_states (`bool`, *optional*):
1283
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1284
+ more detail.
1285
+ return_dict (`bool`, *optional*):
1286
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1287
+ """
1288
+
1289
+ # Warning message for FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
1290
+ __HEAD_MASK_WARNING_MSG = """
1291
+ The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
1292
+ `decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
1293
+ If you do not want to use any `decoder_head_mask` now, please set `decoder_head_mask = torch.ones(num_layers,
1294
+ num_heads)`.
1295
+ """
1296
+
1297
+
1298
+ @add_start_docstrings(
1299
+ "The bare MorphT5Auto Model transformer outputting raw hidden-states without any specific head on top.",
1300
+ MorphT5Auto_START_DOCSTRING,
1301
+ )
1302
+ class MorphT5AutoModel(MorphT5AutoPreTrainedModel):
1303
+ r"""
1304
+ Examples:
1305
+ ```python
1306
+ >>> from transformers import MorphT5AutoModel, AutoTokenizer
1307
+
1308
+ >>> model = MorphT5AutoModel.from_pretrained("google/mt5-small")
1309
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
1310
+ >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
1311
+ >>> summary = "Weiter Verhandlung in Syrien."
1312
+ >>> inputs = tokenizer(article, return_tensors="pt")
1313
+ >>> labels = tokenizer(text_target=summary, return_tensors="pt")
1314
+
1315
+ >>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=labels["input_ids"])
1316
+ >>> hidden_states = outputs.last_hidden_state
1317
+
1318
+ ```
1319
+
1320
+ """
1321
+
1322
+ model_type = "morph-t5-auto"
1323
+ config_class = MorphT5AutoConfig
1324
+ _keys_to_ignore_on_load_missing = [
1325
+ r"encoder.embed_tokens.weight",
1326
+ r"decoder.embed_tokens.weight",
1327
+ r"decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
1328
+ ]
1329
+ _keys_to_ignore_on_save = [
1330
+ r"encoder.embed_tokens.weight",
1331
+ r"decoder.embed_tokens.weight",
1332
+ ]
1333
+ _keys_to_ignore_on_load_unexpected = [
1334
+ r"decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
1335
+ ]
1336
+
1337
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.__init__ with T5->MorphT5Auto
1338
+ def __init__(self, config: MorphT5AutoConfig):
1339
+ super().__init__(config)
1340
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1341
+
1342
+ encoder_config = copy.deepcopy(config)
1343
+ encoder_config.is_decoder = False
1344
+ encoder_config.use_cache = False
1345
+ encoder_config.is_encoder_decoder = False
1346
+ self.encoder = MorphT5AutoStack(encoder_config, self.shared)
1347
+
1348
+ decoder_config = copy.deepcopy(config)
1349
+ decoder_config.is_decoder = True
1350
+ decoder_config.is_encoder_decoder = False
1351
+ decoder_config.num_layers = config.num_decoder_layers
1352
+ self.decoder = MorphT5AutoStack(decoder_config, self.shared)
1353
+
1354
+ # Initialize weights and apply final processing
1355
+ self.post_init()
1356
+
1357
+ # Model parallel
1358
+ self.model_parallel = False
1359
+ self.device_map = None
1360
+
1361
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1362
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.parallelize
1363
+ def parallelize(self, device_map=None):
1364
+ self.device_map = (
1365
+ get_device_map(len(self.encoder.block), range(torch.cuda.device_count())) if device_map is None else device_map
1366
+ )
1367
+ assert_device_map(self.device_map, len(self.encoder.block))
1368
+ self.encoder.parallelize(self.device_map)
1369
+ self.decoder.parallelize(self.device_map)
1370
+ self.model_parallel = True
1371
+
1372
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1373
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.deparallelize
1374
+ def deparallelize(self):
1375
+ self.encoder.deparallelize()
1376
+ self.decoder.deparallelize()
1377
+ self.encoder = self.encoder.to("cpu")
1378
+ self.decoder = self.decoder.to("cpu")
1379
+ self.model_parallel = False
1380
+ self.device_map = None
1381
+ torch.cuda.empty_cache()
1382
+
1383
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.get_input_embeddings
1384
+ def get_input_embeddings(self):
1385
+ return self.shared
1386
+
1387
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.set_input_embeddings
1388
+ def set_input_embeddings(self, new_embeddings):
1389
+ self.shared = new_embeddings
1390
+ self.encoder.set_input_embeddings(new_embeddings)
1391
+ self.decoder.set_input_embeddings(new_embeddings)
1392
+
1393
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.get_encoder
1394
+ def get_encoder(self):
1395
+ return self.encoder
1396
+
1397
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.get_decoder
1398
+ def get_decoder(self):
1399
+ return self.decoder
1400
+
1401
+ # Copied from transformers.morph.t5.modeling_t5.T5Model._prune_heads
1402
+ def _prune_heads(self, heads_to_prune):
1403
+ """
1404
+ Prunes heads of the model.
1405
+
1406
+ heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1407
+ class PreTrainedModel
1408
+ """
1409
+ for layer, heads in heads_to_prune.items():
1410
+ self.encoder.layer[layer].attention.prune_heads(heads)
1411
+
1412
+ @add_start_docstrings_to_model_forward(MORPH_T5_AUTO_INPUTS_DOCSTRING)
1413
+ @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
1414
+ # Copied from transformers.morph.t5.modeling_t5.T5Model.forward with T5->MorphT5Auto, t5->morph_t5_auto
1415
+ def forward(
1416
+ self,
1417
+ input_ids: torch.LongTensor | None = None,
1418
+ attention_mask: torch.FloatTensor | None = None,
1419
+ decoder_input_ids: torch.LongTensor | None = None,
1420
+ decoder_attention_mask: torch.BoolTensor | None = None,
1421
+ head_mask: torch.FloatTensor | None = None,
1422
+ decoder_head_mask: torch.FloatTensor | None = None,
1423
+ cross_attn_head_mask: torch.Tensor | None = None,
1424
+ encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
1425
+ past_key_values: tuple[tuple[torch.FloatTensor]] | None = None,
1426
+ inputs_embeds: torch.Tensor | None = None,
1427
+ decoder_inputs_embeds: torch.Tensor | None = None,
1428
+ use_cache: bool | None = None,
1429
+ output_attentions: bool | None = None,
1430
+ output_hidden_states: bool | None = None,
1431
+ return_dict: bool | None = None,
1432
+ ) -> tuple[torch.FloatTensor] | Seq2SeqModelOutput:
1433
+ r"""
1434
+ Returns:
1435
+
1436
+ Example:
1437
+ ```python
1438
+ >>> from transformers import AutoTokenizer, MorphT5AutoModel
1439
+
1440
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
1441
+ >>> model = MorphT5AutoModel.from_pretrained("google/mt5-small")
1442
+
1443
+ >>> input_ids = tokenizer(
1444
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1445
+ ... ).input_ids # Batch size 1
1446
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
1447
+
1448
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for MorphT5AutoModel.
1449
+ >>> # This is not needed for torch's MorphT5AutoForConditionalGeneration as it does this internally using labels arg.
1450
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
1451
+
1452
+ >>> # forward pass
1453
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
1454
+ >>> last_hidden_states = outputs.last_hidden_state
1455
+
1456
+ ```
1457
+
1458
+ """
1459
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1460
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1461
+
1462
+ # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
1463
+ if head_mask is not None and decoder_head_mask is None:
1464
+ if self.config.num_layers == self.config.num_decoder_layers:
1465
+ warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
1466
+ decoder_head_mask = head_mask
1467
+
1468
+ # Encode if needed (training, first prediction pass)
1469
+ if encoder_outputs is None:
1470
+ encoder_outputs = self.encoder(
1471
+ input_ids=input_ids,
1472
+ attention_mask=attention_mask,
1473
+ inputs_embeds=inputs_embeds,
1474
+ head_mask=head_mask,
1475
+ output_attentions=output_attentions,
1476
+ output_hidden_states=output_hidden_states,
1477
+ return_dict=return_dict,
1478
+ )
1479
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1480
+ encoder_outputs = BaseModelOutput(
1481
+ last_hidden_state=encoder_outputs[0],
1482
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, # type: ignore[misc]
1483
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None, # type: ignore[misc]
1484
+ )
1485
+
1486
+ hidden_states = encoder_outputs[0] # type: ignore
1487
+
1488
+ # Set device for model parallelism
1489
+ if self.model_parallel:
1490
+ torch.cuda.set_device(self.decoder.first_device)
1491
+ hidden_states = hidden_states.to(self.decoder.first_device) # type: ignore[union-attr]
1492
+ if decoder_input_ids is not None:
1493
+ decoder_input_ids = decoder_input_ids.to(self.decoder.first_device)
1494
+ if attention_mask is not None:
1495
+ attention_mask = attention_mask.to(self.decoder.first_device)
1496
+ if decoder_attention_mask is not None:
1497
+ decoder_attention_mask = decoder_attention_mask.to(self.decoder.first_device)
1498
+
1499
+ # Decode
1500
+ decoder_outputs = self.decoder(
1501
+ input_ids=decoder_input_ids,
1502
+ attention_mask=decoder_attention_mask,
1503
+ inputs_embeds=decoder_inputs_embeds,
1504
+ past_key_values=past_key_values,
1505
+ encoder_hidden_states=hidden_states,
1506
+ encoder_attention_mask=attention_mask,
1507
+ head_mask=decoder_head_mask,
1508
+ cross_attn_head_mask=cross_attn_head_mask,
1509
+ use_cache=use_cache,
1510
+ output_attentions=output_attentions,
1511
+ output_hidden_states=output_hidden_states,
1512
+ return_dict=return_dict,
1513
+ )
1514
+
1515
+ if not return_dict:
1516
+ return decoder_outputs + encoder_outputs
1517
+
1518
+ return Seq2SeqModelOutput(
1519
+ last_hidden_state=decoder_outputs.last_hidden_state,
1520
+ past_key_values=decoder_outputs.past_key_values,
1521
+ decoder_hidden_states=decoder_outputs.hidden_states,
1522
+ decoder_attentions=decoder_outputs.attentions,
1523
+ cross_attentions=decoder_outputs.cross_attentions,
1524
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state, # type: ignore[union-attr]
1525
+ encoder_hidden_states=encoder_outputs.hidden_states, # type: ignore[union-attr]
1526
+ encoder_attentions=encoder_outputs.attentions, # type: ignore[union-attr]
1527
+ )
1528
+
1529
+
1530
+ @add_start_docstrings("""MorphT5Auto Model with a `language modeling` head on top.""", MorphT5Auto_START_DOCSTRING)
1531
+ class MorphT5AutoForConditionalGeneration(MorphT5AutoPreTrainedModel):
1532
+ r"""
1533
+ Examples:
1534
+ ```python
1535
+ >>> from transformers import MorphT5AutoForConditionalGeneration, AutoTokenizer
1536
+
1537
+ >>> model = MorphT5AutoForConditionalGeneration.from_pretrained("google/mt5-small")
1538
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
1539
+ >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
1540
+ >>> summary = "Weiter Verhandlung in Syrien."
1541
+ >>> inputs = tokenizer(article, text_target=summary, return_tensors="pt")
1542
+
1543
+ >>> outputs = model(**inputs)
1544
+ >>> loss = outputs.loss
1545
+
1546
+ ```
1547
+
1548
+ """
1549
+
1550
+ model_type = "morph-t5-auto"
1551
+ config_class = MorphT5AutoConfig
1552
+ _keys_to_ignore_on_load_missing = [
1553
+ r"encoder.embed_tokens.weight",
1554
+ ]
1555
+ _keys_to_ignore_on_save = [
1556
+ r"encoder.embed_tokens.weight",
1557
+ ]
1558
+ _keys_to_ignore_on_load_unexpected = [
1559
+ r"decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
1560
+ ]
1561
+
1562
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.__init__ with T5->MorphT5Auto
1563
+ def __init__(self, config: MorphT5AutoConfig):
1564
+ super().__init__(config)
1565
+ self.model_dim = config.d_model
1566
+
1567
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1568
+
1569
+ encoder_config = copy.deepcopy(config)
1570
+ encoder_config.is_decoder = False
1571
+ encoder_config.use_cache = False
1572
+ encoder_config.is_encoder_decoder = False
1573
+ self.encoder = MorphT5AutoStack(encoder_config, embed_tokens=self.shared)
1574
+
1575
+ decoder_config = copy.deepcopy(config)
1576
+ decoder_config.is_decoder = True
1577
+ decoder_config.is_encoder_decoder = False
1578
+ decoder_config.num_layers = config.num_decoder_layers
1579
+ self.decoder = MorphT5AutoStack(decoder_config, embed_tokens=self.shared)
1580
+
1581
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
1582
+
1583
+ # Initialize weights and apply final processing
1584
+ self.post_init()
1585
+
1586
+ # Model parallel
1587
+ self.model_parallel = False
1588
+ self.device_map = None
1589
+
1590
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1591
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.parallelize
1592
+ def parallelize(self, device_map=None):
1593
+ self.device_map = (
1594
+ get_device_map(len(self.encoder.block), range(torch.cuda.device_count())) if device_map is None else device_map
1595
+ )
1596
+ assert_device_map(self.device_map, len(self.encoder.block))
1597
+ self.encoder.parallelize(self.device_map)
1598
+ self.decoder.parallelize(self.device_map)
1599
+ self.lm_head = self.lm_head.to(self.decoder.first_device)
1600
+ self.model_parallel = True
1601
+
1602
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1603
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.deparallelize
1604
+ def deparallelize(self):
1605
+ self.encoder.deparallelize()
1606
+ self.decoder.deparallelize()
1607
+ self.encoder = self.encoder.to("cpu")
1608
+ self.decoder = self.decoder.to("cpu")
1609
+ self.lm_head = self.lm_head.to("cpu")
1610
+ self.model_parallel = False
1611
+ self.device_map = None
1612
+ torch.cuda.empty_cache()
1613
+
1614
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.get_input_embeddings
1615
+ def get_input_embeddings(self):
1616
+ return self.shared
1617
+
1618
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.set_input_embeddings
1619
+ def set_input_embeddings(self, new_embeddings):
1620
+ self.shared = new_embeddings
1621
+ self.encoder.set_input_embeddings(new_embeddings)
1622
+ self.decoder.set_input_embeddings(new_embeddings)
1623
+
1624
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.set_output_embeddings
1625
+ def set_output_embeddings(self, new_embeddings):
1626
+ self.lm_head = new_embeddings
1627
+
1628
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.get_output_embeddings
1629
+ def get_output_embeddings(self):
1630
+ return self.lm_head
1631
+
1632
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.get_encoder
1633
+ def get_encoder(self):
1634
+ return self.encoder
1635
+
1636
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.get_decoder
1637
+ def get_decoder(self):
1638
+ return self.decoder
1639
+
1640
+ @add_start_docstrings_to_model_forward(MORPH_T5_AUTO_INPUTS_DOCSTRING)
1641
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1642
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.forward with T5->MorphT5Auto, t5->morph_t5_auto
1643
+ def forward(
1644
+ self,
1645
+ input_ids: torch.LongTensor | None = None,
1646
+ input_morphs: torch.LongTensor | None = None,
1647
+ attention_mask: torch.FloatTensor | None = None,
1648
+ decoder_input_ids: torch.LongTensor | None = None,
1649
+ decoder_attention_mask: torch.BoolTensor | None = None,
1650
+ head_mask: torch.FloatTensor | None = None,
1651
+ decoder_head_mask: torch.FloatTensor | None = None,
1652
+ cross_attn_head_mask: torch.Tensor | None = None,
1653
+ encoder_outputs: tuple[tuple[torch.Tensor]] | None = None,
1654
+ past_key_values: tuple[tuple[torch.Tensor]] | None = None,
1655
+ inputs_embeds: torch.FloatTensor | None = None,
1656
+ decoder_inputs_embeds: torch.FloatTensor | None = None,
1657
+ labels: torch.LongTensor | None = None,
1658
+ use_cache: bool | None = None,
1659
+ output_attentions: bool | None = None,
1660
+ output_hidden_states: bool | None = None,
1661
+ return_dict: bool | None = None,
1662
+ ) -> tuple[torch.FloatTensor] | Seq2SeqLMOutput:
1663
+ r"""
1664
+ Labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1665
+
1666
+ Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
1667
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
1668
+ labels in `[0, ..., config.vocab_size]`
1669
+
1670
+ Returns:
1671
+
1672
+ Examples:
1673
+ ```python
1674
+ >>> from transformers import AutoTokenizer, MorphT5AutoForConditionalGeneration
1675
+
1676
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
1677
+ >>> model = MorphT5AutoForConditionalGeneration.from_pretrained("google/mt5-small")
1678
+
1679
+ >>> # training
1680
+ >>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
1681
+ >>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
1682
+ >>> outputs = model(input_ids=input_ids, labels=labels)
1683
+ >>> loss = outputs.loss
1684
+ >>> logits = outputs.logits
1685
+
1686
+ >>> # inference
1687
+ >>> input_ids = tokenizer(
1688
+ ... "summarize: studies have shown that owning a dog is good for you", return_tensors="pt"
1689
+ ... ).input_ids # Batch size 1
1690
+ >>> outputs = model.generate(input_ids)
1691
+ >>> print(tokenizer.decode_batch(outputs[0], skip_special_tokens=True))
1692
+ <extra_id_0>
1693
+
1694
+ ```
1695
+
1696
+ """
1697
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1698
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1699
+
1700
+ # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
1701
+ if head_mask is not None and decoder_head_mask is None:
1702
+ if self.config.num_layers == self.config.num_decoder_layers:
1703
+ warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
1704
+ decoder_head_mask = head_mask
1705
+
1706
+ # Encode if needed (training, first prediction pass)
1707
+ if encoder_outputs is None:
1708
+ # Convert encoder inputs in embeddings if needed
1709
+ encoder_outputs = self.encoder(
1710
+ input_ids=input_ids,
1711
+ input_morphs=input_morphs,
1712
+ attention_mask=attention_mask,
1713
+ inputs_embeds=inputs_embeds,
1714
+ head_mask=head_mask,
1715
+ output_attentions=output_attentions,
1716
+ output_hidden_states=output_hidden_states,
1717
+ return_dict=return_dict,
1718
+ )
1719
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1720
+ encoder_outputs = BaseModelOutput(
1721
+ last_hidden_state=encoder_outputs[0],
1722
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, # type: ignore[misc]
1723
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None, # type: ignore[misc]
1724
+ )
1725
+
1726
+ hidden_states = encoder_outputs[0] # type: ignore[index]
1727
+
1728
+ if self.model_parallel:
1729
+ torch.cuda.set_device(self.decoder.first_device)
1730
+
1731
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
1732
+ # get decoder inputs from shifting lm labels to the right
1733
+ decoder_input_ids = self._shift_right(labels)
1734
+
1735
+ # Set device for model parallelism
1736
+ if self.model_parallel:
1737
+ torch.cuda.set_device(self.decoder.first_device)
1738
+ hidden_states = hidden_states.to(self.decoder.first_device) # type: ignore[union-attr]
1739
+ if decoder_input_ids is not None:
1740
+ decoder_input_ids = decoder_input_ids.to(self.decoder.first_device)
1741
+ if attention_mask is not None:
1742
+ attention_mask = attention_mask.to(self.decoder.first_device)
1743
+ if decoder_attention_mask is not None:
1744
+ decoder_attention_mask = decoder_attention_mask.to(self.decoder.first_device)
1745
+
1746
+ # Decode
1747
+ decoder_outputs = self.decoder(
1748
+ input_ids=decoder_input_ids,
1749
+ attention_mask=decoder_attention_mask,
1750
+ inputs_embeds=decoder_inputs_embeds,
1751
+ past_key_values=past_key_values,
1752
+ encoder_hidden_states=hidden_states,
1753
+ encoder_attention_mask=attention_mask,
1754
+ head_mask=decoder_head_mask,
1755
+ cross_attn_head_mask=cross_attn_head_mask,
1756
+ use_cache=use_cache,
1757
+ output_attentions=output_attentions,
1758
+ output_hidden_states=output_hidden_states,
1759
+ return_dict=return_dict,
1760
+ )
1761
+
1762
+ sequence_output = decoder_outputs[0]
1763
+
1764
+ # Set device for model parallelism
1765
+ if self.model_parallel:
1766
+ torch.cuda.set_device(self.encoder.first_device)
1767
+ self.lm_head = self.lm_head.to(self.encoder.first_device)
1768
+ sequence_output = sequence_output.to(self.lm_head.weight.device)
1769
+
1770
+ if self.config.tie_word_embeddings:
1771
+ # Rescale output before projecting on vocab
1772
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
1773
+ sequence_output = sequence_output * (self.model_dim**-0.5)
1774
+
1775
+ lm_logits = self.lm_head(sequence_output)
1776
+
1777
+ loss = None
1778
+ if labels is not None:
1779
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1780
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
1781
+ # TODO(thom): Add z_loss https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L666
1782
+
1783
+ if not return_dict:
1784
+ output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
1785
+ return ((loss,) + output) if loss is not None else output
1786
+
1787
+ return Seq2SeqLMOutput(
1788
+ loss=loss,
1789
+ logits=lm_logits,
1790
+ past_key_values=decoder_outputs.past_key_values,
1791
+ decoder_hidden_states=decoder_outputs.hidden_states,
1792
+ decoder_attentions=decoder_outputs.attentions,
1793
+ cross_attentions=decoder_outputs.cross_attentions,
1794
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state, # type: ignore[union-attr]
1795
+ encoder_hidden_states=encoder_outputs.hidden_states, # type: ignore[union-attr]
1796
+ encoder_attentions=encoder_outputs.attentions, # type: ignore[union-attr]
1797
+ )
1798
+
1799
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.prepare_inputs_for_generation
1800
+ def prepare_inputs_for_generation(
1801
+ self,
1802
+ input_ids,
1803
+ past_key_values=None,
1804
+ attention_mask=None,
1805
+ head_mask=None,
1806
+ decoder_head_mask=None,
1807
+ cross_attn_head_mask=None,
1808
+ use_cache=None,
1809
+ encoder_outputs=None,
1810
+ **kwargs,
1811
+ ):
1812
+ # cut decoder_input_ids if past is used
1813
+ if past_key_values is not None:
1814
+ input_ids = input_ids[:, -1:]
1815
+
1816
+ return {
1817
+ "decoder_input_ids": input_ids,
1818
+ "past_key_values": past_key_values,
1819
+ "encoder_outputs": encoder_outputs,
1820
+ "attention_mask": attention_mask,
1821
+ "head_mask": head_mask,
1822
+ "decoder_head_mask": decoder_head_mask,
1823
+ "cross_attn_head_mask": cross_attn_head_mask,
1824
+ "use_cache": use_cache,
1825
+ }
1826
+
1827
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration.prepare_decoder_input_ids_from_labels
1828
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1829
+ return self._shift_right(labels)
1830
+
1831
+ # Copied from transformers.morph.t5.modeling_t5.T5ForConditionalGeneration._reorder_cache
1832
+ def _reorder_cache(self, past, beam_idx):
1833
+ # if decoder past is not included in output
1834
+ # speedy decoding is disabled and no need to reorder
1835
+ if past is None:
1836
+ logger.warning("You might want to consider setting `use_cache=True` to speed up decoding")
1837
+ return past
1838
+
1839
+ reordered_decoder_past = ()
1840
+ for layer_past_states in past:
1841
+ # get the correct batch idx from layer past batch dim
1842
+ # batch dim of `past` is at 2nd position
1843
+ reordered_layer_past_states = ()
1844
+ for layer_past_state in layer_past_states:
1845
+ # need to set correct `past` for each of the four key / value states
1846
+ reordered_layer_past_states = reordered_layer_past_states + (
1847
+ layer_past_state.index_select(0, beam_idx.to(layer_past_state.device)),
1848
+ )
1849
+
1850
+ assert reordered_layer_past_states[0].shape == layer_past_states[0].shape
1851
+ assert len(reordered_layer_past_states) == len(layer_past_states)
1852
+
1853
+ reordered_decoder_past = reordered_decoder_past + (reordered_layer_past_states,)
1854
+ return reordered_decoder_past
1855
+
1856
+
1857
+ @add_start_docstrings(
1858
+ "The bare MorphT5Auto Model transformer outputting encoder's raw hidden-states without any specific head on top.",
1859
+ MorphT5Auto_START_DOCSTRING,
1860
+ )
1861
+ class MorphT5AutoEncoderModel(MorphT5AutoPreTrainedModel):
1862
+ r"""
1863
+ Examples:
1864
+ ```python
1865
+ >>> from transformers import MorphT5AutoEncoderModel, AutoTokenizer
1866
+
1867
+ >>> model = MorphT5AutoEncoderModel.from_pretrained("google/mt5-small")
1868
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
1869
+ >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
1870
+ >>> input_ids = tokenizer(article, return_tensors="pt").input_ids
1871
+ >>> outputs = model(input_ids)
1872
+ >>> hidden_state = outputs.last_hidden_state
1873
+
1874
+ ```
1875
+
1876
+ """
1877
+
1878
+ model_type = "morph-t5-auto"
1879
+ config_class = MorphT5AutoConfig
1880
+ _keys_to_ignore_on_load_missing = [
1881
+ r"encoder.embed_tokens.weight",
1882
+ ]
1883
+ _keys_to_ignore_on_save = [
1884
+ r"encoder.embed_tokens.weight",
1885
+ ]
1886
+ _keys_to_ignore_on_load_missing = [r"encoder.embed_tokens.weight"]
1887
+
1888
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel.__init__ with T5->MorphT5Auto
1889
+ def __init__(self, config: MorphT5AutoConfig):
1890
+ super().__init__(config)
1891
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1892
+
1893
+ encoder_config = copy.deepcopy(config)
1894
+ encoder_config.use_cache = False
1895
+ encoder_config.is_encoder_decoder = False
1896
+ self.encoder = MorphT5AutoStack(encoder_config, self.shared)
1897
+
1898
+ # Initialize weights and apply final processing
1899
+ self.post_init()
1900
+
1901
+ # Model parallel
1902
+ self.model_parallel = False
1903
+ self.device_map = None
1904
+
1905
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1906
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel.parallelize with T5->MorphT5Auto
1907
+ def parallelize(self, device_map=None):
1908
+ self.device_map = (
1909
+ get_device_map(len(self.encoder.block), range(torch.cuda.device_count())) if device_map is None else device_map
1910
+ )
1911
+ assert_device_map(self.device_map, len(self.encoder.block))
1912
+ self.encoder.parallelize(self.device_map)
1913
+ self.model_parallel = True
1914
+
1915
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1916
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel.deparallelize with T5->MorphT5Auto
1917
+ def deparallelize(self):
1918
+ self.encoder.deparallelize()
1919
+ self.encoder = self.encoder.to("cpu")
1920
+ self.model_parallel = False
1921
+ self.device_map = None
1922
+ torch.cuda.empty_cache()
1923
+
1924
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel.get_input_embeddings with T5->MorphT5Auto
1925
+ def get_input_embeddings(self):
1926
+ return self.shared
1927
+
1928
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel.a with T5->MorphT5Auto
1929
+ def set_input_embeddings(self, new_embeddings):
1930
+ self.shared = new_embeddings
1931
+ self.encoder.set_input_embeddings(new_embeddings)
1932
+
1933
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel.get_encoder with T5->MorphT5Auto
1934
+ def get_encoder(self):
1935
+ return self.encoder
1936
+
1937
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel._prune_heads with T5->MorphT5Auto
1938
+ def _prune_heads(self, heads_to_prune):
1939
+ """
1940
+ Prunes heads of the model.
1941
+
1942
+ heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1943
+ class PreTrainedModel
1944
+ """
1945
+ for layer, heads in heads_to_prune.items():
1946
+ self.encoder.block[layer].layer[0].SelfAttention.prune_heads(heads)
1947
+
1948
+ @add_start_docstrings_to_model_forward(MORPH_T5_AUTO_ENCODER_INPUTS_DOCSTRING)
1949
+ @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
1950
+ # Copied from transformers.morph.t5.modeling_t5.T5EncoderModel.forward with T5->MorphT5Auto
1951
+ def forward(
1952
+ self,
1953
+ input_ids: torch.LongTensor | None = None,
1954
+ attention_mask: torch.FloatTensor | None = None,
1955
+ head_mask: torch.FloatTensor | None = None,
1956
+ inputs_embeds: torch.FloatTensor | None = None,
1957
+ output_attentions: bool | None = None,
1958
+ output_hidden_states: bool | None = None,
1959
+ return_dict: bool | None = None,
1960
+ ) -> tuple[torch.FloatTensor] | BaseModelOutput:
1961
+ r"""
1962
+ Returns:
1963
+
1964
+ Example:
1965
+ ```python
1966
+ >>> from transformers import AutoTokenizer, MorphT5AutoEncoderModel
1967
+
1968
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small")
1969
+ >>> model = MorphT5AutoEncoderModel.from_pretrained("google/mt5-small")
1970
+ >>> input_ids = tokenizer(
1971
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1972
+ ... ).input_ids # Batch size 1
1973
+ >>> outputs = model(input_ids=input_ids)
1974
+ >>> last_hidden_states = outputs.last_hidden_state
1975
+
1976
+ ```
1977
+
1978
+ """
1979
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1980
+
1981
+ encoder_outputs = self.encoder(
1982
+ input_ids=input_ids,
1983
+ attention_mask=attention_mask,
1984
+ inputs_embeds=inputs_embeds,
1985
+ head_mask=head_mask,
1986
+ output_attentions=output_attentions,
1987
+ output_hidden_states=output_hidden_states,
1988
+ return_dict=return_dict,
1989
+ )
1990
+
1991
+ return encoder_outputs