mrapacz commited on
Commit
b17b1ce
·
verified ·
1 Parent(s): 816560e

Upload MorphT5ForConditionalGeneration

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