AdithyaSK HF Staff commited on
Commit
3f2b6f6
·
verified ·
1 Parent(s): 35c119b

Stage Harbor release files 90501-91000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/textnet/modeling_textnet.py +487 -0
  2. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/time_series_transformer/__init__.py +27 -0
  3. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/time_series_transformer/configuration_time_series_transformer.py +229 -0
  4. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py +1784 -0
  5. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/__init__.py +27 -0
  6. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/configuration_timesformer.py +129 -0
  7. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/convert_timesformer_to_pytorch.py +253 -0
  8. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/modeling_timesformer.py +816 -0
  9. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_backbone/__init__.py +27 -0
  10. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_backbone/configuration_timm_backbone.py +86 -0
  11. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_backbone/modeling_timm_backbone.py +161 -0
  12. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/__init__.py +28 -0
  13. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/configuration_timm_wrapper.py +117 -0
  14. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py +138 -0
  15. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/modeling_timm_wrapper.py +367 -0
  16. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/__init__.py +28 -0
  17. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/configuration_trocr.py +146 -0
  18. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py +237 -0
  19. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/modeling_trocr.py +958 -0
  20. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/processing_trocr.py +159 -0
  21. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/__init__.py +29 -0
  22. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/configuration_tvp.py +201 -0
  23. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/image_processing_tvp.py +481 -0
  24. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/modeling_tvp.py +985 -0
  25. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/processing_tvp.py +156 -0
  26. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/__init__.py +30 -0
  27. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/configuration_udop.py +160 -0
  28. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/convert_udop_to_hf.py +224 -0
  29. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/modeling_udop.py +0 -0
  30. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/processing_udop.py +216 -0
  31. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/tokenization_udop.py +1488 -0
  32. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/tokenization_udop_fast.py +1031 -0
  33. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/__init__.py +27 -0
  34. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/configuration_umt5.py +181 -0
  35. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py +274 -0
  36. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/modeling_umt5.py +2029 -0
  37. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/__init__.py +27 -0
  38. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/configuration_unispeech.py +309 -0
  39. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py +273 -0
  40. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/modeling_unispeech.py +1908 -0
  41. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/__init__.py +27 -0
  42. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/configuration_unispeech_sat.py +327 -0
  43. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py +109 -0
  44. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py +224 -0
  45. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/modeling_unispeech_sat.py +0 -0
  46. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/__init__.py +28 -0
  47. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/configuration_univnet.py +125 -0
  48. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/convert_univnet.py +162 -0
  49. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/feature_extraction_univnet.py +459 -0
  50. tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/modeling_univnet.py +654 -0
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/textnet/modeling_textnet.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 the Fast authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch TextNet model."""
16
+
17
+ from typing import Any, List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from torch import Tensor
22
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
23
+
24
+ from transformers import PreTrainedModel, add_start_docstrings
25
+ from transformers.activations import ACT2CLS
26
+ from transformers.modeling_outputs import (
27
+ BackboneOutput,
28
+ BaseModelOutputWithNoAttention,
29
+ BaseModelOutputWithPoolingAndNoAttention,
30
+ ImageClassifierOutputWithNoAttention,
31
+ )
32
+ from transformers.models.textnet.configuration_textnet import TextNetConfig
33
+ from transformers.utils import (
34
+ add_code_sample_docstrings,
35
+ add_start_docstrings_to_model_forward,
36
+ logging,
37
+ replace_return_docstrings,
38
+ )
39
+ from transformers.utils.backbone_utils import BackboneMixin
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ # General docstring
45
+ _CONFIG_FOR_DOC = "TextNetConfig"
46
+ _CHECKPOINT_FOR_DOC = "czczup/textnet-base"
47
+ _EXPECTED_OUTPUT_SHAPE = [1, 512, 20, 27]
48
+
49
+
50
+ class TextNetConvLayer(nn.Module):
51
+ def __init__(self, config: TextNetConfig):
52
+ super().__init__()
53
+
54
+ self.kernel_size = config.stem_kernel_size
55
+ self.stride = config.stem_stride
56
+ self.activation_function = config.stem_act_func
57
+
58
+ padding = (
59
+ (config.kernel_size[0] // 2, config.kernel_size[1] // 2)
60
+ if isinstance(config.stem_kernel_size, tuple)
61
+ else config.stem_kernel_size // 2
62
+ )
63
+
64
+ self.conv = nn.Conv2d(
65
+ config.stem_num_channels,
66
+ config.stem_out_channels,
67
+ kernel_size=config.stem_kernel_size,
68
+ stride=config.stem_stride,
69
+ padding=padding,
70
+ bias=False,
71
+ )
72
+ self.batch_norm = nn.BatchNorm2d(config.stem_out_channels, config.batch_norm_eps)
73
+
74
+ self.activation = nn.Identity()
75
+ if self.activation_function is not None:
76
+ self.activation = ACT2CLS[self.activation_function]()
77
+
78
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
79
+ hidden_states = self.conv(hidden_states)
80
+ hidden_states = self.batch_norm(hidden_states)
81
+ return self.activation(hidden_states)
82
+
83
+
84
+ class TextNetRepConvLayer(nn.Module):
85
+ r"""
86
+ This layer supports re-parameterization by combining multiple convolutional branches
87
+ (e.g., main convolution, vertical, horizontal, and identity branches) during training.
88
+ At inference time, these branches can be collapsed into a single convolution for
89
+ efficiency, as per the re-parameterization paradigm.
90
+
91
+ The "Rep" in the name stands for "re-parameterization" (introduced by RepVGG).
92
+ """
93
+
94
+ def __init__(self, config: TextNetConfig, in_channels: int, out_channels: int, kernel_size: int, stride: int):
95
+ super().__init__()
96
+
97
+ self.num_channels = in_channels
98
+ self.out_channels = out_channels
99
+ self.kernel_size = kernel_size
100
+ self.stride = stride
101
+
102
+ padding = ((kernel_size[0] - 1) // 2, (kernel_size[1] - 1) // 2)
103
+
104
+ self.activation_function = nn.ReLU()
105
+
106
+ self.main_conv = nn.Conv2d(
107
+ in_channels=in_channels,
108
+ out_channels=out_channels,
109
+ kernel_size=kernel_size,
110
+ stride=stride,
111
+ padding=padding,
112
+ bias=False,
113
+ )
114
+ self.main_batch_norm = nn.BatchNorm2d(num_features=out_channels, eps=config.batch_norm_eps)
115
+
116
+ vertical_padding = ((kernel_size[0] - 1) // 2, 0)
117
+ horizontal_padding = (0, (kernel_size[1] - 1) // 2)
118
+
119
+ if kernel_size[1] != 1:
120
+ self.vertical_conv = nn.Conv2d(
121
+ in_channels=in_channels,
122
+ out_channels=out_channels,
123
+ kernel_size=(kernel_size[0], 1),
124
+ stride=stride,
125
+ padding=vertical_padding,
126
+ bias=False,
127
+ )
128
+ self.vertical_batch_norm = nn.BatchNorm2d(num_features=out_channels, eps=config.batch_norm_eps)
129
+ else:
130
+ self.vertical_conv, self.vertical_batch_norm = None, None
131
+
132
+ if kernel_size[0] != 1:
133
+ self.horizontal_conv = nn.Conv2d(
134
+ in_channels=in_channels,
135
+ out_channels=out_channels,
136
+ kernel_size=(1, kernel_size[1]),
137
+ stride=stride,
138
+ padding=horizontal_padding,
139
+ bias=False,
140
+ )
141
+ self.horizontal_batch_norm = nn.BatchNorm2d(num_features=out_channels, eps=config.batch_norm_eps)
142
+ else:
143
+ self.horizontal_conv, self.horizontal_batch_norm = None, None
144
+
145
+ self.rbr_identity = (
146
+ nn.BatchNorm2d(num_features=in_channels, eps=config.batch_norm_eps)
147
+ if out_channels == in_channels and stride == 1
148
+ else None
149
+ )
150
+
151
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
152
+ main_outputs = self.main_conv(hidden_states)
153
+ main_outputs = self.main_batch_norm(main_outputs)
154
+
155
+ # applies a convolution with a vertical kernel
156
+ if self.vertical_conv is not None:
157
+ vertical_outputs = self.vertical_conv(hidden_states)
158
+ vertical_outputs = self.vertical_batch_norm(vertical_outputs)
159
+ main_outputs = main_outputs + vertical_outputs
160
+
161
+ # applies a convolution with a horizontal kernel
162
+ if self.horizontal_conv is not None:
163
+ horizontal_outputs = self.horizontal_conv(hidden_states)
164
+ horizontal_outputs = self.horizontal_batch_norm(horizontal_outputs)
165
+ main_outputs = main_outputs + horizontal_outputs
166
+
167
+ if self.rbr_identity is not None:
168
+ id_out = self.rbr_identity(hidden_states)
169
+ main_outputs = main_outputs + id_out
170
+
171
+ return self.activation_function(main_outputs)
172
+
173
+
174
+ class TextNetStage(nn.Module):
175
+ def __init__(self, config: TextNetConfig, depth: int):
176
+ super().__init__()
177
+ kernel_size = config.conv_layer_kernel_sizes[depth]
178
+ stride = config.conv_layer_strides[depth]
179
+
180
+ num_layers = len(kernel_size)
181
+ stage_in_channel_size = config.hidden_sizes[depth]
182
+ stage_out_channel_size = config.hidden_sizes[depth + 1]
183
+
184
+ in_channels = [stage_in_channel_size] + [stage_out_channel_size] * (num_layers - 1)
185
+ out_channels = [stage_out_channel_size] * num_layers
186
+
187
+ stage = []
188
+ for stage_config in zip(in_channels, out_channels, kernel_size, stride):
189
+ stage.append(TextNetRepConvLayer(config, *stage_config))
190
+ self.stage = nn.ModuleList(stage)
191
+
192
+ def forward(self, hidden_state):
193
+ for block in self.stage:
194
+ hidden_state = block(hidden_state)
195
+ return hidden_state
196
+
197
+
198
+ class TextNetEncoder(nn.Module):
199
+ def __init__(self, config: TextNetConfig):
200
+ super().__init__()
201
+
202
+ stages = []
203
+ num_stages = len(config.conv_layer_kernel_sizes)
204
+ for stage_ix in range(num_stages):
205
+ stages.append(TextNetStage(config, stage_ix))
206
+
207
+ self.stages = nn.ModuleList(stages)
208
+
209
+ def forward(
210
+ self,
211
+ hidden_state: torch.Tensor,
212
+ output_hidden_states: Optional[bool] = None,
213
+ return_dict: Optional[bool] = None,
214
+ ) -> BaseModelOutputWithNoAttention:
215
+ hidden_states = [hidden_state]
216
+ for stage in self.stages:
217
+ hidden_state = stage(hidden_state)
218
+ hidden_states.append(hidden_state)
219
+
220
+ if not return_dict:
221
+ output = (hidden_state,)
222
+ return output + (hidden_states,) if output_hidden_states else output
223
+
224
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state, hidden_states=hidden_states)
225
+
226
+
227
+ TEXTNET_START_DOCSTRING = r"""
228
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
229
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
230
+ behavior.
231
+
232
+ Parameters:
233
+ config ([`TextNetConfig`]): Model configuration class with all the parameters of the model.
234
+ Initializing with a config file does not load the weights associated with the model, only the
235
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
236
+ """
237
+
238
+ TEXTNET_INPUTS_DOCSTRING = r"""
239
+ Args:
240
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
241
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
242
+ [`TextNetImageProcessor.__call__`] for details.
243
+
244
+ output_hidden_states (`bool`, *optional*):
245
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
246
+ more detail.
247
+ return_dict (`bool`, *optional*):
248
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
249
+ """
250
+
251
+
252
+ class TextNetPreTrainedModel(PreTrainedModel):
253
+ """
254
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
255
+ models.
256
+ """
257
+
258
+ config_class = TextNetConfig
259
+ base_model_prefix = "textnet"
260
+ main_input_name = "pixel_values"
261
+
262
+ def _init_weights(self, module):
263
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
264
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
265
+ if module.bias is not None:
266
+ module.bias.data.zero_()
267
+ elif isinstance(module, nn.BatchNorm2d):
268
+ module.weight.data.fill_(1.0)
269
+ if module.bias is not None:
270
+ module.bias.data.zero_()
271
+
272
+
273
+ @add_start_docstrings(
274
+ "The bare Textnet model outputting raw features without any specific head on top.",
275
+ TEXTNET_START_DOCSTRING,
276
+ )
277
+ class TextNetModel(TextNetPreTrainedModel):
278
+ def __init__(self, config):
279
+ super().__init__(config)
280
+ self.stem = TextNetConvLayer(config)
281
+ self.encoder = TextNetEncoder(config)
282
+ self.pooler = nn.AdaptiveAvgPool2d((2, 2))
283
+ self.post_init()
284
+
285
+ @add_start_docstrings_to_model_forward(TEXTNET_INPUTS_DOCSTRING)
286
+ @add_code_sample_docstrings(
287
+ checkpoint=_CHECKPOINT_FOR_DOC,
288
+ output_type=BaseModelOutputWithPoolingAndNoAttention,
289
+ config_class=_CONFIG_FOR_DOC,
290
+ modality="vision",
291
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
292
+ )
293
+ def forward(
294
+ self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
295
+ ) -> Union[Tuple[Any, List[Any]], Tuple[Any], BaseModelOutputWithPoolingAndNoAttention]:
296
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
297
+ output_hidden_states = (
298
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
299
+ )
300
+
301
+ hidden_state = self.stem(pixel_values)
302
+
303
+ encoder_outputs = self.encoder(
304
+ hidden_state, output_hidden_states=output_hidden_states, return_dict=return_dict
305
+ )
306
+
307
+ last_hidden_state = encoder_outputs[0]
308
+ pooled_output = self.pooler(last_hidden_state)
309
+
310
+ if not return_dict:
311
+ output = (last_hidden_state, pooled_output)
312
+ return output + (encoder_outputs[1],) if output_hidden_states else output
313
+
314
+ return BaseModelOutputWithPoolingAndNoAttention(
315
+ last_hidden_state=last_hidden_state,
316
+ pooler_output=pooled_output,
317
+ hidden_states=encoder_outputs[1] if output_hidden_states else None,
318
+ )
319
+
320
+
321
+ @add_start_docstrings(
322
+ """
323
+ TextNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
324
+ ImageNet.
325
+ """,
326
+ TEXTNET_START_DOCSTRING,
327
+ )
328
+ class TextNetForImageClassification(TextNetPreTrainedModel):
329
+ def __init__(self, config):
330
+ super().__init__(config)
331
+ self.num_labels = config.num_labels
332
+ self.textnet = TextNetModel(config)
333
+ self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
334
+ self.flatten = nn.Flatten()
335
+ self.fc = nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
336
+
337
+ # classification head
338
+ self.classifier = nn.ModuleList([self.avg_pool, self.flatten])
339
+
340
+ # initialize weights and apply final processing
341
+ self.post_init()
342
+
343
+ @add_start_docstrings_to_model_forward(TEXTNET_INPUTS_DOCSTRING)
344
+ @replace_return_docstrings(output_type=ImageClassifierOutputWithNoAttention, config_class=_CONFIG_FOR_DOC)
345
+ def forward(
346
+ self,
347
+ pixel_values: Optional[torch.FloatTensor] = None,
348
+ labels: Optional[torch.LongTensor] = None,
349
+ output_hidden_states: Optional[bool] = None,
350
+ return_dict: Optional[bool] = None,
351
+ ) -> ImageClassifierOutputWithNoAttention:
352
+ r"""
353
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
354
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
355
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
356
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
357
+
358
+ Returns:
359
+
360
+ Examples:
361
+ ```python
362
+ >>> import torch
363
+ >>> import requests
364
+ >>> from transformers import TextNetForImageClassification, TextNetImageProcessor
365
+ >>> from PIL import Image
366
+
367
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
368
+ >>> image = Image.open(requests.get(url, stream=True).raw)
369
+
370
+ >>> processor = TextNetImageProcessor.from_pretrained("czczup/textnet-base")
371
+ >>> model = TextNetForImageClassification.from_pretrained("czczup/textnet-base")
372
+
373
+ >>> inputs = processor(images=image, return_tensors="pt")
374
+ >>> with torch.no_grad():
375
+ ... outputs = model(**inputs)
376
+ >>> outputs.logits.shape
377
+ torch.Size([1, 2])
378
+ ```"""
379
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
380
+
381
+ outputs = self.textnet(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
382
+ last_hidden_state = outputs[0]
383
+ for layer in self.classifier:
384
+ last_hidden_state = layer(last_hidden_state)
385
+ logits = self.fc(last_hidden_state)
386
+ loss = None
387
+
388
+ if labels is not None:
389
+ if self.config.problem_type is None:
390
+ if self.num_labels == 1:
391
+ self.config.problem_type = "regression"
392
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
393
+ self.config.problem_type = "single_label_classification"
394
+ else:
395
+ self.config.problem_type = "multi_label_classification"
396
+ if self.config.problem_type == "regression":
397
+ loss_fct = MSELoss()
398
+ if self.num_labels == 1:
399
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
400
+ else:
401
+ loss = loss_fct(logits, labels)
402
+ elif self.config.problem_type == "single_label_classification":
403
+ loss_fct = CrossEntropyLoss()
404
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
405
+ elif self.config.problem_type == "multi_label_classification":
406
+ loss_fct = BCEWithLogitsLoss()
407
+ loss = loss_fct(logits, labels)
408
+
409
+ if not return_dict:
410
+ output = (logits,) + outputs[2:]
411
+ return (loss,) + output if loss is not None else output
412
+
413
+ return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
414
+
415
+
416
+ @add_start_docstrings(
417
+ """
418
+ TextNet backbone, to be used with frameworks like DETR and MaskFormer.
419
+ """,
420
+ TEXTNET_START_DOCSTRING,
421
+ )
422
+ class TextNetBackbone(TextNetPreTrainedModel, BackboneMixin):
423
+ def __init__(self, config):
424
+ super().__init__(config)
425
+ super()._init_backbone(config)
426
+
427
+ self.textnet = TextNetModel(config)
428
+ self.num_features = config.hidden_sizes
429
+
430
+ # initialize weights and apply final processing
431
+ self.post_init()
432
+
433
+ @add_start_docstrings_to_model_forward(TEXTNET_INPUTS_DOCSTRING)
434
+ @replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
435
+ def forward(
436
+ self, pixel_values: Tensor, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None
437
+ ) -> Union[Tuple[Tuple], BackboneOutput]:
438
+ """
439
+ Returns:
440
+
441
+ Examples:
442
+
443
+ ```python
444
+ >>> import torch
445
+ >>> import requests
446
+ >>> from PIL import Image
447
+ >>> from transformers import AutoImageProcessor, AutoBackbone
448
+
449
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
450
+ >>> image = Image.open(requests.get(url, stream=True).raw)
451
+
452
+ >>> processor = AutoImageProcessor.from_pretrained("czczup/textnet-base")
453
+ >>> model = AutoBackbone.from_pretrained("czczup/textnet-base")
454
+
455
+ >>> inputs = processor(image, return_tensors="pt")
456
+ >>> with torch.no_grad():
457
+ >>> outputs = model(**inputs)
458
+ ```"""
459
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
460
+ output_hidden_states = (
461
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
462
+ )
463
+
464
+ outputs = self.textnet(pixel_values, output_hidden_states=True, return_dict=return_dict)
465
+
466
+ hidden_states = outputs.hidden_states if return_dict else outputs[2]
467
+
468
+ feature_maps = ()
469
+ for idx, stage in enumerate(self.stage_names):
470
+ if stage in self.out_features:
471
+ feature_maps += (hidden_states[idx],)
472
+
473
+ if not return_dict:
474
+ output = (feature_maps,)
475
+ if output_hidden_states:
476
+ hidden_states = outputs.hidden_states if return_dict else outputs[2]
477
+ output += (hidden_states,)
478
+ return output
479
+
480
+ return BackboneOutput(
481
+ feature_maps=feature_maps,
482
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
483
+ attentions=None,
484
+ )
485
+
486
+
487
+ __all__ = ["TextNetBackbone", "TextNetModel", "TextNetPreTrainedModel", "TextNetForImageClassification"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/time_series_transformer/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_time_series_transformer import *
22
+ from .modeling_time_series_transformer import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/time_series_transformer/configuration_time_series_transformer.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Time Series Transformer model configuration"""
16
+
17
+ from typing import List, Optional, Union
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class TimeSeriesTransformerConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`TimeSeriesTransformerModel`]. It is used to
29
+ instantiate a Time Series Transformer model according to the specified arguments, defining the model architecture.
30
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Time Series
31
+ Transformer
32
+ [huggingface/time-series-transformer-tourism-monthly](https://huggingface.co/huggingface/time-series-transformer-tourism-monthly)
33
+ architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+ Args:
39
+ prediction_length (`int`):
40
+ The prediction length for the decoder. In other words, the prediction horizon of the model. This value is
41
+ typically dictated by the dataset and we recommend to set it appropriately.
42
+ context_length (`int`, *optional*, defaults to `prediction_length`):
43
+ The context length for the encoder. If `None`, the context length will be the same as the
44
+ `prediction_length`.
45
+ distribution_output (`string`, *optional*, defaults to `"student_t"`):
46
+ The distribution emission head for the model. Could be either "student_t", "normal" or "negative_binomial".
47
+ loss (`string`, *optional*, defaults to `"nll"`):
48
+ The loss function for the model corresponding to the `distribution_output` head. For parametric
49
+ distributions it is the negative log likelihood (nll) - which currently is the only supported one.
50
+ input_size (`int`, *optional*, defaults to 1):
51
+ The size of the target variable which by default is 1 for univariate targets. Would be > 1 in case of
52
+ multivariate targets.
53
+ scaling (`string` or `bool`, *optional* defaults to `"mean"`):
54
+ Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
55
+ scaler is set to "mean".
56
+ lags_sequence (`list[int]`, *optional*, defaults to `[1, 2, 3, 4, 5, 6, 7]`):
57
+ The lags of the input time series as covariates often dictated by the frequency of the data. Default is
58
+ `[1, 2, 3, 4, 5, 6, 7]` but we recommend to change it based on the dataset appropriately.
59
+ num_time_features (`int`, *optional*, defaults to 0):
60
+ The number of time features in the input time series.
61
+ num_dynamic_real_features (`int`, *optional*, defaults to 0):
62
+ The number of dynamic real valued features.
63
+ num_static_categorical_features (`int`, *optional*, defaults to 0):
64
+ The number of static categorical features.
65
+ num_static_real_features (`int`, *optional*, defaults to 0):
66
+ The number of static real valued features.
67
+ cardinality (`list[int]`, *optional*):
68
+ The cardinality (number of different values) for each of the static categorical features. Should be a list
69
+ of integers, having the same length as `num_static_categorical_features`. Cannot be `None` if
70
+ `num_static_categorical_features` is > 0.
71
+ embedding_dimension (`list[int]`, *optional*):
72
+ The dimension of the embedding for each of the static categorical features. Should be a list of integers,
73
+ having the same length as `num_static_categorical_features`. Cannot be `None` if
74
+ `num_static_categorical_features` is > 0.
75
+ d_model (`int`, *optional*, defaults to 64):
76
+ Dimensionality of the transformer layers.
77
+ encoder_layers (`int`, *optional*, defaults to 2):
78
+ Number of encoder layers.
79
+ decoder_layers (`int`, *optional*, defaults to 2):
80
+ Number of decoder layers.
81
+ encoder_attention_heads (`int`, *optional*, defaults to 2):
82
+ Number of attention heads for each attention layer in the Transformer encoder.
83
+ decoder_attention_heads (`int`, *optional*, defaults to 2):
84
+ Number of attention heads for each attention layer in the Transformer decoder.
85
+ encoder_ffn_dim (`int`, *optional*, defaults to 32):
86
+ Dimension of the "intermediate" (often named feed-forward) layer in encoder.
87
+ decoder_ffn_dim (`int`, *optional*, defaults to 32):
88
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
89
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
90
+ The non-linear activation function (function or string) in the encoder and decoder. If string, `"gelu"` and
91
+ `"relu"` are supported.
92
+ dropout (`float`, *optional*, defaults to 0.1):
93
+ The dropout probability for all fully connected layers in the encoder, and decoder.
94
+ encoder_layerdrop (`float`, *optional*, defaults to 0.1):
95
+ The dropout probability for the attention and fully connected layers for each encoder layer.
96
+ decoder_layerdrop (`float`, *optional*, defaults to 0.1):
97
+ The dropout probability for the attention and fully connected layers for each decoder layer.
98
+ attention_dropout (`float`, *optional*, defaults to 0.1):
99
+ The dropout probability for the attention probabilities.
100
+ activation_dropout (`float`, *optional*, defaults to 0.1):
101
+ The dropout probability used between the two layers of the feed-forward networks.
102
+ num_parallel_samples (`int`, *optional*, defaults to 100):
103
+ The number of samples to generate in parallel for each time step of inference.
104
+ init_std (`float`, *optional*, defaults to 0.02):
105
+ The standard deviation of the truncated normal weight initialization distribution.
106
+ use_cache (`bool`, *optional*, defaults to `True`):
107
+ Whether to use the past key/values attentions (if applicable to the model) to speed up decoding.
108
+
109
+ Example:
110
+
111
+ ```python
112
+ >>> from transformers import TimeSeriesTransformerConfig, TimeSeriesTransformerModel
113
+
114
+ >>> # Initializing a Time Series Transformer configuration with 12 time steps for prediction
115
+ >>> configuration = TimeSeriesTransformerConfig(prediction_length=12)
116
+
117
+ >>> # Randomly initializing a model (with random weights) from the configuration
118
+ >>> model = TimeSeriesTransformerModel(configuration)
119
+
120
+ >>> # Accessing the model configuration
121
+ >>> configuration = model.config
122
+ ```"""
123
+
124
+ model_type = "time_series_transformer"
125
+ attribute_map = {
126
+ "hidden_size": "d_model",
127
+ "num_attention_heads": "encoder_attention_heads",
128
+ "num_hidden_layers": "encoder_layers",
129
+ }
130
+
131
+ def __init__(
132
+ self,
133
+ prediction_length: Optional[int] = None,
134
+ context_length: Optional[int] = None,
135
+ distribution_output: str = "student_t",
136
+ loss: str = "nll",
137
+ input_size: int = 1,
138
+ lags_sequence: List[int] = [1, 2, 3, 4, 5, 6, 7],
139
+ scaling: Optional[Union[str, bool]] = "mean",
140
+ num_dynamic_real_features: int = 0,
141
+ num_static_categorical_features: int = 0,
142
+ num_static_real_features: int = 0,
143
+ num_time_features: int = 0,
144
+ cardinality: Optional[List[int]] = None,
145
+ embedding_dimension: Optional[List[int]] = None,
146
+ encoder_ffn_dim: int = 32,
147
+ decoder_ffn_dim: int = 32,
148
+ encoder_attention_heads: int = 2,
149
+ decoder_attention_heads: int = 2,
150
+ encoder_layers: int = 2,
151
+ decoder_layers: int = 2,
152
+ is_encoder_decoder: bool = True,
153
+ activation_function: str = "gelu",
154
+ d_model: int = 64,
155
+ dropout: float = 0.1,
156
+ encoder_layerdrop: float = 0.1,
157
+ decoder_layerdrop: float = 0.1,
158
+ attention_dropout: float = 0.1,
159
+ activation_dropout: float = 0.1,
160
+ num_parallel_samples: int = 100,
161
+ init_std: float = 0.02,
162
+ use_cache=True,
163
+ **kwargs,
164
+ ):
165
+ # time series specific configuration
166
+ self.prediction_length = prediction_length
167
+ self.context_length = context_length or prediction_length
168
+ self.distribution_output = distribution_output
169
+ self.loss = loss
170
+ self.input_size = input_size
171
+ self.num_time_features = num_time_features
172
+ self.lags_sequence = lags_sequence
173
+ self.scaling = scaling
174
+ self.num_dynamic_real_features = num_dynamic_real_features
175
+ self.num_static_real_features = num_static_real_features
176
+ self.num_static_categorical_features = num_static_categorical_features
177
+ if cardinality and num_static_categorical_features > 0:
178
+ if len(cardinality) != num_static_categorical_features:
179
+ raise ValueError(
180
+ "The cardinality should be a list of the same length as `num_static_categorical_features`"
181
+ )
182
+ self.cardinality = cardinality
183
+ else:
184
+ self.cardinality = [0]
185
+ if embedding_dimension and num_static_categorical_features > 0:
186
+ if len(embedding_dimension) != num_static_categorical_features:
187
+ raise ValueError(
188
+ "The embedding dimension should be a list of the same length as `num_static_categorical_features`"
189
+ )
190
+ self.embedding_dimension = embedding_dimension
191
+ else:
192
+ self.embedding_dimension = [min(50, (cat + 1) // 2) for cat in self.cardinality]
193
+ self.num_parallel_samples = num_parallel_samples
194
+
195
+ # Transformer architecture configuration
196
+ self.feature_size = input_size * len(lags_sequence) + self._number_of_features
197
+ self.d_model = d_model
198
+ self.encoder_attention_heads = encoder_attention_heads
199
+ self.decoder_attention_heads = decoder_attention_heads
200
+ self.encoder_ffn_dim = encoder_ffn_dim
201
+ self.decoder_ffn_dim = decoder_ffn_dim
202
+ self.encoder_layers = encoder_layers
203
+ self.decoder_layers = decoder_layers
204
+
205
+ self.dropout = dropout
206
+ self.attention_dropout = attention_dropout
207
+ self.activation_dropout = activation_dropout
208
+ self.encoder_layerdrop = encoder_layerdrop
209
+ self.decoder_layerdrop = decoder_layerdrop
210
+
211
+ self.activation_function = activation_function
212
+ self.init_std = init_std
213
+
214
+ self.use_cache = use_cache
215
+
216
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
217
+
218
+ @property
219
+ def _number_of_features(self) -> int:
220
+ return (
221
+ sum(self.embedding_dimension)
222
+ + self.num_dynamic_real_features
223
+ + self.num_time_features
224
+ + self.num_static_real_features
225
+ + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
226
+ )
227
+
228
+
229
+ __all__ = ["TimeSeriesTransformerConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py ADDED
@@ -0,0 +1,1784 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch Time Series Transformer model."""
17
+
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ...activations import ACT2FN
25
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
26
+ from ...modeling_outputs import (
27
+ BaseModelOutput,
28
+ BaseModelOutputWithPastAndCrossAttentions,
29
+ SampleTSPredictionOutput,
30
+ Seq2SeqTSModelOutput,
31
+ Seq2SeqTSPredictionOutput,
32
+ )
33
+ from ...modeling_utils import PreTrainedModel
34
+ from ...time_series_utils import NegativeBinomialOutput, NormalOutput, StudentTOutput
35
+ from ...utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ logging,
39
+ replace_return_docstrings,
40
+ )
41
+ from .configuration_time_series_transformer import TimeSeriesTransformerConfig
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ _CONFIG_FOR_DOC = "TimeSeriesTransformerConfig"
47
+
48
+
49
+ class TimeSeriesFeatureEmbedder(nn.Module):
50
+ """
51
+ Embed a sequence of categorical features.
52
+
53
+ Args:
54
+ cardinalities (`list[int]`):
55
+ List of cardinalities of the categorical features.
56
+ embedding_dims (`list[int]`):
57
+ List of embedding dimensions of the categorical features.
58
+ """
59
+
60
+ def __init__(self, cardinalities: List[int], embedding_dims: List[int]) -> None:
61
+ super().__init__()
62
+
63
+ self.num_features = len(cardinalities)
64
+ self.embedders = nn.ModuleList([nn.Embedding(c, d) for c, d in zip(cardinalities, embedding_dims)])
65
+
66
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
67
+ if self.num_features > 1:
68
+ # we slice the last dimension, giving an array of length
69
+ # self.num_features with shape (N,T) or (N)
70
+ cat_feature_slices = torch.chunk(features, self.num_features, dim=-1)
71
+ else:
72
+ cat_feature_slices = [features]
73
+
74
+ return torch.cat(
75
+ [
76
+ embed(cat_feature_slice.squeeze(-1))
77
+ for embed, cat_feature_slice in zip(self.embedders, cat_feature_slices)
78
+ ],
79
+ dim=-1,
80
+ )
81
+
82
+
83
+ class TimeSeriesStdScaler(nn.Module):
84
+ """
85
+ Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
86
+ subtracting from the mean and dividing by the standard deviation.
87
+ """
88
+
89
+ def __init__(self, config: TimeSeriesTransformerConfig):
90
+ super().__init__()
91
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
92
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
93
+ self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5
94
+
95
+ def forward(
96
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
97
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
98
+ """
99
+ Parameters:
100
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
101
+ input for Batch norm calculation
102
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
103
+ Calculating the scale on the observed indicator.
104
+ Returns:
105
+ tuple of `torch.Tensor` of shapes
106
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
107
+ `(batch_size, 1, num_input_channels)`)
108
+ """
109
+ denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim)
110
+ denominator = denominator.clamp_min(1.0)
111
+ loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator
112
+
113
+ variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
114
+ scale = torch.sqrt(variance + self.minimum_scale)
115
+ return (data - loc) / scale, loc, scale
116
+
117
+
118
+ class TimeSeriesMeanScaler(nn.Module):
119
+ """
120
+ Computes a scaling factor as the weighted average absolute value along the first dimension, and scales the data
121
+ accordingly.
122
+ """
123
+
124
+ def __init__(self, config: TimeSeriesTransformerConfig):
125
+ super().__init__()
126
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
127
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
128
+ self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-10
129
+ self.default_scale = config.default_scale if hasattr(config, "default_scale") else None
130
+
131
+ def forward(
132
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
133
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
134
+ """
135
+ Parameters:
136
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
137
+ input for Batch norm calculation
138
+ observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
139
+ Calculating the scale on the observed indicator.
140
+ Returns:
141
+ tuple of `torch.Tensor` of shapes
142
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
143
+ `(batch_size, 1, num_input_channels)`)
144
+ """
145
+ ts_sum = (data * observed_indicator).abs().sum(self.dim, keepdim=True)
146
+ num_observed = observed_indicator.sum(self.dim, keepdim=True)
147
+
148
+ scale = ts_sum / torch.clamp(num_observed, min=1)
149
+
150
+ # If `default_scale` is provided, we use it, otherwise we use the scale
151
+ # of the batch.
152
+ if self.default_scale is None:
153
+ batch_sum = ts_sum.sum(dim=0)
154
+ batch_observations = torch.clamp(num_observed.sum(0), min=1)
155
+ default_scale = torch.squeeze(batch_sum / batch_observations)
156
+ else:
157
+ default_scale = self.default_scale * torch.ones_like(scale)
158
+
159
+ # apply default scale where there are no observations
160
+ scale = torch.where(num_observed > 0, scale, default_scale)
161
+
162
+ # ensure the scale is at least `self.minimum_scale`
163
+ scale = torch.clamp(scale, min=self.minimum_scale)
164
+ scaled_data = data / scale
165
+
166
+ if not self.keepdim:
167
+ scale = scale.squeeze(dim=self.dim)
168
+
169
+ return scaled_data, torch.zeros_like(scale), scale
170
+
171
+
172
+ class TimeSeriesNOPScaler(nn.Module):
173
+ """
174
+ Assigns a scaling factor equal to 1 along the first dimension, and therefore applies no scaling to the input data.
175
+ """
176
+
177
+ def __init__(self, config: TimeSeriesTransformerConfig):
178
+ super().__init__()
179
+ self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
180
+ self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
181
+
182
+ def forward(
183
+ self, data: torch.Tensor, observed_indicator: torch.Tensor = None
184
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
185
+ """
186
+ Parameters:
187
+ data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
188
+ input for Batch norm calculation
189
+ Returns:
190
+ tuple of `torch.Tensor` of shapes
191
+ (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
192
+ `(batch_size, 1, num_input_channels)`)
193
+ """
194
+ scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
195
+ loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
196
+ return data, loc, scale
197
+
198
+
199
+ def nll(input: torch.distributions.Distribution, target: torch.Tensor) -> torch.Tensor:
200
+ """
201
+ Computes the negative log likelihood loss from input distribution with respect to target.
202
+ """
203
+ return -input.log_prob(target)
204
+
205
+
206
+ def weighted_average(input_tensor: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None) -> torch.Tensor:
207
+ """
208
+ Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
209
+ meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
210
+
211
+ Args:
212
+ input_tensor (`torch.FloatTensor`):
213
+ Input tensor, of which the average must be computed.
214
+ weights (`torch.FloatTensor`, *optional*):
215
+ Weights tensor, of the same shape as `input_tensor`.
216
+ dim (`int`, *optional*):
217
+ The dim along which to average `input_tensor`.
218
+
219
+ Returns:
220
+ `torch.FloatTensor`: The tensor with values averaged along the specified `dim`.
221
+ """
222
+ if weights is not None:
223
+ weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
224
+ sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
225
+ return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
226
+ else:
227
+ return input_tensor.mean(dim=dim)
228
+
229
+
230
+ # Copied from transformers.models.marian.modeling_marian.MarianSinusoidalPositionalEmbedding with Marian->TimeSeries
231
+ class TimeSeriesSinusoidalPositionalEmbedding(nn.Embedding):
232
+ """This module produces sinusoidal positional embeddings of any length."""
233
+
234
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None) -> None:
235
+ super().__init__(num_positions, embedding_dim)
236
+ self.weight = self._init_weight(self.weight)
237
+
238
+ @staticmethod
239
+ def _init_weight(out: nn.Parameter) -> nn.Parameter:
240
+ """
241
+ Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
242
+ the 2nd half of the vector. [dim // 2:]
243
+ """
244
+ n_pos, dim = out.shape
245
+ position_enc = np.array(
246
+ [[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
247
+ )
248
+ out.requires_grad = False # set early to avoid an error in pytorch-1.8+
249
+ sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
250
+ out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
251
+ out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
252
+ out.detach_()
253
+ return out
254
+
255
+ @torch.no_grad()
256
+ def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0) -> torch.Tensor:
257
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
258
+ bsz, seq_len = input_ids_shape[:2]
259
+ positions = torch.arange(
260
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
261
+ )
262
+ return super().forward(positions)
263
+
264
+
265
+ class TimeSeriesValueEmbedding(nn.Module):
266
+ def __init__(self, feature_size, d_model):
267
+ super().__init__()
268
+ self.value_projection = nn.Linear(in_features=feature_size, out_features=d_model, bias=False)
269
+
270
+ def forward(self, x):
271
+ return self.value_projection(x)
272
+
273
+
274
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->TimeSeriesTransformer
275
+ class TimeSeriesTransformerAttention(nn.Module):
276
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
277
+
278
+ def __init__(
279
+ self,
280
+ embed_dim: int,
281
+ num_heads: int,
282
+ dropout: float = 0.0,
283
+ is_decoder: bool = False,
284
+ bias: bool = True,
285
+ is_causal: bool = False,
286
+ config: Optional[TimeSeriesTransformerConfig] = None,
287
+ ):
288
+ super().__init__()
289
+ self.embed_dim = embed_dim
290
+ self.num_heads = num_heads
291
+ self.dropout = dropout
292
+ self.head_dim = embed_dim // num_heads
293
+ self.config = config
294
+
295
+ if (self.head_dim * num_heads) != self.embed_dim:
296
+ raise ValueError(
297
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
298
+ f" and `num_heads`: {num_heads})."
299
+ )
300
+ self.scaling = self.head_dim**-0.5
301
+ self.is_decoder = is_decoder
302
+ self.is_causal = is_causal
303
+
304
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
305
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
306
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
307
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
308
+
309
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
310
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
311
+
312
+ def forward(
313
+ self,
314
+ hidden_states: torch.Tensor,
315
+ key_value_states: Optional[torch.Tensor] = None,
316
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
317
+ attention_mask: Optional[torch.Tensor] = None,
318
+ layer_head_mask: Optional[torch.Tensor] = None,
319
+ output_attentions: bool = False,
320
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
321
+ """Input shape: Batch x Time x Channel"""
322
+
323
+ # if key_value_states are provided this layer is used as a cross-attention layer
324
+ # for the decoder
325
+ is_cross_attention = key_value_states is not None
326
+
327
+ bsz, tgt_len, _ = hidden_states.size()
328
+
329
+ # get query proj
330
+ query_states = self.q_proj(hidden_states) * self.scaling
331
+ # get key, value proj
332
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
333
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
334
+ # the provided `key_value_states` to support prefix tuning
335
+ if (
336
+ is_cross_attention
337
+ and past_key_value is not None
338
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
339
+ ):
340
+ # reuse k,v, cross_attentions
341
+ key_states = past_key_value[0]
342
+ value_states = past_key_value[1]
343
+ elif is_cross_attention:
344
+ # cross_attentions
345
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
346
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
347
+ elif past_key_value is not None:
348
+ # reuse k, v, self_attention
349
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
350
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
351
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
352
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
353
+ else:
354
+ # self_attention
355
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
356
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
357
+
358
+ if self.is_decoder:
359
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
360
+ # Further calls to cross_attention layer can then reuse all cross-attention
361
+ # key/value_states (first "if" case)
362
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
363
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
364
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
365
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
366
+ past_key_value = (key_states, value_states)
367
+
368
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
369
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
370
+ key_states = key_states.reshape(*proj_shape)
371
+ value_states = value_states.reshape(*proj_shape)
372
+
373
+ src_len = key_states.size(1)
374
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
375
+
376
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
377
+ raise ValueError(
378
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
379
+ f" {attn_weights.size()}"
380
+ )
381
+
382
+ if attention_mask is not None:
383
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
384
+ raise ValueError(
385
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
386
+ )
387
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
388
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
389
+
390
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
391
+
392
+ if layer_head_mask is not None:
393
+ if layer_head_mask.size() != (self.num_heads,):
394
+ raise ValueError(
395
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
396
+ f" {layer_head_mask.size()}"
397
+ )
398
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
399
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
400
+
401
+ if output_attentions:
402
+ # this operation is a bit awkward, but it's required to
403
+ # make sure that attn_weights keeps its gradient.
404
+ # In order to do so, attn_weights have to be reshaped
405
+ # twice and have to be reused in the following
406
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
407
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
408
+ else:
409
+ attn_weights_reshaped = None
410
+
411
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
412
+
413
+ attn_output = torch.bmm(attn_probs, value_states)
414
+
415
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
416
+ raise ValueError(
417
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
418
+ f" {attn_output.size()}"
419
+ )
420
+
421
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
422
+ attn_output = attn_output.transpose(1, 2)
423
+
424
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
425
+ # partitioned across GPUs when using tensor-parallelism.
426
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
427
+
428
+ attn_output = self.out_proj(attn_output)
429
+
430
+ return attn_output, attn_weights_reshaped, past_key_value
431
+
432
+
433
+ # Copied from transformers.models.bart.modeling_bart.BartEncoderLayer with Bart->TimeSeriesTransformer, BART->TIME_SERIES_TRANSFORMER
434
+ class TimeSeriesTransformerEncoderLayer(nn.Module):
435
+ def __init__(self, config: TimeSeriesTransformerConfig):
436
+ super().__init__()
437
+ self.embed_dim = config.d_model
438
+
439
+ self.self_attn = TIME_SERIES_TRANSFORMER_ATTENTION_CLASSES[config._attn_implementation](
440
+ embed_dim=self.embed_dim,
441
+ num_heads=config.encoder_attention_heads,
442
+ dropout=config.attention_dropout,
443
+ config=config,
444
+ )
445
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
446
+ self.dropout = config.dropout
447
+ self.activation_fn = ACT2FN[config.activation_function]
448
+ self.activation_dropout = config.activation_dropout
449
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
450
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
451
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
452
+
453
+ def forward(
454
+ self,
455
+ hidden_states: torch.FloatTensor,
456
+ attention_mask: torch.FloatTensor,
457
+ layer_head_mask: torch.FloatTensor,
458
+ output_attentions: Optional[bool] = False,
459
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
460
+ """
461
+ Args:
462
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
463
+ attention_mask (`torch.FloatTensor`): attention mask of size
464
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
465
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
466
+ `(encoder_attention_heads,)`.
467
+ output_attentions (`bool`, *optional*):
468
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
469
+ returned tensors for more detail.
470
+ """
471
+ residual = hidden_states
472
+ hidden_states, attn_weights, _ = self.self_attn(
473
+ hidden_states=hidden_states,
474
+ attention_mask=attention_mask,
475
+ layer_head_mask=layer_head_mask,
476
+ output_attentions=output_attentions,
477
+ )
478
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
479
+ hidden_states = residual + hidden_states
480
+ hidden_states = self.self_attn_layer_norm(hidden_states)
481
+
482
+ residual = hidden_states
483
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
484
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
485
+ hidden_states = self.fc2(hidden_states)
486
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
487
+ hidden_states = residual + hidden_states
488
+ hidden_states = self.final_layer_norm(hidden_states)
489
+
490
+ if hidden_states.dtype == torch.float16 and (
491
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
492
+ ):
493
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
494
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
495
+
496
+ outputs = (hidden_states,)
497
+
498
+ if output_attentions:
499
+ outputs += (attn_weights,)
500
+
501
+ return outputs
502
+
503
+
504
+ # TODO: Implement attention with SDPA for TimeSeriesTransformer.
505
+ TIME_SERIES_TRANSFORMER_ATTENTION_CLASSES = {
506
+ "eager": TimeSeriesTransformerAttention,
507
+ }
508
+
509
+
510
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderLayer with Bart->TimeSeriesTransformer, with BART->TIME_SERIES_TRANSFORMER
511
+ class TimeSeriesTransformerDecoderLayer(nn.Module):
512
+ def __init__(self, config: TimeSeriesTransformerConfig):
513
+ super().__init__()
514
+ self.embed_dim = config.d_model
515
+
516
+ self.self_attn = TIME_SERIES_TRANSFORMER_ATTENTION_CLASSES[config._attn_implementation](
517
+ embed_dim=self.embed_dim,
518
+ num_heads=config.decoder_attention_heads,
519
+ dropout=config.attention_dropout,
520
+ is_decoder=True,
521
+ is_causal=True,
522
+ config=config,
523
+ )
524
+ self.dropout = config.dropout
525
+ self.activation_fn = ACT2FN[config.activation_function]
526
+ self.activation_dropout = config.activation_dropout
527
+
528
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
529
+ self.encoder_attn = TIME_SERIES_TRANSFORMER_ATTENTION_CLASSES[config._attn_implementation](
530
+ self.embed_dim,
531
+ config.decoder_attention_heads,
532
+ dropout=config.attention_dropout,
533
+ is_decoder=True,
534
+ config=config,
535
+ )
536
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
537
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
538
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
539
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
540
+
541
+ def forward(
542
+ self,
543
+ hidden_states: torch.Tensor,
544
+ attention_mask: Optional[torch.Tensor] = None,
545
+ encoder_hidden_states: Optional[torch.Tensor] = None,
546
+ encoder_attention_mask: Optional[torch.Tensor] = None,
547
+ layer_head_mask: Optional[torch.Tensor] = None,
548
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
549
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
550
+ output_attentions: Optional[bool] = False,
551
+ use_cache: Optional[bool] = True,
552
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
553
+ """
554
+ Args:
555
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
556
+ attention_mask (`torch.FloatTensor`): attention mask of size
557
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
558
+ encoder_hidden_states (`torch.FloatTensor`):
559
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
560
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
561
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
562
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
563
+ `(encoder_attention_heads,)`.
564
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
565
+ size `(decoder_attention_heads,)`.
566
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
567
+ output_attentions (`bool`, *optional*):
568
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
569
+ returned tensors for more detail.
570
+ """
571
+ residual = hidden_states
572
+
573
+ # Self Attention
574
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
575
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
576
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
577
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
578
+ hidden_states=hidden_states,
579
+ past_key_value=self_attn_past_key_value,
580
+ attention_mask=attention_mask,
581
+ layer_head_mask=layer_head_mask,
582
+ output_attentions=output_attentions,
583
+ )
584
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
585
+ hidden_states = residual + hidden_states
586
+ hidden_states = self.self_attn_layer_norm(hidden_states)
587
+
588
+ # Cross-Attention Block
589
+ cross_attn_present_key_value = None
590
+ cross_attn_weights = None
591
+ if encoder_hidden_states is not None:
592
+ residual = hidden_states
593
+
594
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
595
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
596
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
597
+ hidden_states=hidden_states,
598
+ key_value_states=encoder_hidden_states,
599
+ attention_mask=encoder_attention_mask,
600
+ layer_head_mask=cross_attn_layer_head_mask,
601
+ past_key_value=cross_attn_past_key_value,
602
+ output_attentions=output_attentions,
603
+ )
604
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
605
+ hidden_states = residual + hidden_states
606
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
607
+
608
+ # add cross-attn to positions 3,4 of present_key_value tuple
609
+ present_key_value = present_key_value + cross_attn_present_key_value
610
+
611
+ # Fully Connected
612
+ residual = hidden_states
613
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
614
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
615
+ hidden_states = self.fc2(hidden_states)
616
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
617
+ hidden_states = residual + hidden_states
618
+ hidden_states = self.final_layer_norm(hidden_states)
619
+
620
+ outputs = (hidden_states,)
621
+
622
+ if output_attentions:
623
+ outputs += (self_attn_weights, cross_attn_weights)
624
+
625
+ if use_cache:
626
+ outputs += (present_key_value,)
627
+
628
+ return outputs
629
+
630
+
631
+ class TimeSeriesTransformerPreTrainedModel(PreTrainedModel):
632
+ config_class = TimeSeriesTransformerConfig
633
+ base_model_prefix = "model"
634
+ main_input_name = "past_values"
635
+ supports_gradient_checkpointing = True
636
+
637
+ def _init_weights(self, module):
638
+ std = self.config.init_std
639
+ if isinstance(module, nn.Linear):
640
+ module.weight.data.normal_(mean=0.0, std=std)
641
+ if module.bias is not None:
642
+ module.bias.data.zero_()
643
+ elif isinstance(module, TimeSeriesSinusoidalPositionalEmbedding):
644
+ pass
645
+ elif isinstance(module, nn.Embedding):
646
+ module.weight.data.normal_(mean=0.0, std=std)
647
+ if module.padding_idx is not None:
648
+ module.weight.data[module.padding_idx].zero_()
649
+
650
+
651
+ TIME_SERIES_TRANSFORMER_START_DOCSTRING = r"""
652
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
653
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
654
+ etc.)
655
+
656
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
657
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
658
+ and behavior.
659
+
660
+ Parameters:
661
+ config ([`TimeSeriesTransformerConfig`]):
662
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
663
+ load the weights associated with the model, only the configuration. Check out the
664
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
665
+ """
666
+
667
+ TIME_SERIES_TRANSFORMER_INPUTS_DOCSTRING = r"""
668
+ Args:
669
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`):
670
+ Past values of the time series, that serve as context in order to predict the future. The sequence size of
671
+ this tensor must be larger than the `context_length` of the model, since the model will use the larger size
672
+ to construct lag features, i.e. additional values from the past which are added in order to serve as "extra
673
+ context".
674
+
675
+ The `sequence_length` here is equal to `config.context_length` + `max(config.lags_sequence)`, which if no
676
+ `lags_sequence` is configured, is equal to `config.context_length` + 7 (as by default, the largest
677
+ look-back index in `config.lags_sequence` is 7). The property `_past_length` returns the actual length of
678
+ the past.
679
+
680
+ The `past_values` is what the Transformer encoder gets as input (with optional additional features, such as
681
+ `static_categorical_features`, `static_real_features`, `past_time_features` and lags).
682
+
683
+ Optionally, missing values need to be replaced with zeros and indicated via the `past_observed_mask`.
684
+
685
+ For multivariate time series, the `input_size` > 1 dimension is required and corresponds to the number of
686
+ variates in the time series per time step.
687
+ past_time_features (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_features)`):
688
+ Required time features, which the model internally will add to `past_values`. These could be things like
689
+ "month of year", "day of the month", etc. encoded as vectors (for instance as Fourier features). These
690
+ could also be so-called "age" features, which basically help the model know "at which point in life" a
691
+ time-series is. Age features have small values for distant past time steps and increase monotonically the
692
+ more we approach the current time step. Holiday features are also a good example of time features.
693
+
694
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT, where
695
+ the position encodings are learned from scratch internally as parameters of the model, the Time Series
696
+ Transformer requires to provide additional time features. The Time Series Transformer only learns
697
+ additional embeddings for `static_categorical_features`.
698
+
699
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these features
700
+ must but known at prediction time.
701
+
702
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
703
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`, *optional*):
704
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected in
705
+ `[0, 1]`:
706
+
707
+ - 1 for values that are **observed**,
708
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
709
+
710
+ static_categorical_features (`torch.LongTensor` of shape `(batch_size, number of static categorical features)`, *optional*):
711
+ Optional static categorical features for which the model will learn an embedding, which it will add to the
712
+ values of the time series.
713
+
714
+ Static categorical features are features which have the same value for all time steps (static over time).
715
+
716
+ A typical example of a static categorical feature is a time series ID.
717
+ static_real_features (`torch.FloatTensor` of shape `(batch_size, number of static real features)`, *optional*):
718
+ Optional static real features which the model will add to the values of the time series.
719
+
720
+ Static real features are features which have the same value for all time steps (static over time).
721
+
722
+ A typical example of a static real feature is promotion information.
723
+ future_values (`torch.FloatTensor` of shape `(batch_size, prediction_length)` or `(batch_size, prediction_length, input_size)`, *optional*):
724
+ Future values of the time series, that serve as labels for the model. The `future_values` is what the
725
+ Transformer needs during training to learn to output, given the `past_values`.
726
+
727
+ The sequence length here is equal to `prediction_length`.
728
+
729
+ See the demo notebook and code snippets for details.
730
+
731
+ Optionally, during training any missing values need to be replaced with zeros and indicated via the
732
+ `future_observed_mask`.
733
+
734
+ For multivariate time series, the `input_size` > 1 dimension is required and corresponds to the number of
735
+ variates in the time series per time step.
736
+ future_time_features (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_features)`):
737
+ Required time features for the prediction window, which the model internally will add to `future_values`.
738
+ These could be things like "month of year", "day of the month", etc. encoded as vectors (for instance as
739
+ Fourier features). These could also be so-called "age" features, which basically help the model know "at
740
+ which point in life" a time-series is. Age features have small values for distant past time steps and
741
+ increase monotonically the more we approach the current time step. Holiday features are also a good example
742
+ of time features.
743
+
744
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT, where
745
+ the position encodings are learned from scratch internally as parameters of the model, the Time Series
746
+ Transformer requires to provide additional time features. The Time Series Transformer only learns
747
+ additional embeddings for `static_categorical_features`.
748
+
749
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these features
750
+ must but known at prediction time.
751
+
752
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
753
+ future_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`, *optional*):
754
+ Boolean mask to indicate which `future_values` were observed and which were missing. Mask values selected
755
+ in `[0, 1]`:
756
+
757
+ - 1 for values that are **observed**,
758
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
759
+
760
+ This mask is used to filter out missing values for the final loss calculation.
761
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
762
+ Mask to avoid performing attention on certain token indices. Mask values selected in `[0, 1]`:
763
+
764
+ - 1 for tokens that are **not masked**,
765
+ - 0 for tokens that are **masked**.
766
+
767
+ [What are attention masks?](../glossary#attention-mask)
768
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
769
+ Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to
770
+ make sure the model can only look at previous inputs in order to predict the future.
771
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
772
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
773
+
774
+ - 1 indicates the head is **not masked**,
775
+ - 0 indicates the head is **masked**.
776
+
777
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
778
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
779
+
780
+ - 1 indicates the head is **not masked**,
781
+ - 0 indicates the head is **masked**.
782
+
783
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
784
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
785
+
786
+ - 1 indicates the head is **not masked**,
787
+ - 0 indicates the head is **masked**.
788
+
789
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
790
+ Tuple consists of `last_hidden_state`, `hidden_states` (*optional*) and `attentions` (*optional*)
791
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` (*optional*) is a sequence of
792
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
793
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
794
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
795
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
796
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
797
+
798
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
799
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
800
+
801
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
802
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
803
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
804
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
805
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
806
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
807
+ model's internal embedding lookup matrix.
808
+ use_cache (`bool`, *optional*):
809
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
810
+ `past_key_values`).
811
+ output_attentions (`bool`, *optional*):
812
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
813
+ tensors for more detail.
814
+ output_hidden_states (`bool`, *optional*):
815
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
816
+ more detail.
817
+ return_dict (`bool`, *optional*):
818
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
819
+ """
820
+
821
+
822
+ class TimeSeriesTransformerEncoder(TimeSeriesTransformerPreTrainedModel):
823
+ """
824
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
825
+ [`TimeSeriesTransformerEncoderLayer`].
826
+
827
+ Args:
828
+ config: TimeSeriesTransformerConfig
829
+ """
830
+
831
+ def __init__(self, config: TimeSeriesTransformerConfig):
832
+ super().__init__(config)
833
+
834
+ self.dropout = config.dropout
835
+ self.layerdrop = config.encoder_layerdrop
836
+ if config.prediction_length is None:
837
+ raise ValueError("The `prediction_length` config needs to be specified.")
838
+
839
+ self.value_embedding = TimeSeriesValueEmbedding(feature_size=config.feature_size, d_model=config.d_model)
840
+ self.embed_positions = TimeSeriesSinusoidalPositionalEmbedding(
841
+ config.context_length + config.prediction_length, config.d_model
842
+ )
843
+ self.layers = nn.ModuleList([TimeSeriesTransformerEncoderLayer(config) for _ in range(config.encoder_layers)])
844
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
845
+
846
+ self.gradient_checkpointing = False
847
+ # Initialize weights and apply final processing
848
+ self.post_init()
849
+
850
+ def forward(
851
+ self,
852
+ attention_mask: Optional[torch.Tensor] = None,
853
+ head_mask: Optional[torch.Tensor] = None,
854
+ inputs_embeds: Optional[torch.FloatTensor] = None,
855
+ output_attentions: Optional[bool] = None,
856
+ output_hidden_states: Optional[bool] = None,
857
+ return_dict: Optional[bool] = None,
858
+ ) -> Union[Tuple, BaseModelOutput]:
859
+ r"""
860
+ Args:
861
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
862
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
863
+
864
+ - 1 for tokens that are **not masked**,
865
+ - 0 for tokens that are **masked**.
866
+
867
+ [What are attention masks?](../glossary#attention-mask)
868
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
869
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
870
+
871
+ - 1 indicates the head is **not masked**,
872
+ - 0 indicates the head is **masked**.
873
+
874
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
875
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
876
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
877
+ than the model's internal embedding lookup matrix.
878
+ output_attentions (`bool`, *optional*):
879
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
880
+ returned tensors for more detail.
881
+ output_hidden_states (`bool`, *optional*):
882
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
883
+ for more detail.
884
+ return_dict (`bool`, *optional*):
885
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
886
+ """
887
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
888
+ output_hidden_states = (
889
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
890
+ )
891
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
892
+
893
+ hidden_states = self.value_embedding(inputs_embeds)
894
+ embed_pos = self.embed_positions(inputs_embeds.size())
895
+
896
+ hidden_states = self.layernorm_embedding(hidden_states + embed_pos)
897
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
898
+
899
+ # expand attention_mask
900
+ if attention_mask is not None:
901
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
902
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
903
+
904
+ encoder_states = () if output_hidden_states else None
905
+ all_attentions = () if output_attentions else None
906
+
907
+ # check if head_mask has a correct number of layers specified if desired
908
+ if head_mask is not None:
909
+ if head_mask.size()[0] != (len(self.layers)):
910
+ raise ValueError(
911
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
912
+ f" {head_mask.size()[0]}."
913
+ )
914
+
915
+ for idx, encoder_layer in enumerate(self.layers):
916
+ if output_hidden_states:
917
+ encoder_states = encoder_states + (hidden_states,)
918
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
919
+ to_drop = False
920
+ if self.training:
921
+ dropout_probability = torch.rand([])
922
+ if dropout_probability < self.layerdrop: # skip the layer
923
+ to_drop = True
924
+
925
+ if to_drop:
926
+ layer_outputs = (None, None)
927
+ else:
928
+ if self.gradient_checkpointing and self.training:
929
+ layer_outputs = self._gradient_checkpointing_func(
930
+ encoder_layer.__call__,
931
+ hidden_states,
932
+ attention_mask,
933
+ (head_mask[idx] if head_mask is not None else None),
934
+ output_attentions,
935
+ )
936
+ else:
937
+ layer_outputs = encoder_layer(
938
+ hidden_states,
939
+ attention_mask,
940
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
941
+ output_attentions=output_attentions,
942
+ )
943
+
944
+ hidden_states = layer_outputs[0]
945
+
946
+ if output_attentions:
947
+ all_attentions = all_attentions + (layer_outputs[1],)
948
+
949
+ if output_hidden_states:
950
+ encoder_states = encoder_states + (hidden_states,)
951
+
952
+ if not return_dict:
953
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
954
+ return BaseModelOutput(
955
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
956
+ )
957
+
958
+
959
+ class TimeSeriesTransformerDecoder(TimeSeriesTransformerPreTrainedModel):
960
+ """
961
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a
962
+ [`TimeSeriesTransformerDecoderLayer`]
963
+
964
+ Args:
965
+ config: TimeSeriesTransformerConfig
966
+ """
967
+
968
+ def __init__(self, config: TimeSeriesTransformerConfig):
969
+ super().__init__(config)
970
+ self.dropout = config.dropout
971
+ self.layerdrop = config.decoder_layerdrop
972
+ if config.prediction_length is None:
973
+ raise ValueError("The `prediction_length` config needs to be specified.")
974
+
975
+ self.value_embedding = TimeSeriesValueEmbedding(feature_size=config.feature_size, d_model=config.d_model)
976
+ self.embed_positions = TimeSeriesSinusoidalPositionalEmbedding(
977
+ config.context_length + config.prediction_length, config.d_model
978
+ )
979
+ self.layers = nn.ModuleList([TimeSeriesTransformerDecoderLayer(config) for _ in range(config.decoder_layers)])
980
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
981
+
982
+ self.gradient_checkpointing = False
983
+ # Initialize weights and apply final processing
984
+ self.post_init()
985
+
986
+ def forward(
987
+ self,
988
+ attention_mask: Optional[torch.Tensor] = None,
989
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
990
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
991
+ head_mask: Optional[torch.Tensor] = None,
992
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
993
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
994
+ inputs_embeds: Optional[torch.FloatTensor] = None,
995
+ use_cache: Optional[bool] = None,
996
+ output_attentions: Optional[bool] = None,
997
+ output_hidden_states: Optional[bool] = None,
998
+ return_dict: Optional[bool] = None,
999
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
1000
+ r"""
1001
+ Args:
1002
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1003
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1004
+
1005
+ - 1 for tokens that are **not masked**,
1006
+ - 0 for tokens that are **masked**.
1007
+
1008
+ [What are attention masks?](../glossary#attention-mask)
1009
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1010
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1011
+ of the decoder.
1012
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1013
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
1014
+ selected in `[0, 1]`:
1015
+
1016
+ - 1 for tokens that are **not masked**,
1017
+ - 0 for tokens that are **masked**.
1018
+
1019
+ [What are attention masks?](../glossary#attention-mask)
1020
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1021
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1022
+
1023
+ - 1 indicates the head is **not masked**,
1024
+ - 0 indicates the head is **masked**.
1025
+
1026
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1027
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
1028
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
1029
+
1030
+ - 1 indicates the head is **not masked**,
1031
+ - 0 indicates the head is **masked**.
1032
+
1033
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1034
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1035
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1036
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1037
+
1038
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1039
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1040
+
1041
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1042
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1043
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1044
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1045
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1046
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1047
+ than the model's internal embedding lookup matrix.
1048
+ output_attentions (`bool`, *optional*):
1049
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1050
+ returned tensors for more detail.
1051
+ output_hidden_states (`bool`, *optional*):
1052
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1053
+ for more detail.
1054
+ return_dict (`bool`, *optional*):
1055
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1056
+ """
1057
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1058
+ output_hidden_states = (
1059
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1060
+ )
1061
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1062
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1063
+
1064
+ input_shape = inputs_embeds.size()[:-1]
1065
+
1066
+ # past_key_values_length
1067
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1068
+
1069
+ attention_mask = _prepare_4d_causal_attention_mask(
1070
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1071
+ )
1072
+
1073
+ # expand encoder attention mask
1074
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1075
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1076
+ encoder_attention_mask = _prepare_4d_attention_mask(
1077
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1078
+ )
1079
+
1080
+ hidden_states = self.value_embedding(inputs_embeds)
1081
+ embed_pos = self.embed_positions(inputs_embeds.size(), past_key_values_length=self.config.context_length)
1082
+ hidden_states = self.layernorm_embedding(hidden_states + embed_pos)
1083
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1084
+
1085
+ if self.gradient_checkpointing and self.training:
1086
+ if use_cache:
1087
+ logger.warning_once(
1088
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1089
+ )
1090
+ use_cache = False
1091
+
1092
+ # decoder layers
1093
+ all_hidden_states = () if output_hidden_states else None
1094
+ all_self_attns = () if output_attentions else None
1095
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1096
+ next_decoder_cache = () if use_cache else None
1097
+
1098
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1099
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1100
+ if attn_mask is not None:
1101
+ if attn_mask.size()[0] != (len(self.layers)):
1102
+ raise ValueError(
1103
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1104
+ f" {head_mask.size()[0]}."
1105
+ )
1106
+
1107
+ for idx, decoder_layer in enumerate(self.layers):
1108
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1109
+ if output_hidden_states:
1110
+ all_hidden_states += (hidden_states,)
1111
+ if self.training:
1112
+ dropout_probability = torch.rand([])
1113
+ if dropout_probability < self.layerdrop:
1114
+ continue
1115
+
1116
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1117
+
1118
+ if self.gradient_checkpointing and self.training:
1119
+ layer_outputs = self._gradient_checkpointing_func(
1120
+ decoder_layer.__call__,
1121
+ hidden_states,
1122
+ attention_mask,
1123
+ encoder_hidden_states,
1124
+ encoder_attention_mask,
1125
+ head_mask[idx] if head_mask is not None else None,
1126
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1127
+ None,
1128
+ output_attentions,
1129
+ use_cache,
1130
+ )
1131
+ else:
1132
+ layer_outputs = decoder_layer(
1133
+ hidden_states,
1134
+ attention_mask=attention_mask,
1135
+ encoder_hidden_states=encoder_hidden_states,
1136
+ encoder_attention_mask=encoder_attention_mask,
1137
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1138
+ cross_attn_layer_head_mask=(
1139
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1140
+ ),
1141
+ past_key_value=past_key_value,
1142
+ output_attentions=output_attentions,
1143
+ use_cache=use_cache,
1144
+ )
1145
+ hidden_states = layer_outputs[0]
1146
+
1147
+ if use_cache:
1148
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1149
+
1150
+ if output_attentions:
1151
+ all_self_attns += (layer_outputs[1],)
1152
+
1153
+ if encoder_hidden_states is not None:
1154
+ all_cross_attentions += (layer_outputs[2],)
1155
+
1156
+ # add hidden states from the last decoder layer
1157
+ if output_hidden_states:
1158
+ all_hidden_states += (hidden_states,)
1159
+
1160
+ next_cache = next_decoder_cache if use_cache else None
1161
+ if not return_dict:
1162
+ return tuple(
1163
+ v
1164
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1165
+ if v is not None
1166
+ )
1167
+ return BaseModelOutputWithPastAndCrossAttentions(
1168
+ last_hidden_state=hidden_states,
1169
+ past_key_values=next_cache,
1170
+ hidden_states=all_hidden_states,
1171
+ attentions=all_self_attns,
1172
+ cross_attentions=all_cross_attentions,
1173
+ )
1174
+
1175
+
1176
+ @add_start_docstrings(
1177
+ "The bare Time Series Transformer Model outputting raw hidden-states without any specific head on top.",
1178
+ TIME_SERIES_TRANSFORMER_START_DOCSTRING,
1179
+ )
1180
+ class TimeSeriesTransformerModel(TimeSeriesTransformerPreTrainedModel):
1181
+ def __init__(self, config: TimeSeriesTransformerConfig):
1182
+ super().__init__(config)
1183
+
1184
+ if config.scaling == "mean" or config.scaling is True:
1185
+ self.scaler = TimeSeriesMeanScaler(config)
1186
+ elif config.scaling == "std":
1187
+ self.scaler = TimeSeriesStdScaler(config)
1188
+ else:
1189
+ self.scaler = TimeSeriesNOPScaler(config)
1190
+
1191
+ if config.num_static_categorical_features > 0:
1192
+ self.embedder = TimeSeriesFeatureEmbedder(
1193
+ cardinalities=config.cardinality,
1194
+ embedding_dims=config.embedding_dimension,
1195
+ )
1196
+
1197
+ # transformer encoder-decoder and mask initializer
1198
+ self.encoder = TimeSeriesTransformerEncoder(config)
1199
+ self.decoder = TimeSeriesTransformerDecoder(config)
1200
+
1201
+ # Initialize weights and apply final processing
1202
+ self.post_init()
1203
+
1204
+ @property
1205
+ def _past_length(self) -> int:
1206
+ return self.config.context_length + max(self.config.lags_sequence)
1207
+
1208
+ def get_lagged_subsequences(
1209
+ self, sequence: torch.Tensor, subsequences_length: int, shift: int = 0
1210
+ ) -> torch.Tensor:
1211
+ """
1212
+ Returns lagged subsequences of a given sequence. Returns a tensor of shape (N, S, C, I),
1213
+ where S = subsequences_length and I = len(indices), containing lagged subsequences. Specifically, lagged[i,
1214
+ j, :, k] = sequence[i, -indices[k]-S+j, :].
1215
+
1216
+ Args:
1217
+ sequence: Tensor
1218
+ The sequence from which lagged subsequences should be extracted. Shape: (N, T, C).
1219
+ subsequences_length : int
1220
+ Length of the subsequences to be extracted.
1221
+ shift: int
1222
+ Shift the lags by this amount back.
1223
+ """
1224
+ sequence_length = sequence.shape[1]
1225
+ indices = [lag - shift for lag in self.config.lags_sequence]
1226
+
1227
+ if max(indices) + subsequences_length > sequence_length:
1228
+ raise ValueError(
1229
+ f"lags cannot go further than history length, found lag {max(indices)} "
1230
+ f"while history length is only {sequence_length}"
1231
+ )
1232
+
1233
+ lagged_values = []
1234
+ for lag_index in indices:
1235
+ begin_index = -lag_index - subsequences_length
1236
+ end_index = -lag_index if lag_index > 0 else None
1237
+ lagged_values.append(sequence[:, begin_index:end_index, ...])
1238
+ return torch.stack(lagged_values, dim=-1)
1239
+
1240
+ def create_network_inputs(
1241
+ self,
1242
+ past_values: torch.Tensor,
1243
+ past_time_features: torch.Tensor,
1244
+ static_categorical_features: Optional[torch.Tensor] = None,
1245
+ static_real_features: Optional[torch.Tensor] = None,
1246
+ past_observed_mask: Optional[torch.Tensor] = None,
1247
+ future_values: Optional[torch.Tensor] = None,
1248
+ future_time_features: Optional[torch.Tensor] = None,
1249
+ ):
1250
+ # time feature
1251
+ time_feat = (
1252
+ torch.cat(
1253
+ (
1254
+ past_time_features[:, self._past_length - self.config.context_length :, ...],
1255
+ future_time_features,
1256
+ ),
1257
+ dim=1,
1258
+ )
1259
+ if future_values is not None
1260
+ else past_time_features[:, self._past_length - self.config.context_length :, ...]
1261
+ )
1262
+
1263
+ # target
1264
+ if past_observed_mask is None:
1265
+ past_observed_mask = torch.ones_like(past_values)
1266
+
1267
+ context = past_values[:, -self.config.context_length :]
1268
+ observed_context = past_observed_mask[:, -self.config.context_length :]
1269
+ _, loc, scale = self.scaler(context, observed_context)
1270
+
1271
+ inputs = (
1272
+ (torch.cat((past_values, future_values), dim=1) - loc) / scale
1273
+ if future_values is not None
1274
+ else (past_values - loc) / scale
1275
+ )
1276
+
1277
+ # static features
1278
+ log_abs_loc = loc.abs().log1p() if self.config.input_size == 1 else loc.squeeze(1).abs().log1p()
1279
+ log_scale = scale.log() if self.config.input_size == 1 else scale.squeeze(1).log()
1280
+ static_feat = torch.cat((log_abs_loc, log_scale), dim=1)
1281
+
1282
+ if static_real_features is not None:
1283
+ static_feat = torch.cat((static_real_features, static_feat), dim=1)
1284
+ if static_categorical_features is not None:
1285
+ embedded_cat = self.embedder(static_categorical_features)
1286
+ static_feat = torch.cat((embedded_cat, static_feat), dim=1)
1287
+ expanded_static_feat = static_feat.unsqueeze(1).expand(-1, time_feat.shape[1], -1)
1288
+
1289
+ # all features
1290
+ features = torch.cat((expanded_static_feat, time_feat), dim=-1)
1291
+
1292
+ # lagged features
1293
+ subsequences_length = (
1294
+ self.config.context_length + self.config.prediction_length
1295
+ if future_values is not None
1296
+ else self.config.context_length
1297
+ )
1298
+ lagged_sequence = self.get_lagged_subsequences(sequence=inputs, subsequences_length=subsequences_length)
1299
+ lags_shape = lagged_sequence.shape
1300
+ reshaped_lagged_sequence = lagged_sequence.reshape(lags_shape[0], lags_shape[1], -1)
1301
+
1302
+ if reshaped_lagged_sequence.shape[1] != time_feat.shape[1]:
1303
+ raise ValueError(
1304
+ f"input length {reshaped_lagged_sequence.shape[1]} and time feature lengths {time_feat.shape[1]} does not match"
1305
+ )
1306
+
1307
+ # transformer inputs
1308
+ transformer_inputs = torch.cat((reshaped_lagged_sequence, features), dim=-1)
1309
+
1310
+ return transformer_inputs, loc, scale, static_feat
1311
+
1312
+ def get_encoder(self):
1313
+ return self.encoder
1314
+
1315
+ def get_decoder(self):
1316
+ return self.decoder
1317
+
1318
+ @add_start_docstrings_to_model_forward(TIME_SERIES_TRANSFORMER_INPUTS_DOCSTRING)
1319
+ @replace_return_docstrings(output_type=Seq2SeqTSModelOutput, config_class=_CONFIG_FOR_DOC)
1320
+ def forward(
1321
+ self,
1322
+ past_values: torch.Tensor,
1323
+ past_time_features: torch.Tensor,
1324
+ past_observed_mask: torch.Tensor,
1325
+ static_categorical_features: Optional[torch.Tensor] = None,
1326
+ static_real_features: Optional[torch.Tensor] = None,
1327
+ future_values: Optional[torch.Tensor] = None,
1328
+ future_time_features: Optional[torch.Tensor] = None,
1329
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1330
+ head_mask: Optional[torch.Tensor] = None,
1331
+ decoder_head_mask: Optional[torch.Tensor] = None,
1332
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1333
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1334
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1335
+ output_hidden_states: Optional[bool] = None,
1336
+ output_attentions: Optional[bool] = None,
1337
+ use_cache: Optional[bool] = None,
1338
+ return_dict: Optional[bool] = None,
1339
+ ) -> Union[Seq2SeqTSModelOutput, Tuple]:
1340
+ r"""
1341
+ Returns:
1342
+
1343
+ Examples:
1344
+
1345
+ ```python
1346
+ >>> from huggingface_hub import hf_hub_download
1347
+ >>> import torch
1348
+ >>> from transformers import TimeSeriesTransformerModel
1349
+
1350
+ >>> file = hf_hub_download(
1351
+ ... repo_id="hf-internal-testing/tourism-monthly-batch", filename="train-batch.pt", repo_type="dataset"
1352
+ ... )
1353
+ >>> batch = torch.load(file)
1354
+
1355
+ >>> model = TimeSeriesTransformerModel.from_pretrained("huggingface/time-series-transformer-tourism-monthly")
1356
+
1357
+ >>> # during training, one provides both past and future values
1358
+ >>> # as well as possible additional features
1359
+ >>> outputs = model(
1360
+ ... past_values=batch["past_values"],
1361
+ ... past_time_features=batch["past_time_features"],
1362
+ ... past_observed_mask=batch["past_observed_mask"],
1363
+ ... static_categorical_features=batch["static_categorical_features"],
1364
+ ... static_real_features=batch["static_real_features"],
1365
+ ... future_values=batch["future_values"],
1366
+ ... future_time_features=batch["future_time_features"],
1367
+ ... )
1368
+
1369
+ >>> last_hidden_state = outputs.last_hidden_state
1370
+ ```"""
1371
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1372
+ output_hidden_states = (
1373
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1374
+ )
1375
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1376
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1377
+
1378
+ transformer_inputs, loc, scale, static_feat = self.create_network_inputs(
1379
+ past_values=past_values,
1380
+ past_time_features=past_time_features,
1381
+ past_observed_mask=past_observed_mask,
1382
+ static_categorical_features=static_categorical_features,
1383
+ static_real_features=static_real_features,
1384
+ future_values=future_values,
1385
+ future_time_features=future_time_features,
1386
+ )
1387
+
1388
+ if encoder_outputs is None:
1389
+ enc_input = transformer_inputs[:, : self.config.context_length, ...]
1390
+ encoder_outputs = self.encoder(
1391
+ inputs_embeds=enc_input,
1392
+ head_mask=head_mask,
1393
+ output_attentions=output_attentions,
1394
+ output_hidden_states=output_hidden_states,
1395
+ return_dict=return_dict,
1396
+ )
1397
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1398
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1399
+ encoder_outputs = BaseModelOutput(
1400
+ last_hidden_state=encoder_outputs[0],
1401
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1402
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1403
+ )
1404
+
1405
+ dec_input = transformer_inputs[:, self.config.context_length :, ...]
1406
+ decoder_outputs = self.decoder(
1407
+ inputs_embeds=dec_input,
1408
+ attention_mask=decoder_attention_mask,
1409
+ encoder_hidden_states=encoder_outputs[0],
1410
+ head_mask=decoder_head_mask,
1411
+ cross_attn_head_mask=cross_attn_head_mask,
1412
+ past_key_values=past_key_values,
1413
+ use_cache=use_cache,
1414
+ output_attentions=output_attentions,
1415
+ output_hidden_states=output_hidden_states,
1416
+ return_dict=return_dict,
1417
+ )
1418
+
1419
+ if not return_dict:
1420
+ return decoder_outputs + encoder_outputs + (loc, scale, static_feat)
1421
+
1422
+ return Seq2SeqTSModelOutput(
1423
+ last_hidden_state=decoder_outputs.last_hidden_state,
1424
+ past_key_values=decoder_outputs.past_key_values,
1425
+ decoder_hidden_states=decoder_outputs.hidden_states,
1426
+ decoder_attentions=decoder_outputs.attentions,
1427
+ cross_attentions=decoder_outputs.cross_attentions,
1428
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1429
+ encoder_hidden_states=encoder_outputs.hidden_states,
1430
+ encoder_attentions=encoder_outputs.attentions,
1431
+ loc=loc,
1432
+ scale=scale,
1433
+ static_features=static_feat,
1434
+ )
1435
+
1436
+
1437
+ @add_start_docstrings(
1438
+ "The Time Series Transformer Model with a distribution head on top for time-series forecasting.",
1439
+ TIME_SERIES_TRANSFORMER_START_DOCSTRING,
1440
+ )
1441
+ class TimeSeriesTransformerForPrediction(TimeSeriesTransformerPreTrainedModel):
1442
+ def __init__(self, config: TimeSeriesTransformerConfig):
1443
+ super().__init__(config)
1444
+ self.model = TimeSeriesTransformerModel(config)
1445
+ if config.distribution_output == "student_t":
1446
+ self.distribution_output = StudentTOutput(dim=config.input_size)
1447
+ elif config.distribution_output == "normal":
1448
+ self.distribution_output = NormalOutput(dim=config.input_size)
1449
+ elif config.distribution_output == "negative_binomial":
1450
+ self.distribution_output = NegativeBinomialOutput(dim=config.input_size)
1451
+ else:
1452
+ raise ValueError(f"Unknown distribution output {config.distribution_output}")
1453
+
1454
+ self.parameter_projection = self.distribution_output.get_parameter_projection(self.model.config.d_model)
1455
+ self.target_shape = self.distribution_output.event_shape
1456
+
1457
+ if config.loss == "nll":
1458
+ self.loss = nll
1459
+ else:
1460
+ raise ValueError(f"Unknown loss function {config.loss}")
1461
+
1462
+ # Initialize weights of distribution_output and apply final processing
1463
+ self.post_init()
1464
+
1465
+ def output_params(self, dec_output):
1466
+ return self.parameter_projection(dec_output)
1467
+
1468
+ def get_encoder(self):
1469
+ return self.model.get_encoder()
1470
+
1471
+ def get_decoder(self):
1472
+ return self.model.get_decoder()
1473
+
1474
+ @torch.jit.ignore
1475
+ def output_distribution(self, params, loc=None, scale=None, trailing_n=None) -> torch.distributions.Distribution:
1476
+ sliced_params = params
1477
+ if trailing_n is not None:
1478
+ sliced_params = [p[:, -trailing_n:] for p in params]
1479
+ return self.distribution_output.distribution(sliced_params, loc=loc, scale=scale)
1480
+
1481
+ @add_start_docstrings_to_model_forward(TIME_SERIES_TRANSFORMER_INPUTS_DOCSTRING)
1482
+ @replace_return_docstrings(output_type=Seq2SeqTSModelOutput, config_class=_CONFIG_FOR_DOC)
1483
+ def forward(
1484
+ self,
1485
+ past_values: torch.Tensor,
1486
+ past_time_features: torch.Tensor,
1487
+ past_observed_mask: torch.Tensor,
1488
+ static_categorical_features: Optional[torch.Tensor] = None,
1489
+ static_real_features: Optional[torch.Tensor] = None,
1490
+ future_values: Optional[torch.Tensor] = None,
1491
+ future_time_features: Optional[torch.Tensor] = None,
1492
+ future_observed_mask: Optional[torch.Tensor] = None,
1493
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1494
+ head_mask: Optional[torch.Tensor] = None,
1495
+ decoder_head_mask: Optional[torch.Tensor] = None,
1496
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1497
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1498
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1499
+ output_hidden_states: Optional[bool] = None,
1500
+ output_attentions: Optional[bool] = None,
1501
+ use_cache: Optional[bool] = None,
1502
+ return_dict: Optional[bool] = None,
1503
+ ) -> Union[Seq2SeqTSModelOutput, Tuple]:
1504
+ r"""
1505
+ Returns:
1506
+
1507
+ Examples:
1508
+
1509
+ ```python
1510
+ >>> from huggingface_hub import hf_hub_download
1511
+ >>> import torch
1512
+ >>> from transformers import TimeSeriesTransformerForPrediction
1513
+
1514
+ >>> file = hf_hub_download(
1515
+ ... repo_id="hf-internal-testing/tourism-monthly-batch", filename="train-batch.pt", repo_type="dataset"
1516
+ ... )
1517
+ >>> batch = torch.load(file)
1518
+
1519
+ >>> model = TimeSeriesTransformerForPrediction.from_pretrained(
1520
+ ... "huggingface/time-series-transformer-tourism-monthly"
1521
+ ... )
1522
+
1523
+ >>> # during training, one provides both past and future values
1524
+ >>> # as well as possible additional features
1525
+ >>> outputs = model(
1526
+ ... past_values=batch["past_values"],
1527
+ ... past_time_features=batch["past_time_features"],
1528
+ ... past_observed_mask=batch["past_observed_mask"],
1529
+ ... static_categorical_features=batch["static_categorical_features"],
1530
+ ... static_real_features=batch["static_real_features"],
1531
+ ... future_values=batch["future_values"],
1532
+ ... future_time_features=batch["future_time_features"],
1533
+ ... )
1534
+
1535
+ >>> loss = outputs.loss
1536
+ >>> loss.backward()
1537
+
1538
+ >>> # during inference, one only provides past values
1539
+ >>> # as well as possible additional features
1540
+ >>> # the model autoregressively generates future values
1541
+ >>> outputs = model.generate(
1542
+ ... past_values=batch["past_values"],
1543
+ ... past_time_features=batch["past_time_features"],
1544
+ ... past_observed_mask=batch["past_observed_mask"],
1545
+ ... static_categorical_features=batch["static_categorical_features"],
1546
+ ... static_real_features=batch["static_real_features"],
1547
+ ... future_time_features=batch["future_time_features"],
1548
+ ... )
1549
+
1550
+ >>> mean_prediction = outputs.sequences.mean(dim=1)
1551
+ ```"""
1552
+
1553
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1554
+ if future_values is not None:
1555
+ use_cache = False
1556
+
1557
+ outputs = self.model(
1558
+ past_values=past_values,
1559
+ past_time_features=past_time_features,
1560
+ past_observed_mask=past_observed_mask,
1561
+ static_categorical_features=static_categorical_features,
1562
+ static_real_features=static_real_features,
1563
+ future_values=future_values,
1564
+ future_time_features=future_time_features,
1565
+ decoder_attention_mask=decoder_attention_mask,
1566
+ head_mask=head_mask,
1567
+ decoder_head_mask=decoder_head_mask,
1568
+ cross_attn_head_mask=cross_attn_head_mask,
1569
+ encoder_outputs=encoder_outputs,
1570
+ past_key_values=past_key_values,
1571
+ output_hidden_states=output_hidden_states,
1572
+ output_attentions=output_attentions,
1573
+ use_cache=use_cache,
1574
+ return_dict=return_dict,
1575
+ )
1576
+
1577
+ prediction_loss = None
1578
+ params = None
1579
+ if future_values is not None:
1580
+ params = self.output_params(outputs[0]) # outputs.last_hidden_state
1581
+ # loc is 3rd last and scale is 2nd last output
1582
+ distribution = self.output_distribution(params, loc=outputs[-3], scale=outputs[-2])
1583
+
1584
+ loss = self.loss(distribution, future_values)
1585
+
1586
+ if future_observed_mask is None:
1587
+ future_observed_mask = torch.ones_like(future_values)
1588
+
1589
+ if len(self.target_shape) == 0:
1590
+ loss_weights = future_observed_mask
1591
+ else:
1592
+ loss_weights, _ = future_observed_mask.min(dim=-1, keepdim=False)
1593
+
1594
+ prediction_loss = weighted_average(loss, weights=loss_weights)
1595
+
1596
+ if not return_dict:
1597
+ outputs = ((params,) + outputs[1:]) if params is not None else outputs[1:]
1598
+ return ((prediction_loss,) + outputs) if prediction_loss is not None else outputs
1599
+
1600
+ return Seq2SeqTSPredictionOutput(
1601
+ loss=prediction_loss,
1602
+ params=params,
1603
+ past_key_values=outputs.past_key_values,
1604
+ decoder_hidden_states=outputs.decoder_hidden_states,
1605
+ decoder_attentions=outputs.decoder_attentions,
1606
+ cross_attentions=outputs.cross_attentions,
1607
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1608
+ encoder_hidden_states=outputs.encoder_hidden_states,
1609
+ encoder_attentions=outputs.encoder_attentions,
1610
+ loc=outputs.loc,
1611
+ scale=outputs.scale,
1612
+ static_features=outputs.static_features,
1613
+ )
1614
+
1615
+ @torch.no_grad()
1616
+ def generate(
1617
+ self,
1618
+ past_values: torch.Tensor,
1619
+ past_time_features: torch.Tensor,
1620
+ future_time_features: torch.Tensor,
1621
+ past_observed_mask: Optional[torch.Tensor] = None,
1622
+ static_categorical_features: Optional[torch.Tensor] = None,
1623
+ static_real_features: Optional[torch.Tensor] = None,
1624
+ output_attentions: Optional[bool] = None,
1625
+ output_hidden_states: Optional[bool] = None,
1626
+ ) -> SampleTSPredictionOutput:
1627
+ r"""
1628
+ Greedily generate sequences of sample predictions from a model with a probability distribution head.
1629
+
1630
+ Parameters:
1631
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`):
1632
+ Past values of the time series, that serve as context in order to predict the future. The sequence size
1633
+ of this tensor must be larger than the `context_length` of the model, since the model will use the
1634
+ larger size to construct lag features, i.e. additional values from the past which are added in order to
1635
+ serve as "extra context".
1636
+
1637
+ The `sequence_length` here is equal to `config.context_length` + `max(config.lags_sequence)`, which if
1638
+ no `lags_sequence` is configured, is equal to `config.context_length` + 7 (as by default, the largest
1639
+ look-back index in `config.lags_sequence` is 7). The property `_past_length` returns the actual length
1640
+ of the past.
1641
+
1642
+ The `past_values` is what the Transformer encoder gets as input (with optional additional features,
1643
+ such as `static_categorical_features`, `static_real_features`, `past_time_features` and lags).
1644
+
1645
+ Optionally, missing values need to be replaced with zeros and indicated via the `past_observed_mask`.
1646
+
1647
+ For multivariate time series, the `input_size` > 1 dimension is required and corresponds to the number
1648
+ of variates in the time series per time step.
1649
+ past_time_features (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_features)`):
1650
+ Required time features, which the model internally will add to `past_values`. These could be things
1651
+ like "month of year", "day of the month", etc. encoded as vectors (for instance as Fourier features).
1652
+ These could also be so-called "age" features, which basically help the model know "at which point in
1653
+ life" a time-series is. Age features have small values for distant past time steps and increase
1654
+ monotonically the more we approach the current time step. Holiday features are also a good example of
1655
+ time features.
1656
+
1657
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT,
1658
+ where the position encodings are learned from scratch internally as parameters of the model, the Time
1659
+ Series Transformer requires to provide additional time features. The Time Series Transformer only
1660
+ learns additional embeddings for `static_categorical_features`.
1661
+
1662
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these
1663
+ features must but known at prediction time.
1664
+
1665
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
1666
+ future_time_features (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_features)`):
1667
+ Required time features for the prediction window, which the model internally will add to sampled
1668
+ predictions. These could be things like "month of year", "day of the month", etc. encoded as vectors
1669
+ (for instance as Fourier features). These could also be so-called "age" features, which basically help
1670
+ the model know "at which point in life" a time-series is. Age features have small values for distant
1671
+ past time steps and increase monotonically the more we approach the current time step. Holiday features
1672
+ are also a good example of time features.
1673
+
1674
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT,
1675
+ where the position encodings are learned from scratch internally as parameters of the model, the Time
1676
+ Series Transformer requires to provide additional time features. The Time Series Transformer only
1677
+ learns additional embeddings for `static_categorical_features`.
1678
+
1679
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these
1680
+ features must but known at prediction time.
1681
+
1682
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
1683
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`, *optional*):
1684
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1685
+ in `[0, 1]`:
1686
+
1687
+ - 1 for values that are **observed**,
1688
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1689
+
1690
+ static_categorical_features (`torch.LongTensor` of shape `(batch_size, number of static categorical features)`, *optional*):
1691
+ Optional static categorical features for which the model will learn an embedding, which it will add to
1692
+ the values of the time series.
1693
+
1694
+ Static categorical features are features which have the same value for all time steps (static over
1695
+ time).
1696
+
1697
+ A typical example of a static categorical feature is a time series ID.
1698
+ static_real_features (`torch.FloatTensor` of shape `(batch_size, number of static real features)`, *optional*):
1699
+ Optional static real features which the model will add to the values of the time series.
1700
+
1701
+ Static real features are features which have the same value for all time steps (static over time).
1702
+
1703
+ A typical example of a static real feature is promotion information.
1704
+ output_attentions (`bool`, *optional*):
1705
+ Whether or not to return the attentions tensors of all attention layers.
1706
+ output_hidden_states (`bool`, *optional*):
1707
+ Whether or not to return the hidden states of all layers.
1708
+
1709
+ Return:
1710
+ [`SampleTSPredictionOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
1711
+ samples, prediction_length)` or `(batch_size, number of samples, prediction_length, input_size)` for
1712
+ multivariate predictions.
1713
+ """
1714
+ outputs = self(
1715
+ static_categorical_features=static_categorical_features,
1716
+ static_real_features=static_real_features,
1717
+ past_time_features=past_time_features,
1718
+ past_values=past_values,
1719
+ past_observed_mask=past_observed_mask,
1720
+ future_time_features=future_time_features,
1721
+ future_values=None,
1722
+ output_attentions=output_attentions,
1723
+ output_hidden_states=output_hidden_states,
1724
+ return_dict=True,
1725
+ use_cache=True,
1726
+ )
1727
+
1728
+ decoder = self.model.get_decoder()
1729
+ enc_last_hidden = outputs.encoder_last_hidden_state
1730
+ loc = outputs.loc
1731
+ scale = outputs.scale
1732
+ static_feat = outputs.static_features
1733
+
1734
+ num_parallel_samples = self.config.num_parallel_samples
1735
+ repeated_loc = loc.repeat_interleave(repeats=num_parallel_samples, dim=0)
1736
+ repeated_scale = scale.repeat_interleave(repeats=num_parallel_samples, dim=0)
1737
+
1738
+ repeated_past_values = (
1739
+ past_values.repeat_interleave(repeats=num_parallel_samples, dim=0) - repeated_loc
1740
+ ) / repeated_scale
1741
+
1742
+ expanded_static_feat = static_feat.unsqueeze(1).expand(-1, future_time_features.shape[1], -1)
1743
+ features = torch.cat((expanded_static_feat, future_time_features), dim=-1)
1744
+ repeated_features = features.repeat_interleave(repeats=num_parallel_samples, dim=0)
1745
+
1746
+ repeated_enc_last_hidden = enc_last_hidden.repeat_interleave(repeats=num_parallel_samples, dim=0)
1747
+
1748
+ future_samples = []
1749
+
1750
+ # greedy decoding
1751
+ for k in range(self.config.prediction_length):
1752
+ lagged_sequence = self.model.get_lagged_subsequences(
1753
+ sequence=repeated_past_values,
1754
+ subsequences_length=1 + k,
1755
+ shift=1,
1756
+ )
1757
+
1758
+ lags_shape = lagged_sequence.shape
1759
+ reshaped_lagged_sequence = lagged_sequence.reshape(lags_shape[0], lags_shape[1], -1)
1760
+
1761
+ decoder_input = torch.cat((reshaped_lagged_sequence, repeated_features[:, : k + 1]), dim=-1)
1762
+
1763
+ dec_output = decoder(inputs_embeds=decoder_input, encoder_hidden_states=repeated_enc_last_hidden)
1764
+ dec_last_hidden = dec_output.last_hidden_state
1765
+
1766
+ params = self.parameter_projection(dec_last_hidden[:, -1:])
1767
+ distr = self.output_distribution(params, loc=repeated_loc, scale=repeated_scale)
1768
+ next_sample = distr.sample()
1769
+
1770
+ repeated_past_values = torch.cat(
1771
+ (repeated_past_values, (next_sample - repeated_loc) / repeated_scale), dim=1
1772
+ )
1773
+ future_samples.append(next_sample)
1774
+
1775
+ concat_future_samples = torch.cat(future_samples, dim=1)
1776
+
1777
+ return SampleTSPredictionOutput(
1778
+ sequences=concat_future_samples.reshape(
1779
+ (-1, num_parallel_samples, self.config.prediction_length) + self.target_shape,
1780
+ )
1781
+ )
1782
+
1783
+
1784
+ __all__ = ["TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_timesformer import *
22
+ from .modeling_timesformer import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/configuration_timesformer.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """TimeSformer model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class TimesformerConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`TimesformerModel`]. It is used to instantiate a
27
+ TimeSformer model according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the TimeSformer
29
+ [facebook/timesformer-base-finetuned-k600](https://huggingface.co/facebook/timesformer-base-finetuned-k600)
30
+ architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ image_size (`int`, *optional*, defaults to 224):
37
+ The size (resolution) of each image.
38
+ patch_size (`int`, *optional*, defaults to 16):
39
+ The size (resolution) of each patch.
40
+ num_channels (`int`, *optional*, defaults to 3):
41
+ The number of input channels.
42
+ num_frames (`int`, *optional*, defaults to 8):
43
+ The number of frames in each video.
44
+ hidden_size (`int`, *optional*, defaults to 768):
45
+ Dimensionality of the encoder layers and the pooler layer.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ intermediate_size (`int`, *optional*, defaults to 3072):
51
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
55
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
58
+ The dropout ratio for the attention probabilities.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the layer normalization layers.
63
+ qkv_bias (`bool`, *optional*, defaults to `True`):
64
+ Whether to add a bias to the queries, keys and values.
65
+ attention_type (`str`, *optional*, defaults to `"divided_space_time"`):
66
+ The attention type to use. Must be one of `"divided_space_time"`, `"space_only"`, `"joint_space_time"`.
67
+ drop_path_rate (`float`, *optional*, defaults to 0):
68
+ The dropout ratio for stochastic depth.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ >>> from transformers import TimesformerConfig, TimesformerModel
74
+
75
+ >>> # Initializing a TimeSformer timesformer-base style configuration
76
+ >>> configuration = TimesformerConfig()
77
+
78
+ >>> # Initializing a model from the configuration
79
+ >>> model = TimesformerModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```"""
84
+
85
+ model_type = "timesformer"
86
+
87
+ def __init__(
88
+ self,
89
+ image_size=224,
90
+ patch_size=16,
91
+ num_channels=3,
92
+ num_frames=8,
93
+ hidden_size=768,
94
+ num_hidden_layers=12,
95
+ num_attention_heads=12,
96
+ intermediate_size=3072,
97
+ hidden_act="gelu",
98
+ hidden_dropout_prob=0.0,
99
+ attention_probs_dropout_prob=0.0,
100
+ initializer_range=0.02,
101
+ layer_norm_eps=1e-6,
102
+ qkv_bias=True,
103
+ attention_type="divided_space_time",
104
+ drop_path_rate=0,
105
+ **kwargs,
106
+ ):
107
+ super().__init__(**kwargs)
108
+
109
+ self.image_size = image_size
110
+ self.patch_size = patch_size
111
+ self.num_channels = num_channels
112
+ self.num_frames = num_frames
113
+
114
+ self.hidden_size = hidden_size
115
+ self.num_hidden_layers = num_hidden_layers
116
+ self.num_attention_heads = num_attention_heads
117
+ self.intermediate_size = intermediate_size
118
+ self.hidden_act = hidden_act
119
+ self.hidden_dropout_prob = hidden_dropout_prob
120
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
121
+ self.initializer_range = initializer_range
122
+ self.layer_norm_eps = layer_norm_eps
123
+ self.qkv_bias = qkv_bias
124
+
125
+ self.attention_type = attention_type
126
+ self.drop_path_rate = drop_path_rate
127
+
128
+
129
+ __all__ = ["TimesformerConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/convert_timesformer_to_pytorch.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert TimeSformer checkpoints from the original repository: https://github.com/MCG-NJU/TimeSformer"""
16
+
17
+ import argparse
18
+ import json
19
+
20
+ import gdown
21
+ import numpy as np
22
+ import torch
23
+ from huggingface_hub import hf_hub_download
24
+
25
+ from transformers import TimesformerConfig, TimesformerForVideoClassification, VideoMAEImageProcessor
26
+
27
+
28
+ def get_timesformer_config(model_name):
29
+ config = TimesformerConfig()
30
+
31
+ if "large" in model_name:
32
+ config.num_frames = 96
33
+
34
+ if "hr" in model_name:
35
+ config.num_frames = 16
36
+ config.image_size = 448
37
+
38
+ repo_id = "huggingface/label-files"
39
+ if "k400" in model_name:
40
+ config.num_labels = 400
41
+ filename = "kinetics400-id2label.json"
42
+ elif "k600" in model_name:
43
+ config.num_labels = 600
44
+ filename = "kinetics600-id2label.json"
45
+ elif "ssv2" in model_name:
46
+ config.num_labels = 174
47
+ filename = "something-something-v2-id2label.json"
48
+ else:
49
+ raise ValueError("Model name should either contain 'k400', 'k600' or 'ssv2'.")
50
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
51
+ id2label = {int(k): v for k, v in id2label.items()}
52
+ config.id2label = id2label
53
+ config.label2id = {v: k for k, v in id2label.items()}
54
+
55
+ return config
56
+
57
+
58
+ def rename_key(name):
59
+ if "encoder." in name:
60
+ name = name.replace("encoder.", "")
61
+ if "cls_token" in name:
62
+ name = name.replace("cls_token", "timesformer.embeddings.cls_token")
63
+ if "pos_embed" in name:
64
+ name = name.replace("pos_embed", "timesformer.embeddings.position_embeddings")
65
+ if "time_embed" in name:
66
+ name = name.replace("time_embed", "timesformer.embeddings.time_embeddings")
67
+ if "patch_embed.proj" in name:
68
+ name = name.replace("patch_embed.proj", "timesformer.embeddings.patch_embeddings.projection")
69
+ if "patch_embed.norm" in name:
70
+ name = name.replace("patch_embed.norm", "timesformer.embeddings.norm")
71
+ if "blocks" in name:
72
+ name = name.replace("blocks", "timesformer.encoder.layer")
73
+ if "attn.proj" in name:
74
+ name = name.replace("attn.proj", "attention.output.dense")
75
+ if "attn" in name and "bias" not in name and "temporal" not in name:
76
+ name = name.replace("attn", "attention.self")
77
+ if "attn" in name and "temporal" not in name:
78
+ name = name.replace("attn", "attention.attention")
79
+ if "temporal_norm1" in name:
80
+ name = name.replace("temporal_norm1", "temporal_layernorm")
81
+ if "temporal_attn.proj" in name:
82
+ name = name.replace("temporal_attn", "temporal_attention.output.dense")
83
+ if "temporal_fc" in name:
84
+ name = name.replace("temporal_fc", "temporal_dense")
85
+ if "norm1" in name and "temporal" not in name:
86
+ name = name.replace("norm1", "layernorm_before")
87
+ if "norm2" in name:
88
+ name = name.replace("norm2", "layernorm_after")
89
+ if "mlp.fc1" in name:
90
+ name = name.replace("mlp.fc1", "intermediate.dense")
91
+ if "mlp.fc2" in name:
92
+ name = name.replace("mlp.fc2", "output.dense")
93
+ if "norm.weight" in name and "fc" not in name and "temporal" not in name:
94
+ name = name.replace("norm.weight", "timesformer.layernorm.weight")
95
+ if "norm.bias" in name and "fc" not in name and "temporal" not in name:
96
+ name = name.replace("norm.bias", "timesformer.layernorm.bias")
97
+ if "head" in name:
98
+ name = name.replace("head", "classifier")
99
+
100
+ return name
101
+
102
+
103
+ def convert_state_dict(orig_state_dict, config):
104
+ for key in orig_state_dict.copy().keys():
105
+ val = orig_state_dict.pop(key)
106
+
107
+ if key.startswith("model."):
108
+ key = key.replace("model.", "")
109
+
110
+ if "qkv" in key:
111
+ key_split = key.split(".")
112
+ layer_num = int(key_split[1])
113
+ prefix = "timesformer.encoder.layer."
114
+ if "temporal" in key:
115
+ postfix = ".temporal_attention.attention.qkv."
116
+ else:
117
+ postfix = ".attention.attention.qkv."
118
+ if "weight" in key:
119
+ orig_state_dict[f"{prefix}{layer_num}{postfix}weight"] = val
120
+ else:
121
+ orig_state_dict[f"{prefix}{layer_num}{postfix}bias"] = val
122
+ else:
123
+ orig_state_dict[rename_key(key)] = val
124
+
125
+ return orig_state_dict
126
+
127
+
128
+ # We will verify our results on a video of eating spaghetti
129
+ # Frame indices used: [164 168 172 176 181 185 189 193 198 202 206 210 215 219 223 227]
130
+ def prepare_video():
131
+ file = hf_hub_download(
132
+ repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti.npy", repo_type="dataset"
133
+ )
134
+ video = np.load(file)
135
+ return list(video)
136
+
137
+
138
+ def convert_timesformer_checkpoint(checkpoint_url, pytorch_dump_folder_path, model_name, push_to_hub):
139
+ config = get_timesformer_config(model_name)
140
+
141
+ model = TimesformerForVideoClassification(config)
142
+
143
+ # download original checkpoint, hosted on Google Drive
144
+ output = "pytorch_model.bin"
145
+ gdown.cached_download(checkpoint_url, output, quiet=False)
146
+ files = torch.load(output, map_location="cpu")
147
+ if "model" in files:
148
+ state_dict = files["model"]
149
+ elif "module" in files:
150
+ state_dict = files["module"]
151
+ else:
152
+ state_dict = files["model_state"]
153
+ new_state_dict = convert_state_dict(state_dict, config)
154
+
155
+ model.load_state_dict(new_state_dict)
156
+ model.eval()
157
+
158
+ # verify model on basic input
159
+ image_processor = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5])
160
+ video = prepare_video()
161
+ inputs = image_processor(video[:8], return_tensors="pt")
162
+
163
+ outputs = model(**inputs)
164
+ logits = outputs.logits
165
+
166
+ model_names = [
167
+ # Kinetics-400 checkpoints (hr = high resolution input of 448px instead of 224px)
168
+ "timesformer-base-finetuned-k400",
169
+ "timesformer-large-finetuned-k400",
170
+ "timesformer-hr-finetuned-k400",
171
+ # Kinetics-600 checkpoints (hr = high resolution input of 448px instead of 224px)
172
+ "timesformer-base-finetuned-k600",
173
+ "timesformer-large-finetuned-k600",
174
+ "timesformer-hr-finetuned-k600",
175
+ # Something-Something-v2 checkpoints (hr = high resolution input of 448px instead of 224px)
176
+ "timesformer-base-finetuned-ssv2",
177
+ "timesformer-large-finetuned-ssv2",
178
+ "timesformer-hr-finetuned-ssv2",
179
+ ]
180
+
181
+ # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
182
+ if model_name == "timesformer-base-finetuned-k400":
183
+ expected_shape = torch.Size([1, 400])
184
+ expected_slice = torch.tensor([-0.3016, -0.7713, -0.4205])
185
+ elif model_name == "timesformer-base-finetuned-k600":
186
+ expected_shape = torch.Size([1, 600])
187
+ expected_slice = torch.tensor([-0.7267, -0.7466, 3.2404])
188
+ elif model_name == "timesformer-base-finetuned-ssv2":
189
+ expected_shape = torch.Size([1, 174])
190
+ expected_slice = torch.tensor([-0.9059, 0.6433, -3.1457])
191
+ elif model_name == "timesformer-large-finetuned-k400":
192
+ expected_shape = torch.Size([1, 400])
193
+ expected_slice = torch.tensor([0, 0, 0])
194
+ elif model_name == "timesformer-large-finetuned-k600":
195
+ expected_shape = torch.Size([1, 600])
196
+ expected_slice = torch.tensor([0, 0, 0])
197
+ elif model_name == "timesformer-large-finetuned-ssv2":
198
+ expected_shape = torch.Size([1, 174])
199
+ expected_slice = torch.tensor([0, 0, 0])
200
+ elif model_name == "timesformer-hr-finetuned-k400":
201
+ expected_shape = torch.Size([1, 400])
202
+ expected_slice = torch.tensor([-0.9617, -3.7311, -3.7708])
203
+ elif model_name == "timesformer-hr-finetuned-k600":
204
+ expected_shape = torch.Size([1, 600])
205
+ expected_slice = torch.tensor([2.5273, 0.7127, 1.8848])
206
+ elif model_name == "timesformer-hr-finetuned-ssv2":
207
+ expected_shape = torch.Size([1, 174])
208
+ expected_slice = torch.tensor([-3.6756, -0.7513, 0.7180])
209
+ else:
210
+ raise ValueError(f"Model name not supported. Should be one of {model_names}")
211
+
212
+ # verify logits
213
+ assert logits.shape == expected_shape
214
+ assert torch.allclose(logits[0, :3], expected_slice, atol=1e-4)
215
+ print("Logits ok!")
216
+
217
+ if pytorch_dump_folder_path is not None:
218
+ print(f"Saving model and image processor to {pytorch_dump_folder_path}")
219
+ image_processor.save_pretrained(pytorch_dump_folder_path)
220
+ model.save_pretrained(pytorch_dump_folder_path)
221
+
222
+ if push_to_hub:
223
+ print("Pushing to the hub...")
224
+ model.push_to_hub(f"fcakyon/{model_name}")
225
+
226
+
227
+ if __name__ == "__main__":
228
+ parser = argparse.ArgumentParser()
229
+ # Required parameters
230
+ parser.add_argument(
231
+ "--checkpoint_url",
232
+ default="https://drive.google.com/u/1/uc?id=17yvuYp9L4mn-HpIcK5Zo6K3UoOy1kA5l&export=download",
233
+ type=str,
234
+ help=(
235
+ "URL of the original PyTorch checkpoint (on Google Drive) you'd like to convert. Should be a direct"
236
+ " download link."
237
+ ),
238
+ )
239
+ parser.add_argument(
240
+ "--pytorch_dump_folder_path",
241
+ default="",
242
+ type=str,
243
+ help="Path to the output PyTorch model directory.",
244
+ )
245
+ parser.add_argument("--model_name", default="timesformer-base-finetuned-k400", type=str, help="Name of the model.")
246
+ parser.add_argument(
247
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
248
+ )
249
+
250
+ args = parser.parse_args()
251
+ convert_timesformer_checkpoint(
252
+ args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub
253
+ )
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timesformer/modeling_timesformer.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch TimeSformer model."""
16
+
17
+ import collections
18
+ from typing import Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn.functional
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
30
+ from .configuration_timesformer import TimesformerConfig
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+ _CONFIG_FOR_DOC = "TimesformerConfig"
36
+ _CHECKPOINT_FOR_DOC = "facebook/timesformer"
37
+
38
+
39
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L155
40
+ class TimesformerPatchEmbeddings(nn.Module):
41
+ """Image to Patch Embedding"""
42
+
43
+ def __init__(self, config):
44
+ super().__init__()
45
+
46
+ image_size = config.image_size
47
+ patch_size = config.patch_size
48
+
49
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
50
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
51
+
52
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
53
+ self.image_size = image_size
54
+ self.patch_size = patch_size
55
+ self.num_patches = num_patches
56
+
57
+ self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size, stride=patch_size)
58
+
59
+ def forward(self, pixel_values):
60
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
61
+ pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
62
+
63
+ embeddings = self.projection(pixel_values)
64
+ patch_width = embeddings.size(-1)
65
+ embeddings = embeddings.flatten(2).transpose(1, 2)
66
+ return embeddings, num_frames, patch_width
67
+
68
+
69
+ class TimesformerEmbeddings(nn.Module):
70
+ """
71
+ Construct the patch and position embeddings.
72
+ """
73
+
74
+ def __init__(self, config):
75
+ super().__init__()
76
+
77
+ embed_dim = config.hidden_size
78
+ num_frames = config.num_frames
79
+ drop_rate = config.hidden_dropout_prob
80
+ attention_type = config.attention_type
81
+
82
+ self.attention_type = attention_type
83
+ self.patch_embeddings = TimesformerPatchEmbeddings(config)
84
+ self.num_patches = self.patch_embeddings.num_patches
85
+
86
+ # Positional Embeddings
87
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
88
+ self.position_embeddings = nn.Parameter(torch.zeros(1, self.num_patches + 1, embed_dim))
89
+ self.pos_drop = nn.Dropout(p=drop_rate)
90
+ if attention_type != "space_only":
91
+ self.time_embeddings = nn.Parameter(torch.zeros(1, num_frames, embed_dim))
92
+ self.time_drop = nn.Dropout(p=drop_rate)
93
+
94
+ def forward(self, pixel_values):
95
+ batch_size = pixel_values.shape[0]
96
+
97
+ # create patch embeddings
98
+ embeddings, num_frames, patch_width = self.patch_embeddings(pixel_values)
99
+
100
+ cls_tokens = self.cls_token.expand(embeddings.size(0), -1, -1)
101
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
102
+
103
+ # resizing the positional embeddings in case they don't match the input at inference
104
+ if embeddings.size(1) != self.position_embeddings.size(1):
105
+ position_embeddings = self.position_embeddings
106
+ cls_pos_embed = position_embeddings[0, 0, :].unsqueeze(0).unsqueeze(1)
107
+ other_pos_embed = position_embeddings[0, 1:, :].unsqueeze(0).transpose(1, 2)
108
+ patch_num = int(other_pos_embed.size(2) ** 0.5)
109
+ patch_height = embeddings.size(1) // patch_width
110
+ other_pos_embed = other_pos_embed.reshape(1, embeddings.size(2), patch_num, patch_num)
111
+ new_pos_embed = nn.functional.interpolate(
112
+ other_pos_embed, size=(patch_height, patch_width), mode="nearest"
113
+ )
114
+ new_pos_embed = new_pos_embed.flatten(2)
115
+ new_pos_embed = new_pos_embed.transpose(1, 2)
116
+ new_pos_embed = torch.cat((cls_pos_embed, new_pos_embed), 1)
117
+ embeddings = embeddings + new_pos_embed
118
+ else:
119
+ embeddings = embeddings + self.position_embeddings
120
+ embeddings = self.pos_drop(embeddings)
121
+
122
+ # Time Embeddings
123
+ if self.attention_type != "space_only":
124
+ cls_tokens = embeddings[:batch_size, 0, :].unsqueeze(1)
125
+ embeddings = embeddings[:, 1:]
126
+ _, patch_height, patch_width = embeddings.shape
127
+ embeddings = (
128
+ embeddings.reshape(batch_size, num_frames, patch_height, patch_width)
129
+ .permute(0, 2, 1, 3)
130
+ .reshape(batch_size * patch_height, num_frames, patch_width)
131
+ )
132
+ # Resizing time embeddings in case they don't match
133
+ if num_frames != self.time_embeddings.size(1):
134
+ time_embeddings = self.time_embeddings.transpose(1, 2)
135
+ new_time_embeddings = nn.functional.interpolate(time_embeddings, size=(num_frames), mode="nearest")
136
+ new_time_embeddings = new_time_embeddings.transpose(1, 2)
137
+ embeddings = embeddings + new_time_embeddings
138
+ else:
139
+ embeddings = embeddings + self.time_embeddings
140
+ embeddings = self.time_drop(embeddings)
141
+ embeddings = embeddings.view(batch_size, patch_height, num_frames, patch_width).reshape(
142
+ batch_size, patch_height * num_frames, patch_width
143
+ )
144
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
145
+
146
+ return embeddings
147
+
148
+
149
+ # Copied from transformers.models.beit.modeling_beit.drop_path
150
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
151
+ """
152
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
153
+
154
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
155
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
156
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
157
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
158
+ argument.
159
+ """
160
+ if drop_prob == 0.0 or not training:
161
+ return input
162
+ keep_prob = 1 - drop_prob
163
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
164
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
165
+ random_tensor.floor_() # binarize
166
+ output = input.div(keep_prob) * random_tensor
167
+ return output
168
+
169
+
170
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->TimeSformer
171
+ class TimeSformerDropPath(nn.Module):
172
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
173
+
174
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
175
+ super().__init__()
176
+ self.drop_prob = drop_prob
177
+
178
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
179
+ return drop_path(hidden_states, self.drop_prob, self.training)
180
+
181
+ def extra_repr(self) -> str:
182
+ return "p={}".format(self.drop_prob)
183
+
184
+
185
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L57
186
+ class TimesformerSelfAttention(nn.Module):
187
+ def __init__(self, config: TimesformerConfig):
188
+ super().__init__()
189
+
190
+ num_heads = config.num_attention_heads
191
+ qkv_bias = config.qkv_bias
192
+ attention_dropout_prob = config.attention_probs_dropout_prob
193
+
194
+ self.num_heads = num_heads
195
+ head_dim = config.hidden_size // num_heads
196
+ self.scale = head_dim**-0.5
197
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=qkv_bias)
198
+ self.attn_drop = nn.Dropout(attention_dropout_prob)
199
+
200
+ def forward(self, hidden_states, output_attentions: bool = False):
201
+ batch_size, hidden_size, num_channels = hidden_states.shape
202
+ qkv = (
203
+ self.qkv(hidden_states)
204
+ .reshape(batch_size, hidden_size, 3, self.num_heads, num_channels // self.num_heads)
205
+ .permute(2, 0, 3, 1, 4)
206
+ )
207
+ query, key, value = qkv[0], qkv[1], qkv[2]
208
+
209
+ attention_probs = (query @ key.transpose(-2, -1)) * self.scale
210
+ attention_probs = attention_probs.softmax(dim=-1)
211
+ attention_probs = self.attn_drop(attention_probs)
212
+
213
+ context_layer = (attention_probs @ value).transpose(1, 2).reshape(batch_size, hidden_size, num_channels)
214
+
215
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
216
+
217
+ return outputs
218
+
219
+
220
+ class TimesformerSelfOutput(nn.Module):
221
+ """
222
+ The residual connection is defined in TimesformerLayer instead of here (as is the case with other models), due to
223
+ the layernorm applied before each block.
224
+ """
225
+
226
+ def __init__(self, config: TimesformerConfig) -> None:
227
+ super().__init__()
228
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
229
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
230
+
231
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
232
+ hidden_states = self.dense(hidden_states)
233
+ hidden_states = self.dropout(hidden_states)
234
+
235
+ return hidden_states
236
+
237
+
238
+ class TimeSformerAttention(nn.Module):
239
+ def __init__(self, config: TimesformerConfig) -> None:
240
+ super().__init__()
241
+ self.attention = TimesformerSelfAttention(config)
242
+ self.output = TimesformerSelfOutput(config)
243
+
244
+ def forward(
245
+ self,
246
+ hidden_states: torch.Tensor,
247
+ output_attentions: bool = False,
248
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
249
+ self_outputs = self.attention(hidden_states, output_attentions)
250
+
251
+ attention_output = self.output(self_outputs[0])
252
+
253
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
254
+ return outputs
255
+
256
+
257
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L39
258
+ class TimesformerIntermediate(nn.Module):
259
+ def __init__(self, config: TimesformerConfig) -> None:
260
+ super().__init__()
261
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
262
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
263
+
264
+ if isinstance(config.hidden_act, str):
265
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
266
+ else:
267
+ self.intermediate_act_fn = config.hidden_act
268
+
269
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
270
+ hidden_states = self.dense(hidden_states)
271
+ hidden_states = self.intermediate_act_fn(hidden_states)
272
+ hidden_states = self.dropout(hidden_states)
273
+
274
+ return hidden_states
275
+
276
+
277
+ class TimesformerOutput(nn.Module):
278
+ def __init__(self, config: TimesformerConfig) -> None:
279
+ super().__init__()
280
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
281
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
282
+
283
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
284
+ hidden_states = self.dense(hidden_states)
285
+ hidden_states = self.dropout(hidden_states)
286
+
287
+ return hidden_states
288
+
289
+
290
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L89
291
+ class TimesformerLayer(nn.Module):
292
+ def __init__(self, config: TimesformerConfig, layer_index: int) -> None:
293
+ super().__init__()
294
+
295
+ attention_type = config.attention_type
296
+
297
+ drop_path_rates = [
298
+ x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)
299
+ ] # stochastic depth decay rule
300
+ drop_path_rate = drop_path_rates[layer_index]
301
+
302
+ self.drop_path = TimeSformerDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
303
+ self.attention = TimeSformerAttention(config)
304
+ self.intermediate = TimesformerIntermediate(config)
305
+ self.output = TimesformerOutput(config)
306
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
307
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
308
+
309
+ self.config = config
310
+ self.attention_type = attention_type
311
+ if attention_type not in ["divided_space_time", "space_only", "joint_space_time"]:
312
+ raise ValueError("Unknown attention type: {}".format(attention_type))
313
+
314
+ # Temporal Attention Parameters
315
+ if self.attention_type == "divided_space_time":
316
+ self.temporal_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
317
+ self.temporal_attention = TimeSformerAttention(config)
318
+ self.temporal_dense = nn.Linear(config.hidden_size, config.hidden_size)
319
+
320
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False):
321
+ num_frames = self.config.num_frames
322
+ num_patch_width = self.config.image_size // self.config.patch_size
323
+ batch_size = hidden_states.shape[0]
324
+ num_spatial_tokens = (hidden_states.size(1) - 1) // num_frames
325
+ num_patch_height = num_spatial_tokens // num_patch_width
326
+
327
+ if self.attention_type in ["space_only", "joint_space_time"]:
328
+ self_attention_outputs = self.attention(
329
+ self.layernorm_before(hidden_states), output_attentions=output_attentions
330
+ )
331
+ attention_output = self_attention_outputs[0]
332
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
333
+
334
+ hidden_states = hidden_states + self.drop_path(attention_output)
335
+
336
+ layer_output = self.layernorm_after(hidden_states)
337
+ layer_output = self.intermediate(layer_output)
338
+ layer_output = self.output(layer_output)
339
+ layer_output = hidden_states + self.drop_path(layer_output)
340
+
341
+ outputs = (layer_output,) + outputs
342
+
343
+ return outputs
344
+
345
+ elif self.attention_type == "divided_space_time":
346
+ # Temporal
347
+ temporal_embedding = hidden_states[:, 1:, :]
348
+ temporal_embedding = temporal_embedding.reshape(
349
+ batch_size, num_patch_height, num_patch_width, num_frames, temporal_embedding.shape[2]
350
+ ).reshape(batch_size * num_patch_height * num_patch_width, num_frames, temporal_embedding.shape[2])
351
+
352
+ temporal_attention_outputs = self.temporal_attention(
353
+ self.temporal_layernorm(temporal_embedding),
354
+ )
355
+ attention_output = temporal_attention_outputs[0]
356
+
357
+ residual_temporal = self.drop_path(attention_output)
358
+
359
+ residual_temporal = residual_temporal.reshape(
360
+ batch_size, num_patch_height, num_patch_width, num_frames, residual_temporal.shape[2]
361
+ ).reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_temporal.shape[2])
362
+ residual_temporal = self.temporal_dense(residual_temporal)
363
+ temporal_embedding = hidden_states[:, 1:, :] + residual_temporal
364
+
365
+ # Spatial
366
+ init_cls_token = hidden_states[:, 0, :].unsqueeze(1)
367
+ cls_token = init_cls_token.repeat(1, num_frames, 1)
368
+ cls_token = cls_token.reshape(batch_size * num_frames, 1, cls_token.shape[2])
369
+ spatial_embedding = temporal_embedding
370
+ spatial_embedding = (
371
+ spatial_embedding.reshape(
372
+ batch_size, num_patch_height, num_patch_width, num_frames, spatial_embedding.shape[2]
373
+ )
374
+ .permute(0, 3, 1, 2, 4)
375
+ .reshape(batch_size * num_frames, num_patch_height * num_patch_width, spatial_embedding.shape[2])
376
+ )
377
+ spatial_embedding = torch.cat((cls_token, spatial_embedding), 1)
378
+
379
+ spatial_attention_outputs = self.attention(
380
+ self.layernorm_before(spatial_embedding), output_attentions=output_attentions
381
+ )
382
+ attention_output = spatial_attention_outputs[0]
383
+ outputs = spatial_attention_outputs[1:] # add self attentions if we output attention weights
384
+
385
+ residual_spatial = self.drop_path(attention_output)
386
+
387
+ # Taking care of CLS token
388
+ cls_token = residual_spatial[:, 0, :]
389
+ cls_token = cls_token.reshape(batch_size, num_frames, cls_token.shape[1])
390
+ cls_token = torch.mean(cls_token, 1, True) # averaging for every frame
391
+ residual_spatial = residual_spatial[:, 1:, :]
392
+ residual_spatial = (
393
+ residual_spatial.reshape(
394
+ batch_size, num_frames, num_patch_height, num_patch_width, residual_spatial.shape[2]
395
+ )
396
+ .permute(0, 2, 3, 1, 4)
397
+ .reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_spatial.shape[2])
398
+ )
399
+ residual = residual_spatial
400
+ hidden_states = temporal_embedding
401
+
402
+ # Mlp
403
+ hidden_states = torch.cat((init_cls_token, hidden_states), 1) + torch.cat((cls_token, residual), 1)
404
+ layer_output = self.layernorm_after(hidden_states)
405
+ layer_output = self.intermediate(layer_output)
406
+ layer_output = self.output(layer_output)
407
+ layer_output = hidden_states + self.drop_path(layer_output)
408
+
409
+ outputs = (layer_output,) + outputs
410
+
411
+ return outputs
412
+
413
+
414
+ class TimesformerEncoder(nn.Module):
415
+ def __init__(self, config: TimesformerConfig) -> None:
416
+ super().__init__()
417
+ self.config = config
418
+ self.layer = nn.ModuleList([TimesformerLayer(config, ind) for ind in range(config.num_hidden_layers)])
419
+ self.gradient_checkpointing = False
420
+
421
+ def forward(
422
+ self,
423
+ hidden_states: torch.Tensor,
424
+ output_attentions: bool = False,
425
+ output_hidden_states: bool = False,
426
+ return_dict: bool = True,
427
+ ) -> Union[tuple, BaseModelOutput]:
428
+ all_hidden_states = () if output_hidden_states else None
429
+ all_self_attentions = () if output_attentions else None
430
+
431
+ for i, layer_module in enumerate(self.layer):
432
+ if output_hidden_states:
433
+ all_hidden_states = all_hidden_states + (hidden_states,)
434
+
435
+ if self.gradient_checkpointing and self.training:
436
+ layer_outputs = self._gradient_checkpointing_func(
437
+ layer_module.__call__,
438
+ hidden_states,
439
+ output_attentions,
440
+ )
441
+ else:
442
+ layer_outputs = layer_module(hidden_states, output_attentions)
443
+
444
+ hidden_states = layer_outputs[0]
445
+
446
+ if output_attentions:
447
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
448
+
449
+ if output_hidden_states:
450
+ all_hidden_states = all_hidden_states + (hidden_states,)
451
+
452
+ if not return_dict:
453
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
454
+ return BaseModelOutput(
455
+ last_hidden_state=hidden_states,
456
+ hidden_states=all_hidden_states,
457
+ attentions=all_self_attentions,
458
+ )
459
+
460
+
461
+ class TimesformerPreTrainedModel(PreTrainedModel):
462
+ """
463
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
464
+ models.
465
+ """
466
+
467
+ config_class = TimesformerConfig
468
+ base_model_prefix = "timesformer"
469
+ main_input_name = "pixel_values"
470
+ supports_gradient_checkpointing = True
471
+ _no_split_modules = ["TimesformerLayer"]
472
+
473
+ def _init_weights(self, module):
474
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
475
+ nn.init.trunc_normal_(module.weight, std=self.config.initializer_range)
476
+ if module.bias is not None:
477
+ nn.init.constant_(module.bias, 0)
478
+ elif isinstance(module, nn.LayerNorm):
479
+ nn.init.constant_(module.bias, 0)
480
+ nn.init.constant_(module.weight, 1.0)
481
+ elif isinstance(module, TimesformerEmbeddings):
482
+ nn.init.trunc_normal_(module.cls_token, std=self.config.initializer_range)
483
+ nn.init.trunc_normal_(module.position_embeddings, std=self.config.initializer_range)
484
+ module.patch_embeddings.apply(self._init_weights)
485
+
486
+
487
+ TIMESFORMER_START_DOCSTRING = r"""
488
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
489
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
490
+ behavior.
491
+
492
+ Parameters:
493
+ config ([`TimesformerConfig`]): Model configuration class with all the parameters of the model.
494
+ Initializing with a config file does not load the weights associated with the model, only the
495
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
496
+ """
497
+
498
+ TIMESFORMER_INPUTS_DOCSTRING = r"""
499
+ Args:
500
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
501
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
502
+ [`VideoMAEImageProcessor.preprocess`] for details.
503
+
504
+ output_attentions (`bool`, *optional*):
505
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
506
+ tensors for more detail.
507
+ output_hidden_states (`bool`, *optional*):
508
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
509
+ more detail.
510
+ return_dict (`bool`, *optional*):
511
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
512
+ """
513
+
514
+
515
+ @add_start_docstrings(
516
+ "The bare TimeSformer Model transformer outputting raw hidden-states without any specific head on top.",
517
+ TIMESFORMER_START_DOCSTRING,
518
+ )
519
+ class TimesformerModel(TimesformerPreTrainedModel):
520
+ def __init__(self, config):
521
+ super().__init__(config)
522
+ self.config = config
523
+
524
+ self.embeddings = TimesformerEmbeddings(config)
525
+ self.encoder = TimesformerEncoder(config)
526
+
527
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
528
+
529
+ # Initialize weights and apply final processing
530
+ self.post_init()
531
+
532
+ def get_input_embeddings(self):
533
+ return self.embeddings.patch_embeddings
534
+
535
+ def _prune_heads(self, heads_to_prune):
536
+ """
537
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
538
+ class PreTrainedModel
539
+ """
540
+ for layer, heads in heads_to_prune.items():
541
+ self.encoder.layer[layer].attention.prune_heads(heads)
542
+
543
+ @add_start_docstrings_to_model_forward(TIMESFORMER_INPUTS_DOCSTRING)
544
+ @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
545
+ def forward(
546
+ self,
547
+ pixel_values: torch.FloatTensor,
548
+ output_attentions: Optional[bool] = None,
549
+ output_hidden_states: Optional[bool] = None,
550
+ return_dict: Optional[bool] = None,
551
+ ) -> Union[Tuple[torch.FloatTensor], BaseModelOutput]:
552
+ r"""
553
+ Returns:
554
+
555
+ Examples:
556
+
557
+ ```python
558
+ >>> import av
559
+ >>> import numpy as np
560
+
561
+ >>> from transformers import AutoImageProcessor, TimesformerModel
562
+ >>> from huggingface_hub import hf_hub_download
563
+
564
+ >>> np.random.seed(0)
565
+
566
+
567
+ >>> def read_video_pyav(container, indices):
568
+ ... '''
569
+ ... Decode the video with PyAV decoder.
570
+ ... Args:
571
+ ... container (`av.container.input.InputContainer`): PyAV container.
572
+ ... indices (`List[int]`): List of frame indices to decode.
573
+ ... Returns:
574
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
575
+ ... '''
576
+ ... frames = []
577
+ ... container.seek(0)
578
+ ... start_index = indices[0]
579
+ ... end_index = indices[-1]
580
+ ... for i, frame in enumerate(container.decode(video=0)):
581
+ ... if i > end_index:
582
+ ... break
583
+ ... if i >= start_index and i in indices:
584
+ ... frames.append(frame)
585
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
586
+
587
+
588
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
589
+ ... '''
590
+ ... Sample a given number of frame indices from the video.
591
+ ... Args:
592
+ ... clip_len (`int`): Total number of frames to sample.
593
+ ... frame_sample_rate (`int`): Sample every n-th frame.
594
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
595
+ ... Returns:
596
+ ... indices (`List[int]`): List of sampled frame indices
597
+ ... '''
598
+ ... converted_len = int(clip_len * frame_sample_rate)
599
+ ... end_idx = np.random.randint(converted_len, seg_len)
600
+ ... start_idx = end_idx - converted_len
601
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
602
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
603
+ ... return indices
604
+
605
+
606
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
607
+ >>> file_path = hf_hub_download(
608
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
609
+ ... )
610
+ >>> container = av.open(file_path)
611
+
612
+ >>> # sample 8 frames
613
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
614
+ >>> video = read_video_pyav(container, indices)
615
+
616
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
617
+ >>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
618
+
619
+ >>> # prepare video for the model
620
+ >>> inputs = image_processor(list(video), return_tensors="pt")
621
+
622
+ >>> # forward pass
623
+ >>> outputs = model(**inputs)
624
+ >>> last_hidden_states = outputs.last_hidden_state
625
+ >>> list(last_hidden_states.shape)
626
+ [1, 1569, 768]
627
+ ```"""
628
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
629
+ output_hidden_states = (
630
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
631
+ )
632
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
633
+
634
+ embedding_output = self.embeddings(pixel_values)
635
+
636
+ encoder_outputs = self.encoder(
637
+ embedding_output,
638
+ output_attentions=output_attentions,
639
+ output_hidden_states=output_hidden_states,
640
+ return_dict=return_dict,
641
+ )
642
+ sequence_output = encoder_outputs[0]
643
+ if self.layernorm is not None:
644
+ sequence_output = self.layernorm(sequence_output)
645
+
646
+ if not return_dict:
647
+ return (sequence_output,) + encoder_outputs[1:]
648
+
649
+ return BaseModelOutput(
650
+ last_hidden_state=sequence_output,
651
+ hidden_states=encoder_outputs.hidden_states,
652
+ attentions=encoder_outputs.attentions,
653
+ )
654
+
655
+
656
+ @add_start_docstrings(
657
+ """TimeSformer Model transformer with a video classification head on top (a linear layer on top of the final hidden state
658
+ of the [CLS] token) e.g. for ImageNet.""",
659
+ TIMESFORMER_START_DOCSTRING,
660
+ )
661
+ class TimesformerForVideoClassification(TimesformerPreTrainedModel):
662
+ def __init__(self, config):
663
+ super().__init__(config)
664
+
665
+ self.num_labels = config.num_labels
666
+ self.timesformer = TimesformerModel(config)
667
+
668
+ # Classifier head
669
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
670
+
671
+ # Initialize weights and apply final processing
672
+ self.post_init()
673
+
674
+ @add_start_docstrings_to_model_forward(TIMESFORMER_INPUTS_DOCSTRING)
675
+ @replace_return_docstrings(output_type=ImageClassifierOutput, config_class=_CONFIG_FOR_DOC)
676
+ def forward(
677
+ self,
678
+ pixel_values: Optional[torch.Tensor] = None,
679
+ labels: Optional[torch.Tensor] = None,
680
+ output_attentions: Optional[bool] = None,
681
+ output_hidden_states: Optional[bool] = None,
682
+ return_dict: Optional[bool] = None,
683
+ ) -> Union[Tuple, ImageClassifierOutput]:
684
+ r"""
685
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
686
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
687
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
688
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
689
+
690
+ Returns:
691
+
692
+ Examples:
693
+
694
+ ```python
695
+ >>> import av
696
+ >>> import torch
697
+ >>> import numpy as np
698
+
699
+ >>> from transformers import AutoImageProcessor, TimesformerForVideoClassification
700
+ >>> from huggingface_hub import hf_hub_download
701
+
702
+ >>> np.random.seed(0)
703
+
704
+
705
+ >>> def read_video_pyav(container, indices):
706
+ ... '''
707
+ ... Decode the video with PyAV decoder.
708
+ ... Args:
709
+ ... container (`av.container.input.InputContainer`): PyAV container.
710
+ ... indices (`List[int]`): List of frame indices to decode.
711
+ ... Returns:
712
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
713
+ ... '''
714
+ ... frames = []
715
+ ... container.seek(0)
716
+ ... start_index = indices[0]
717
+ ... end_index = indices[-1]
718
+ ... for i, frame in enumerate(container.decode(video=0)):
719
+ ... if i > end_index:
720
+ ... break
721
+ ... if i >= start_index and i in indices:
722
+ ... frames.append(frame)
723
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
724
+
725
+
726
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
727
+ ... '''
728
+ ... Sample a given number of frame indices from the video.
729
+ ... Args:
730
+ ... clip_len (`int`): Total number of frames to sample.
731
+ ... frame_sample_rate (`int`): Sample every n-th frame.
732
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
733
+ ... Returns:
734
+ ... indices (`List[int]`): List of sampled frame indices
735
+ ... '''
736
+ ... converted_len = int(clip_len * frame_sample_rate)
737
+ ... end_idx = np.random.randint(converted_len, seg_len)
738
+ ... start_idx = end_idx - converted_len
739
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
740
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
741
+ ... return indices
742
+
743
+
744
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
745
+ >>> file_path = hf_hub_download(
746
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
747
+ ... )
748
+ >>> container = av.open(file_path)
749
+
750
+ >>> # sample 8 frames
751
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
752
+ >>> video = read_video_pyav(container, indices)
753
+
754
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
755
+ >>> model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
756
+
757
+ >>> inputs = image_processor(list(video), return_tensors="pt")
758
+
759
+ >>> with torch.no_grad():
760
+ ... outputs = model(**inputs)
761
+ ... logits = outputs.logits
762
+
763
+ >>> # model predicts one of the 400 Kinetics-400 classes
764
+ >>> predicted_label = logits.argmax(-1).item()
765
+ >>> print(model.config.id2label[predicted_label])
766
+ eating spaghetti
767
+ ```"""
768
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
769
+
770
+ outputs = self.timesformer(
771
+ pixel_values,
772
+ output_attentions=output_attentions,
773
+ output_hidden_states=output_hidden_states,
774
+ return_dict=return_dict,
775
+ )
776
+
777
+ sequence_output = outputs[0][:, 0]
778
+
779
+ logits = self.classifier(sequence_output)
780
+
781
+ loss = None
782
+ if labels is not None:
783
+ if self.config.problem_type is None:
784
+ if self.num_labels == 1:
785
+ self.config.problem_type = "regression"
786
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
787
+ self.config.problem_type = "single_label_classification"
788
+ else:
789
+ self.config.problem_type = "multi_label_classification"
790
+
791
+ if self.config.problem_type == "regression":
792
+ loss_fct = MSELoss()
793
+ if self.num_labels == 1:
794
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
795
+ else:
796
+ loss = loss_fct(logits, labels)
797
+ elif self.config.problem_type == "single_label_classification":
798
+ loss_fct = CrossEntropyLoss()
799
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
800
+ elif self.config.problem_type == "multi_label_classification":
801
+ loss_fct = BCEWithLogitsLoss()
802
+ loss = loss_fct(logits, labels)
803
+
804
+ if not return_dict:
805
+ output = (logits,) + outputs[1:]
806
+ return ((loss,) + output) if loss is not None else output
807
+
808
+ return ImageClassifierOutput(
809
+ loss=loss,
810
+ logits=logits,
811
+ hidden_states=outputs.hidden_states,
812
+ attentions=outputs.attentions,
813
+ )
814
+
815
+
816
+ __all__ = ["TimesformerModel", "TimesformerForVideoClassification", "TimesformerPreTrainedModel"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_backbone/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_timm_backbone import *
22
+ from .modeling_timm_backbone import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_backbone/configuration_timm_backbone.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Configuration for Backbone models"""
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class TimmBackboneConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration for a timm backbone [`TimmBackbone`].
28
+
29
+ It is used to instantiate a timm backbone model according to the specified arguments, defining the model.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ backbone (`str`, *optional*):
36
+ The timm checkpoint to load.
37
+ num_channels (`int`, *optional*, defaults to 3):
38
+ The number of input channels.
39
+ features_only (`bool`, *optional*, defaults to `True`):
40
+ Whether to output only the features or also the logits.
41
+ use_pretrained_backbone (`bool`, *optional*, defaults to `True`):
42
+ Whether to use a pretrained backbone.
43
+ out_indices (`List[int]`, *optional*):
44
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
45
+ many stages the model has). Will default to the last stage if unset.
46
+ freeze_batch_norm_2d (`bool`, *optional*, defaults to `False`):
47
+ Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`.
48
+
49
+ Example:
50
+ ```python
51
+ >>> from transformers import TimmBackboneConfig, TimmBackbone
52
+
53
+ >>> # Initializing a timm backbone
54
+ >>> configuration = TimmBackboneConfig("resnet50")
55
+
56
+ >>> # Initializing a model from the configuration
57
+ >>> model = TimmBackbone(configuration)
58
+
59
+ >>> # Accessing the model configuration
60
+ >>> configuration = model.config
61
+ ```
62
+ """
63
+
64
+ model_type = "timm_backbone"
65
+
66
+ def __init__(
67
+ self,
68
+ backbone=None,
69
+ num_channels=3,
70
+ features_only=True,
71
+ use_pretrained_backbone=True,
72
+ out_indices=None,
73
+ freeze_batch_norm_2d=False,
74
+ **kwargs,
75
+ ):
76
+ super().__init__(**kwargs)
77
+ self.backbone = backbone
78
+ self.num_channels = num_channels
79
+ self.features_only = features_only
80
+ self.use_pretrained_backbone = use_pretrained_backbone
81
+ self.use_timm_backbone = True
82
+ self.out_indices = out_indices if out_indices is not None else [-1]
83
+ self.freeze_batch_norm_2d = freeze_batch_norm_2d
84
+
85
+
86
+ __all__ = ["TimmBackboneConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_backbone/modeling_timm_backbone.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional, Tuple, Union
17
+
18
+ import torch
19
+
20
+ from ...modeling_outputs import BackboneOutput
21
+ from ...modeling_utils import PreTrainedModel
22
+ from ...utils import is_timm_available, is_torch_available, requires_backends
23
+ from ...utils.backbone_utils import BackboneMixin
24
+ from .configuration_timm_backbone import TimmBackboneConfig
25
+
26
+
27
+ if is_timm_available():
28
+ import timm
29
+
30
+
31
+ if is_torch_available():
32
+ from torch import Tensor
33
+
34
+
35
+ class TimmBackbone(PreTrainedModel, BackboneMixin):
36
+ """
37
+ Wrapper class for timm models to be used as backbones. This enables using the timm models interchangeably with the
38
+ other models in the library keeping the same API.
39
+ """
40
+
41
+ main_input_name = "pixel_values"
42
+ supports_gradient_checkpointing = False
43
+ config_class = TimmBackboneConfig
44
+
45
+ def __init__(self, config, **kwargs):
46
+ requires_backends(self, "timm")
47
+ super().__init__(config)
48
+ self.config = config
49
+
50
+ if config.backbone is None:
51
+ raise ValueError("backbone is not set in the config. Please set it to a timm model name.")
52
+
53
+ if hasattr(config, "out_features") and config.out_features is not None:
54
+ raise ValueError("out_features is not supported by TimmBackbone. Please use out_indices instead.")
55
+
56
+ pretrained = getattr(config, "use_pretrained_backbone", None)
57
+ if pretrained is None:
58
+ raise ValueError("use_pretrained_backbone is not set in the config. Please set it to True or False.")
59
+
60
+ # We just take the final layer by default. This matches the default for the transformers models.
61
+ out_indices = config.out_indices if getattr(config, "out_indices", None) is not None else (-1,)
62
+
63
+ in_chans = kwargs.pop("in_chans", config.num_channels)
64
+ self._backbone = timm.create_model(
65
+ config.backbone,
66
+ pretrained=pretrained,
67
+ # This is currently not possible for transformer architectures.
68
+ features_only=config.features_only,
69
+ in_chans=in_chans,
70
+ out_indices=out_indices,
71
+ **kwargs,
72
+ )
73
+
74
+ # Converts all `BatchNorm2d` and `SyncBatchNorm` or `BatchNormAct2d` and `SyncBatchNormAct2d` layers of provided module into `FrozenBatchNorm2d` or `FrozenBatchNormAct2d` respectively
75
+ if getattr(config, "freeze_batch_norm_2d", False):
76
+ self.freeze_batch_norm_2d()
77
+
78
+ # These are used to control the output of the model when called. If output_hidden_states is True, then
79
+ # return_layers is modified to include all layers.
80
+ self._return_layers = {
81
+ layer["module"]: str(layer["index"]) for layer in self._backbone.feature_info.get_dicts()
82
+ }
83
+ self._all_layers = {layer["module"]: str(i) for i, layer in enumerate(self._backbone.feature_info.info)}
84
+ super()._init_backbone(config)
85
+
86
+ @classmethod
87
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
88
+ requires_backends(cls, ["vision", "timm"])
89
+ from ...models.timm_backbone import TimmBackboneConfig
90
+
91
+ config = kwargs.pop("config", TimmBackboneConfig())
92
+
93
+ use_timm = kwargs.pop("use_timm_backbone", True)
94
+ if not use_timm:
95
+ raise ValueError("use_timm_backbone must be True for timm backbones")
96
+
97
+ num_channels = kwargs.pop("num_channels", config.num_channels)
98
+ features_only = kwargs.pop("features_only", config.features_only)
99
+ use_pretrained_backbone = kwargs.pop("use_pretrained_backbone", config.use_pretrained_backbone)
100
+ out_indices = kwargs.pop("out_indices", config.out_indices)
101
+ config = TimmBackboneConfig(
102
+ backbone=pretrained_model_name_or_path,
103
+ num_channels=num_channels,
104
+ features_only=features_only,
105
+ use_pretrained_backbone=use_pretrained_backbone,
106
+ out_indices=out_indices,
107
+ )
108
+ return super()._from_config(config, **kwargs)
109
+
110
+ def freeze_batch_norm_2d(self):
111
+ timm.utils.model.freeze_batch_norm_2d(self._backbone)
112
+
113
+ def unfreeze_batch_norm_2d(self):
114
+ timm.utils.model.unfreeze_batch_norm_2d(self._backbone)
115
+
116
+ def _init_weights(self, module):
117
+ """
118
+ Empty init weights function to ensure compatibility of the class in the library.
119
+ """
120
+ pass
121
+
122
+ def forward(
123
+ self,
124
+ pixel_values: torch.FloatTensor,
125
+ output_attentions: Optional[bool] = None,
126
+ output_hidden_states: Optional[bool] = None,
127
+ return_dict: Optional[bool] = None,
128
+ **kwargs,
129
+ ) -> Union[BackboneOutput, Tuple[Tensor, ...]]:
130
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
131
+ output_hidden_states = (
132
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
133
+ )
134
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
135
+
136
+ if output_attentions:
137
+ raise ValueError("Cannot output attentions for timm backbones at the moment")
138
+
139
+ if output_hidden_states:
140
+ # We modify the return layers to include all the stages of the backbone
141
+ self._backbone.return_layers = self._all_layers
142
+ hidden_states = self._backbone(pixel_values, **kwargs)
143
+ self._backbone.return_layers = self._return_layers
144
+ feature_maps = tuple(hidden_states[i] for i in self.out_indices)
145
+ else:
146
+ feature_maps = self._backbone(pixel_values, **kwargs)
147
+ hidden_states = None
148
+
149
+ feature_maps = tuple(feature_maps)
150
+ hidden_states = tuple(hidden_states) if hidden_states is not None else None
151
+
152
+ if not return_dict:
153
+ output = (feature_maps,)
154
+ if output_hidden_states:
155
+ output = output + (hidden_states,)
156
+ return output
157
+
158
+ return BackboneOutput(feature_maps=feature_maps, hidden_states=hidden_states, attentions=None)
159
+
160
+
161
+ __all__ = ["TimmBackbone"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_timm_wrapper import *
22
+ from .modeling_timm_wrapper import *
23
+ from .processing_timm_wrapper import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/configuration_timm_wrapper.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """Configuration for TimmWrapper models"""
17
+
18
+ from typing import Any, Dict
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import is_timm_available, logging, requires_backends
22
+
23
+
24
+ if is_timm_available():
25
+ from timm.data import ImageNetInfo, infer_imagenet_subset
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class TimmWrapperConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration for a timm backbone [`TimmWrapper`].
34
+
35
+ It is used to instantiate a timm model according to the specified arguments, defining the model.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Config loads imagenet label descriptions and stores them in `id2label` attribute, `label2id` attribute for default
41
+ imagenet models is set to `None` due to occlusions in the label descriptions.
42
+
43
+ Args:
44
+ initializer_range (`float`, *optional*, defaults to 0.02):
45
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
46
+ do_pooling (`bool`, *optional*, defaults to `True`):
47
+ Whether to do pooling for the last_hidden_state in `TimmWrapperModel` or not.
48
+
49
+ Example:
50
+ ```python
51
+ >>> from transformers import TimmWrapperModel
52
+
53
+ >>> # Initializing a timm model
54
+ >>> model = TimmWrapperModel.from_pretrained("timm/resnet18.a1_in1k")
55
+
56
+ >>> # Accessing the model configuration
57
+ >>> configuration = model.config
58
+ ```
59
+ """
60
+
61
+ model_type = "timm_wrapper"
62
+
63
+ def __init__(self, initializer_range: float = 0.02, do_pooling: bool = True, **kwargs):
64
+ self.initializer_range = initializer_range
65
+ self.do_pooling = do_pooling
66
+ super().__init__(**kwargs)
67
+
68
+ @classmethod
69
+ def from_dict(cls, config_dict: Dict[str, Any], **kwargs):
70
+ label_names = config_dict.get("label_names", None)
71
+ is_custom_model = "num_labels" in kwargs or "id2label" in kwargs
72
+
73
+ # if no labels added to config, use imagenet labeller in timm
74
+ if label_names is None and not is_custom_model:
75
+ requires_backends(cls, ["timm"])
76
+ imagenet_subset = infer_imagenet_subset(config_dict)
77
+ if imagenet_subset:
78
+ dataset_info = ImageNetInfo(imagenet_subset)
79
+ synsets = dataset_info.label_names()
80
+ label_descriptions = dataset_info.label_descriptions(as_dict=True)
81
+ label_names = [label_descriptions[synset] for synset in synsets]
82
+
83
+ if label_names is not None and not is_custom_model:
84
+ kwargs["id2label"] = dict(enumerate(label_names))
85
+
86
+ # if all label names are unique, create label2id mapping as well
87
+ if len(set(label_names)) == len(label_names):
88
+ kwargs["label2id"] = {name: i for i, name in enumerate(label_names)}
89
+ else:
90
+ kwargs["label2id"] = None
91
+
92
+ # timm config stores the `num_classes` attribute in both the root of config and in the "pretrained_cfg" dict.
93
+ # We are removing these attributes in order to have the native `transformers` num_labels attribute in config
94
+ # and to avoid duplicate attributes
95
+ num_labels_in_kwargs = kwargs.pop("num_labels", None)
96
+ num_labels_in_dict = config_dict.pop("num_classes", None)
97
+
98
+ # passed num_labels has priority over num_classes in config_dict
99
+ kwargs["num_labels"] = num_labels_in_kwargs or num_labels_in_dict
100
+
101
+ # pop num_classes from "pretrained_cfg",
102
+ # it is not necessary to have it, only root one is used in timm
103
+ if "pretrained_cfg" in config_dict and "num_classes" in config_dict["pretrained_cfg"]:
104
+ config_dict["pretrained_cfg"].pop("num_classes", None)
105
+
106
+ return super().from_dict(config_dict, **kwargs)
107
+
108
+ def to_dict(self) -> Dict[str, Any]:
109
+ output = super().to_dict()
110
+ output["num_classes"] = self.num_labels
111
+ output["label_names"] = list(self.id2label.values())
112
+ output.pop("id2label", None)
113
+ output.pop("label2id", None)
114
+ return output
115
+
116
+
117
+ __all__ = ["TimmWrapperConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ from typing import Any, Dict, Optional, Tuple, Union
18
+
19
+ import torch
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature
22
+ from ...image_transforms import to_pil_image
23
+ from ...image_utils import ImageInput, make_list_of_images
24
+ from ...utils import TensorType, logging, requires_backends
25
+ from ...utils.import_utils import is_timm_available, is_torch_available
26
+
27
+
28
+ if is_timm_available():
29
+ import timm
30
+
31
+ if is_torch_available():
32
+ import torch
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class TimmWrapperImageProcessor(BaseImageProcessor):
39
+ """
40
+ Wrapper class for timm models to be used within transformers.
41
+
42
+ Args:
43
+ pretrained_cfg (`Dict[str, Any]`):
44
+ The configuration of the pretrained model used to resolve evaluation and
45
+ training transforms.
46
+ architecture (`Optional[str]`, *optional*):
47
+ Name of the architecture of the model.
48
+ """
49
+
50
+ main_input_name = "pixel_values"
51
+
52
+ def __init__(
53
+ self,
54
+ pretrained_cfg: Dict[str, Any],
55
+ architecture: Optional[str] = None,
56
+ **kwargs,
57
+ ):
58
+ requires_backends(self, "timm")
59
+ super().__init__(architecture=architecture)
60
+
61
+ self.data_config = timm.data.resolve_data_config(pretrained_cfg, model=None, verbose=False)
62
+ self.val_transforms = timm.data.create_transform(**self.data_config, is_training=False)
63
+
64
+ # useful for training, see examples/pytorch/image-classification/run_image_classification.py
65
+ self.train_transforms = timm.data.create_transform(**self.data_config, is_training=True)
66
+
67
+ # If `ToTensor` is in the transforms, then the input should be numpy array or PIL image.
68
+ # Otherwise, the input can be a tensor. In later timm versions, `MaybeToTensor` is used
69
+ # which can handle both numpy arrays / PIL images and tensors.
70
+ self._not_supports_tensor_input = any(
71
+ transform.__class__.__name__ == "ToTensor" for transform in self.val_transforms.transforms
72
+ )
73
+
74
+ def to_dict(self) -> Dict[str, Any]:
75
+ """
76
+ Serializes this instance to a Python dictionary.
77
+ """
78
+ output = super().to_dict()
79
+ output.pop("train_transforms", None)
80
+ output.pop("val_transforms", None)
81
+ output.pop("_not_supports_tensor_input", None)
82
+ return output
83
+
84
+ @classmethod
85
+ def get_image_processor_dict(
86
+ cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
87
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
88
+ """
89
+ Get the image processor dict for the model.
90
+ """
91
+ image_processor_filename = kwargs.pop("image_processor_filename", "config.json")
92
+ return super().get_image_processor_dict(
93
+ pretrained_model_name_or_path, image_processor_filename=image_processor_filename, **kwargs
94
+ )
95
+
96
+ def preprocess(
97
+ self,
98
+ images: ImageInput,
99
+ return_tensors: Optional[Union[str, TensorType]] = "pt",
100
+ ) -> BatchFeature:
101
+ """
102
+ Preprocess an image or batch of images.
103
+
104
+ Args:
105
+ images (`ImageInput`):
106
+ Image to preprocess. Expects a single or batch of images
107
+ return_tensors (`str` or `TensorType`, *optional*):
108
+ The type of tensors to return.
109
+ """
110
+ if return_tensors != "pt":
111
+ raise ValueError(f"return_tensors for TimmWrapperImageProcessor must be 'pt', but got {return_tensors}")
112
+
113
+ if self._not_supports_tensor_input and isinstance(images, torch.Tensor):
114
+ images = images.cpu().numpy()
115
+
116
+ # If the input is a torch tensor, then no conversion is needed
117
+ # Otherwise, we need to pass in a list of PIL images
118
+ if isinstance(images, torch.Tensor):
119
+ images = self.val_transforms(images)
120
+ # Add batch dimension if a single image
121
+ images = images.unsqueeze(0) if images.ndim == 3 else images
122
+ else:
123
+ images = make_list_of_images(images)
124
+ images = [to_pil_image(image) for image in images]
125
+ images = torch.stack([self.val_transforms(image) for image in images])
126
+
127
+ return BatchFeature({"pixel_values": images}, tensor_type=return_tensors)
128
+
129
+ def save_pretrained(self, *args, **kwargs):
130
+ # disable it to make checkpoint the same as in `timm` library.
131
+ logger.warning_once(
132
+ "The `save_pretrained` method is disabled for TimmWrapperImageProcessor. "
133
+ "The image processor configuration is saved directly in `config.json` when "
134
+ "`save_pretrained` is called for saving the model."
135
+ )
136
+
137
+
138
+ __all__ = ["TimmWrapperImageProcessor"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/timm_wrapper/modeling_timm_wrapper.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from dataclasses import dataclass
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ from torch import Tensor, nn
21
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
22
+
23
+ from ...modeling_outputs import ImageClassifierOutput, ModelOutput
24
+ from ...modeling_utils import PreTrainedModel
25
+ from ...utils import (
26
+ add_start_docstrings_to_model_forward,
27
+ is_timm_available,
28
+ replace_return_docstrings,
29
+ requires_backends,
30
+ )
31
+ from .configuration_timm_wrapper import TimmWrapperConfig
32
+
33
+
34
+ if is_timm_available():
35
+ import timm
36
+
37
+
38
+ @dataclass
39
+ class TimmWrapperModelOutput(ModelOutput):
40
+ """
41
+ Output class for models TimmWrapperModel, containing the last hidden states, an optional pooled output,
42
+ and optional hidden states.
43
+
44
+ Args:
45
+ last_hidden_state (`torch.FloatTensor`):
46
+ The last hidden state of the model, output before applying the classification head.
47
+ pooler_output (`torch.FloatTensor`, *optional*):
48
+ The pooled output derived from the last hidden state, if applicable.
49
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*):
50
+ A tuple containing the intermediate hidden states of the model at the output of each layer or specified layers.
51
+ Returned if `output_hidden_states=True` is set or if `config.output_hidden_states=True`.
52
+ attentions (`tuple(torch.FloatTensor)`, *optional*):
53
+ A tuple containing the intermediate attention weights of the model at the output of each layer.
54
+ Returned if `output_attentions=True` is set or if `config.output_attentions=True`.
55
+ Note: Currently, Timm models do not support attentions output.
56
+ """
57
+
58
+ last_hidden_state: torch.FloatTensor
59
+ pooler_output: Optional[torch.FloatTensor] = None
60
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
61
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
62
+
63
+
64
+ TIMM_WRAPPER_INPUTS_DOCSTRING = r"""
65
+ Args:
66
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
67
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`TimmWrapperImageProcessor.preprocess`]
68
+ for details.
69
+ output_attentions (`bool`, *optional*):
70
+ Whether or not to return the attentions tensors of all attention layers. Not compatible with timm wrapped models.
71
+ output_hidden_states (`bool`, *optional*):
72
+ Whether or not to return the hidden states of all layers. Not compatible with timm wrapped models.
73
+ return_dict (`bool`, *optional*):
74
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
75
+ **kwargs:
76
+ Additional keyword arguments passed along to the `timm` model forward.
77
+ """
78
+
79
+
80
+ class TimmWrapperPreTrainedModel(PreTrainedModel):
81
+ main_input_name = "pixel_values"
82
+ config_class = TimmWrapperConfig
83
+ _no_split_modules = []
84
+ model_tags = ["timm"]
85
+
86
+ # used in Trainer to avoid passing `loss_kwargs` to model forward
87
+ accepts_loss_kwargs = False
88
+
89
+ def __init__(self, *args, **kwargs):
90
+ requires_backends(self, ["vision", "timm"])
91
+ super().__init__(*args, **kwargs)
92
+
93
+ @staticmethod
94
+ def _fix_state_dict_key_on_load(key) -> Tuple[str, bool]:
95
+ """
96
+ Overrides original method that renames `gamma` and `beta` to `weight` and `bias`.
97
+ We don't want this behavior for timm wrapped models. Instead, this method adds a
98
+ "timm_model." prefix to enable loading official timm Hub checkpoints.
99
+ """
100
+ if "timm_model." not in key:
101
+ return f"timm_model.{key}", True
102
+ return key, False
103
+
104
+ def _fix_state_dict_key_on_save(self, key):
105
+ """
106
+ Overrides original method to remove "timm_model." prefix from state_dict keys.
107
+ Makes the saved checkpoint compatible with the `timm` library.
108
+ """
109
+ return key.replace("timm_model.", ""), True
110
+
111
+ def load_state_dict(self, state_dict, *args, **kwargs):
112
+ """
113
+ Override original method to fix state_dict keys on load for cases when weights are loaded
114
+ without using the `from_pretrained` method (e.g., in Trainer to resume from checkpoint).
115
+ """
116
+ state_dict = self._fix_state_dict_keys_on_load(state_dict)
117
+ return super().load_state_dict(state_dict, *args, **kwargs)
118
+
119
+ def _init_weights(self, module):
120
+ """
121
+ Initialize weights function to properly initialize Linear layer weights.
122
+ Since model architectures may vary, we assume only the classifier requires
123
+ initialization, while all other weights should be loaded from the checkpoint.
124
+ """
125
+ if isinstance(module, (nn.Linear)):
126
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
127
+ if module.bias is not None:
128
+ module.bias.data.zero_()
129
+
130
+
131
+ class TimmWrapperModel(TimmWrapperPreTrainedModel):
132
+ """
133
+ Wrapper class for timm models to be used in transformers.
134
+ """
135
+
136
+ def __init__(self, config: TimmWrapperConfig):
137
+ super().__init__(config)
138
+ # using num_classes=0 to avoid creating classification head
139
+ self.timm_model = timm.create_model(config.architecture, pretrained=False, num_classes=0)
140
+ self.post_init()
141
+
142
+ @add_start_docstrings_to_model_forward(TIMM_WRAPPER_INPUTS_DOCSTRING)
143
+ @replace_return_docstrings(output_type=TimmWrapperModelOutput, config_class=TimmWrapperConfig)
144
+ def forward(
145
+ self,
146
+ pixel_values: torch.FloatTensor,
147
+ output_attentions: Optional[bool] = None,
148
+ output_hidden_states: Optional[Union[bool, List[int]]] = None,
149
+ return_dict: Optional[bool] = None,
150
+ do_pooling: Optional[bool] = None,
151
+ **kwargs,
152
+ ) -> Union[TimmWrapperModelOutput, Tuple[Tensor, ...]]:
153
+ r"""
154
+ do_pooling (`bool`, *optional*):
155
+ Whether to do pooling for the last_hidden_state in `TimmWrapperModel` or not. If `None` is passed, the
156
+ `do_pooling` value from the config is used.
157
+
158
+ Returns:
159
+
160
+ Examples:
161
+ ```python
162
+ >>> import torch
163
+ >>> from PIL import Image
164
+ >>> from urllib.request import urlopen
165
+ >>> from transformers import AutoModel, AutoImageProcessor
166
+
167
+ >>> # Load image
168
+ >>> image = Image.open(urlopen(
169
+ ... 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
170
+ ... ))
171
+
172
+ >>> # Load model and image processor
173
+ >>> checkpoint = "timm/resnet50.a1_in1k"
174
+ >>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
175
+ >>> model = AutoModel.from_pretrained(checkpoint).eval()
176
+
177
+ >>> # Preprocess image
178
+ >>> inputs = image_processor(image)
179
+
180
+ >>> # Forward pass
181
+ >>> with torch.no_grad():
182
+ ... outputs = model(**inputs)
183
+
184
+ >>> # Get pooled output
185
+ >>> pooled_output = outputs.pooler_output
186
+
187
+ >>> # Get last hidden state
188
+ >>> last_hidden_state = outputs.last_hidden_state
189
+ ```
190
+ """
191
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
192
+ output_hidden_states = (
193
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
194
+ )
195
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
196
+ do_pooling = do_pooling if do_pooling is not None else self.config.do_pooling
197
+
198
+ if output_attentions:
199
+ raise ValueError("Cannot set `output_attentions` for timm models.")
200
+
201
+ if output_hidden_states and not hasattr(self.timm_model, "forward_intermediates"):
202
+ raise ValueError(
203
+ "The 'output_hidden_states' option cannot be set for this timm model. "
204
+ "To enable this feature, the 'forward_intermediates' method must be implemented "
205
+ "in the timm model (available in timm versions > 1.*). Please consider using a "
206
+ "different architecture or updating the timm package to a compatible version."
207
+ )
208
+
209
+ pixel_values = pixel_values.to(self.device, self.dtype)
210
+
211
+ if output_hidden_states:
212
+ # to enable hidden states selection
213
+ if isinstance(output_hidden_states, (list, tuple)):
214
+ kwargs["indices"] = output_hidden_states
215
+ last_hidden_state, hidden_states = self.timm_model.forward_intermediates(pixel_values, **kwargs)
216
+ else:
217
+ last_hidden_state = self.timm_model.forward_features(pixel_values, **kwargs)
218
+ hidden_states = None
219
+
220
+ if do_pooling:
221
+ # classification head is not created, applying pooling only
222
+ pooler_output = self.timm_model.forward_head(last_hidden_state)
223
+ else:
224
+ pooler_output = None
225
+
226
+ if not return_dict:
227
+ outputs = (last_hidden_state, pooler_output, hidden_states)
228
+ outputs = tuple(output for output in outputs if output is not None)
229
+ return outputs
230
+
231
+ return TimmWrapperModelOutput(
232
+ last_hidden_state=last_hidden_state,
233
+ pooler_output=pooler_output,
234
+ hidden_states=hidden_states,
235
+ )
236
+
237
+
238
+ class TimmWrapperForImageClassification(TimmWrapperPreTrainedModel):
239
+ """
240
+ Wrapper class for timm models to be used in transformers for image classification.
241
+ """
242
+
243
+ def __init__(self, config: TimmWrapperConfig):
244
+ super().__init__(config)
245
+
246
+ if config.num_labels == 0:
247
+ raise ValueError(
248
+ "You are trying to load weights into `TimmWrapperForImageClassification` from a checkpoint with no classifier head. "
249
+ "Please specify the number of classes, e.g. `model = TimmWrapperForImageClassification.from_pretrained(..., num_labels=10)`, "
250
+ "or use `TimmWrapperModel` for feature extraction."
251
+ )
252
+
253
+ self.timm_model = timm.create_model(config.architecture, pretrained=False, num_classes=config.num_labels)
254
+ self.num_labels = config.num_labels
255
+ self.post_init()
256
+
257
+ @add_start_docstrings_to_model_forward(TIMM_WRAPPER_INPUTS_DOCSTRING)
258
+ @replace_return_docstrings(output_type=ImageClassifierOutput, config_class=TimmWrapperConfig)
259
+ def forward(
260
+ self,
261
+ pixel_values: torch.FloatTensor,
262
+ labels: Optional[torch.LongTensor] = None,
263
+ output_attentions: Optional[bool] = None,
264
+ output_hidden_states: Optional[Union[bool, List[int]]] = None,
265
+ return_dict: Optional[bool] = None,
266
+ **kwargs,
267
+ ) -> Union[ImageClassifierOutput, Tuple[Tensor, ...]]:
268
+ r"""
269
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
270
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
271
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
272
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
273
+
274
+ Returns:
275
+
276
+ Examples:
277
+ ```python
278
+ >>> import torch
279
+ >>> from PIL import Image
280
+ >>> from urllib.request import urlopen
281
+ >>> from transformers import AutoModelForImageClassification, AutoImageProcessor
282
+
283
+ >>> # Load image
284
+ >>> image = Image.open(urlopen(
285
+ ... 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
286
+ ... ))
287
+
288
+ >>> # Load model and image processor
289
+ >>> checkpoint = "timm/resnet50.a1_in1k"
290
+ >>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
291
+ >>> model = AutoModelForImageClassification.from_pretrained(checkpoint).eval()
292
+
293
+ >>> # Preprocess image
294
+ >>> inputs = image_processor(image)
295
+
296
+ >>> # Forward pass
297
+ >>> with torch.no_grad():
298
+ ... logits = model(**inputs).logits
299
+
300
+ >>> # Get top 5 predictions
301
+ >>> top5_probabilities, top5_class_indices = torch.topk(logits.softmax(dim=1) * 100, k=5)
302
+ ```
303
+ """
304
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
305
+ output_hidden_states = (
306
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
307
+ )
308
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
309
+
310
+ if output_attentions:
311
+ raise ValueError("Cannot set `output_attentions` for timm models.")
312
+
313
+ if output_hidden_states and not hasattr(self.timm_model, "forward_intermediates"):
314
+ raise ValueError(
315
+ "The 'output_hidden_states' option cannot be set for this timm model. "
316
+ "To enable this feature, the 'forward_intermediates' method must be implemented "
317
+ "in the timm model (available in timm versions > 1.*). Please consider using a "
318
+ "different architecture or updating the timm package to a compatible version."
319
+ )
320
+
321
+ pixel_values = pixel_values.to(self.device, self.dtype)
322
+
323
+ if output_hidden_states:
324
+ # to enable hidden states selection
325
+ if isinstance(output_hidden_states, (list, tuple)):
326
+ kwargs["indices"] = output_hidden_states
327
+ last_hidden_state, hidden_states = self.timm_model.forward_intermediates(pixel_values, **kwargs)
328
+ logits = self.timm_model.forward_head(last_hidden_state)
329
+ else:
330
+ logits = self.timm_model(pixel_values, **kwargs)
331
+ hidden_states = None
332
+
333
+ loss = None
334
+ if labels is not None:
335
+ if self.config.problem_type is None:
336
+ if self.num_labels == 1:
337
+ self.config.problem_type = "regression"
338
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
339
+ self.config.problem_type = "single_label_classification"
340
+ else:
341
+ self.config.problem_type = "multi_label_classification"
342
+ if self.config.problem_type == "regression":
343
+ loss_fct = MSELoss()
344
+ if self.num_labels == 1:
345
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
346
+ else:
347
+ loss = loss_fct(logits, labels)
348
+ elif self.config.problem_type == "single_label_classification":
349
+ loss_fct = CrossEntropyLoss()
350
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
351
+ elif self.config.problem_type == "multi_label_classification":
352
+ loss_fct = BCEWithLogitsLoss()
353
+ loss = loss_fct(logits, labels)
354
+
355
+ if not return_dict:
356
+ outputs = (loss, logits, hidden_states)
357
+ outputs = tuple(output for output in outputs if output is not None)
358
+ return outputs
359
+
360
+ return ImageClassifierOutput(
361
+ loss=loss,
362
+ logits=logits,
363
+ hidden_states=hidden_states,
364
+ )
365
+
366
+
367
+ __all__ = ["TimmWrapperPreTrainedModel", "TimmWrapperModel", "TimmWrapperForImageClassification"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_trocr import *
22
+ from .modeling_trocr import *
23
+ from .processing_trocr import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/configuration_trocr.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """TrOCR model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class TrOCRConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`TrOCRForCausalLM`]. It is used to instantiate an
27
+ TrOCR model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the TrOCR
29
+ [microsoft/trocr-base-handwritten](https://huggingface.co/microsoft/trocr-base-handwritten) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 50265):
37
+ Vocabulary size of the TrOCR model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`TrOCRForCausalLM`].
39
+ d_model (`int`, *optional*, defaults to 1024):
40
+ Dimensionality of the layers and the pooler layer.
41
+ decoder_layers (`int`, *optional*, defaults to 12):
42
+ Number of decoder layers.
43
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
44
+ Number of attention heads for each attention layer in the Transformer decoder.
45
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
46
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
47
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the pooler. If string, `"gelu"`, `"relu"`,
49
+ `"silu"` and `"gelu_new"` are supported.
50
+ max_position_embeddings (`int`, *optional*, defaults to 512):
51
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
52
+ just in case (e.g., 512 or 1024 or 2048).
53
+ dropout (`float`, *optional*, defaults to 0.1):
54
+ The dropout probability for all fully connected layers in the embeddings, and pooler.
55
+ attention_dropout (`float`, *optional*, defaults to 0.0):
56
+ The dropout ratio for the attention probabilities.
57
+ activation_dropout (`float`, *optional*, defaults to 0.0):
58
+ The dropout ratio for activations inside the fully connected layer.
59
+ init_std (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
62
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
63
+ for more details.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models).
66
+ scale_embedding (`bool`, *optional*, defaults to `False`):
67
+ Whether or not to scale the word embeddings by sqrt(d_model).
68
+ use_learned_position_embeddings (`bool`, *optional*, defaults to `True`):
69
+ Whether or not to use learned position embeddings. If not, sinusoidal position embeddings will be used.
70
+ layernorm_embedding (`bool`, *optional*, defaults to `True`):
71
+ Whether or not to use a layernorm after the word + position embeddings.
72
+
73
+ Example:
74
+
75
+ ```python
76
+ >>> from transformers import TrOCRConfig, TrOCRForCausalLM
77
+
78
+ >>> # Initializing a TrOCR-base style configuration
79
+ >>> configuration = TrOCRConfig()
80
+
81
+ >>> # Initializing a model (with random weights) from the TrOCR-base style configuration
82
+ >>> model = TrOCRForCausalLM(configuration)
83
+
84
+ >>> # Accessing the model configuration
85
+ >>> configuration = model.config
86
+ ```"""
87
+
88
+ model_type = "trocr"
89
+ keys_to_ignore_at_inference = ["past_key_values"]
90
+ attribute_map = {
91
+ "num_attention_heads": "decoder_attention_heads",
92
+ "hidden_size": "d_model",
93
+ "num_hidden_layers": "decoder_layers",
94
+ }
95
+
96
+ def __init__(
97
+ self,
98
+ vocab_size=50265,
99
+ d_model=1024,
100
+ decoder_layers=12,
101
+ decoder_attention_heads=16,
102
+ decoder_ffn_dim=4096,
103
+ activation_function="gelu",
104
+ max_position_embeddings=512,
105
+ dropout=0.1,
106
+ attention_dropout=0.0,
107
+ activation_dropout=0.0,
108
+ decoder_start_token_id=2,
109
+ init_std=0.02,
110
+ decoder_layerdrop=0.0,
111
+ use_cache=True,
112
+ scale_embedding=False,
113
+ use_learned_position_embeddings=True,
114
+ layernorm_embedding=True,
115
+ pad_token_id=1,
116
+ bos_token_id=0,
117
+ eos_token_id=2,
118
+ **kwargs,
119
+ ):
120
+ self.vocab_size = vocab_size
121
+ self.d_model = d_model
122
+ self.decoder_layers = decoder_layers
123
+ self.decoder_attention_heads = decoder_attention_heads
124
+ self.decoder_ffn_dim = decoder_ffn_dim
125
+ self.activation_function = activation_function
126
+ self.max_position_embeddings = max_position_embeddings
127
+ self.dropout = dropout
128
+ self.attention_dropout = attention_dropout
129
+ self.activation_dropout = activation_dropout
130
+ self.init_std = init_std
131
+ self.decoder_layerdrop = decoder_layerdrop
132
+ self.use_cache = use_cache
133
+ self.scale_embedding = scale_embedding
134
+ self.use_learned_position_embeddings = use_learned_position_embeddings
135
+ self.layernorm_embedding = layernorm_embedding
136
+
137
+ super().__init__(
138
+ pad_token_id=pad_token_id,
139
+ bos_token_id=bos_token_id,
140
+ eos_token_id=eos_token_id,
141
+ decoder_start_token_id=decoder_start_token_id,
142
+ **kwargs,
143
+ )
144
+
145
+
146
+ __all__ = ["TrOCRConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert TrOCR checkpoints from the unilm repository."""
16
+
17
+ import argparse
18
+ from pathlib import Path
19
+
20
+ import requests
21
+ import torch
22
+ from PIL import Image
23
+
24
+ from transformers import (
25
+ RobertaTokenizer,
26
+ TrOCRConfig,
27
+ TrOCRForCausalLM,
28
+ TrOCRProcessor,
29
+ VisionEncoderDecoderModel,
30
+ ViTConfig,
31
+ ViTImageProcessor,
32
+ ViTModel,
33
+ )
34
+ from transformers.utils import logging
35
+
36
+
37
+ logging.set_verbosity_info()
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ # here we list all keys to be renamed (original name on the left, our name on the right)
42
+ def create_rename_keys(encoder_config, decoder_config):
43
+ rename_keys = []
44
+ for i in range(encoder_config.num_hidden_layers):
45
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
46
+ rename_keys.append(
47
+ (f"encoder.deit.blocks.{i}.norm1.weight", f"encoder.encoder.layer.{i}.layernorm_before.weight")
48
+ )
49
+ rename_keys.append((f"encoder.deit.blocks.{i}.norm1.bias", f"encoder.encoder.layer.{i}.layernorm_before.bias"))
50
+ rename_keys.append(
51
+ (f"encoder.deit.blocks.{i}.attn.proj.weight", f"encoder.encoder.layer.{i}.attention.output.dense.weight")
52
+ )
53
+ rename_keys.append(
54
+ (f"encoder.deit.blocks.{i}.attn.proj.bias", f"encoder.encoder.layer.{i}.attention.output.dense.bias")
55
+ )
56
+ rename_keys.append(
57
+ (f"encoder.deit.blocks.{i}.norm2.weight", f"encoder.encoder.layer.{i}.layernorm_after.weight")
58
+ )
59
+ rename_keys.append((f"encoder.deit.blocks.{i}.norm2.bias", f"encoder.encoder.layer.{i}.layernorm_after.bias"))
60
+ rename_keys.append(
61
+ (f"encoder.deit.blocks.{i}.mlp.fc1.weight", f"encoder.encoder.layer.{i}.intermediate.dense.weight")
62
+ )
63
+ rename_keys.append(
64
+ (f"encoder.deit.blocks.{i}.mlp.fc1.bias", f"encoder.encoder.layer.{i}.intermediate.dense.bias")
65
+ )
66
+ rename_keys.append(
67
+ (f"encoder.deit.blocks.{i}.mlp.fc2.weight", f"encoder.encoder.layer.{i}.output.dense.weight")
68
+ )
69
+ rename_keys.append((f"encoder.deit.blocks.{i}.mlp.fc2.bias", f"encoder.encoder.layer.{i}.output.dense.bias"))
70
+
71
+ # cls token, position embeddings and patch embeddings of encoder
72
+ rename_keys.extend(
73
+ [
74
+ ("encoder.deit.cls_token", "encoder.embeddings.cls_token"),
75
+ ("encoder.deit.pos_embed", "encoder.embeddings.position_embeddings"),
76
+ ("encoder.deit.patch_embed.proj.weight", "encoder.embeddings.patch_embeddings.projection.weight"),
77
+ ("encoder.deit.patch_embed.proj.bias", "encoder.embeddings.patch_embeddings.projection.bias"),
78
+ ("encoder.deit.norm.weight", "encoder.layernorm.weight"),
79
+ ("encoder.deit.norm.bias", "encoder.layernorm.bias"),
80
+ ]
81
+ )
82
+
83
+ return rename_keys
84
+
85
+
86
+ # we split up the matrix of each encoder layer into queries, keys and values
87
+ def read_in_q_k_v(state_dict, encoder_config):
88
+ for i in range(encoder_config.num_hidden_layers):
89
+ # queries, keys and values (only weights, no biases)
90
+ in_proj_weight = state_dict.pop(f"encoder.deit.blocks.{i}.attn.qkv.weight")
91
+
92
+ state_dict[f"encoder.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
93
+ : encoder_config.hidden_size, :
94
+ ]
95
+ state_dict[f"encoder.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
96
+ encoder_config.hidden_size : encoder_config.hidden_size * 2, :
97
+ ]
98
+ state_dict[f"encoder.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
99
+ -encoder_config.hidden_size :, :
100
+ ]
101
+
102
+
103
+ def rename_key(dct, old, new):
104
+ val = dct.pop(old)
105
+ dct[new] = val
106
+
107
+
108
+ # We will verify our results on an image of the IAM Handwriting Database
109
+ def prepare_img(checkpoint_url):
110
+ if "handwritten" in checkpoint_url:
111
+ url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg" # industry
112
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have
113
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let
114
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" #
115
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg"
116
+ elif "printed" in checkpoint_url or "stage1" in checkpoint_url:
117
+ url = "https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg"
118
+ im = Image.open(requests.get(url, stream=True).raw).convert("RGB")
119
+ return im
120
+
121
+
122
+ @torch.no_grad()
123
+ def convert_tr_ocr_checkpoint(checkpoint_url, pytorch_dump_folder_path):
124
+ """
125
+ Copy/paste/tweak model's weights to our VisionEncoderDecoderModel structure.
126
+ """
127
+ # define encoder and decoder configs based on checkpoint_url
128
+ encoder_config = ViTConfig(image_size=384, qkv_bias=False)
129
+ decoder_config = TrOCRConfig()
130
+
131
+ # size of the architecture
132
+ if "base" in checkpoint_url:
133
+ decoder_config.encoder_hidden_size = 768
134
+ elif "large" in checkpoint_url:
135
+ # use ViT-large encoder
136
+ encoder_config.hidden_size = 1024
137
+ encoder_config.intermediate_size = 4096
138
+ encoder_config.num_hidden_layers = 24
139
+ encoder_config.num_attention_heads = 16
140
+ decoder_config.encoder_hidden_size = 1024
141
+ else:
142
+ raise ValueError("Should either find 'base' or 'large' in checkpoint URL")
143
+
144
+ # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards
145
+ if "large-printed" in checkpoint_url or "stage1" in checkpoint_url:
146
+ decoder_config.tie_word_embeddings = False
147
+ decoder_config.activation_function = "relu"
148
+ decoder_config.max_position_embeddings = 1024
149
+ decoder_config.scale_embedding = True
150
+ decoder_config.use_learned_position_embeddings = False
151
+ decoder_config.layernorm_embedding = False
152
+
153
+ # load HuggingFace model
154
+ encoder = ViTModel(encoder_config, add_pooling_layer=False)
155
+ decoder = TrOCRForCausalLM(decoder_config)
156
+ model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)
157
+ model.eval()
158
+
159
+ # load state_dict of original model, rename some keys
160
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu", check_hash=True)["model"]
161
+
162
+ rename_keys = create_rename_keys(encoder_config, decoder_config)
163
+ for src, dest in rename_keys:
164
+ rename_key(state_dict, src, dest)
165
+ read_in_q_k_v(state_dict, encoder_config)
166
+
167
+ # remove parameters we don't need
168
+ del state_dict["encoder.deit.head.weight"]
169
+ del state_dict["encoder.deit.head.bias"]
170
+ del state_dict["decoder.version"]
171
+
172
+ # add prefix to decoder keys
173
+ for key, val in state_dict.copy().items():
174
+ val = state_dict.pop(key)
175
+ if key.startswith("decoder") and "output_projection" not in key:
176
+ state_dict["decoder.model." + key] = val
177
+ else:
178
+ state_dict[key] = val
179
+
180
+ # load state dict
181
+ model.load_state_dict(state_dict)
182
+
183
+ # Check outputs on an image
184
+ image_processor = ViTImageProcessor(size=encoder_config.image_size)
185
+ tokenizer = RobertaTokenizer.from_pretrained("FacebookAI/roberta-large")
186
+ processor = TrOCRProcessor(image_processor, tokenizer)
187
+
188
+ pixel_values = processor(images=prepare_img(checkpoint_url), return_tensors="pt").pixel_values
189
+
190
+ # verify logits
191
+ decoder_input_ids = torch.tensor([[model.config.decoder.decoder_start_token_id]])
192
+ outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids)
193
+ logits = outputs.logits
194
+
195
+ expected_shape = torch.Size([1, 1, 50265])
196
+ if "trocr-base-handwritten" in checkpoint_url:
197
+ expected_slice = torch.tensor(
198
+ [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311]
199
+ )
200
+ elif "trocr-large-handwritten" in checkpoint_url:
201
+ expected_slice = torch.tensor(
202
+ [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170]
203
+ )
204
+ elif "trocr-base-printed" in checkpoint_url:
205
+ expected_slice = torch.tensor(
206
+ [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210]
207
+ )
208
+ elif "trocr-large-printed" in checkpoint_url:
209
+ expected_slice = torch.tensor(
210
+ [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535]
211
+ )
212
+
213
+ if "stage1" not in checkpoint_url:
214
+ assert logits.shape == expected_shape, "Shape of logits not as expected"
215
+ assert torch.allclose(logits[0, 0, :10], expected_slice, atol=1e-3), "First elements of logits not as expected"
216
+
217
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
218
+ print(f"Saving model to {pytorch_dump_folder_path}")
219
+ model.save_pretrained(pytorch_dump_folder_path)
220
+ print(f"Saving processor to {pytorch_dump_folder_path}")
221
+ processor.save_pretrained(pytorch_dump_folder_path)
222
+
223
+
224
+ if __name__ == "__main__":
225
+ parser = argparse.ArgumentParser()
226
+
227
+ parser.add_argument(
228
+ "--checkpoint_url",
229
+ default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt",
230
+ type=str,
231
+ help="URL to the original PyTorch checkpoint (.pth file).",
232
+ )
233
+ parser.add_argument(
234
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
235
+ )
236
+ args = parser.parse_args()
237
+ convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/modeling_trocr.py ADDED
@@ -0,0 +1,958 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch TrOCR decoder model (based on RoBERTa)."""
16
+
17
+ import copy
18
+ import math
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import CrossEntropyLoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
28
+ from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import add_start_docstrings, logging, replace_return_docstrings
31
+ from .configuration_trocr import TrOCRConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ _CONFIG_FOR_DOC = "TrOCRConfig"
37
+ _CHECKPOINT_FOR_DOC = "microsoft/trocr-base-handwritten"
38
+
39
+
40
+ # Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->TrOCR
41
+ class TrOCRLearnedPositionalEmbedding(nn.Embedding):
42
+ """
43
+ This module learns positional embeddings up to a fixed maximum size.
44
+ """
45
+
46
+ def __init__(self, num_embeddings: int, embedding_dim: int):
47
+ # TrOCR is set up so that if padding_idx is specified then offset the embedding ids by 2
48
+ # and adjust num_embeddings appropriately. Other models don't have this hack
49
+ self.offset = 2
50
+ super().__init__(num_embeddings + self.offset, embedding_dim)
51
+
52
+ def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
53
+ """`input_ids' shape is expected to be [bsz x seqlen]."""
54
+
55
+ bsz, seq_len = input_ids.shape[:2]
56
+ positions = torch.arange(
57
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
58
+ ).expand(bsz, -1)
59
+
60
+ return super().forward(positions + self.offset)
61
+
62
+
63
+ # Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->TrOCR
64
+ class TrOCRScaledWordEmbedding(nn.Embedding):
65
+ """
66
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
67
+ """
68
+
69
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
70
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
71
+ self.embed_scale = embed_scale
72
+
73
+ def forward(self, input_ids: torch.Tensor):
74
+ return super().forward(input_ids) * self.embed_scale
75
+
76
+
77
+ class TrOCRSinusoidalPositionalEmbedding(nn.Module):
78
+ """This module produces sinusoidal positional embeddings of any length."""
79
+
80
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
81
+ super().__init__()
82
+ self.offset = 2
83
+ self.embedding_dim = embedding_dim
84
+ self.padding_idx = padding_idx
85
+ self.weights = self.get_embedding(num_positions, embedding_dim, padding_idx)
86
+ self.register_buffer("_float_tensor", torch.FloatTensor(1))
87
+
88
+ @staticmethod
89
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
90
+ """
91
+ Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
92
+ description in Section 3.5 of "Attention Is All You Need".
93
+ """
94
+ half_dim = embedding_dim // 2
95
+ emb = math.log(10000) / (half_dim - 1)
96
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
97
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
98
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
99
+ if embedding_dim % 2 == 1:
100
+ # zero pad
101
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
102
+ if padding_idx is not None:
103
+ emb[padding_idx, :] = 0
104
+
105
+ return emb.to(torch.get_default_dtype())
106
+
107
+ @torch.no_grad()
108
+ def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
109
+ bsz, seq_len = input_ids.size()
110
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
111
+ position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
112
+ input_ids.device
113
+ )
114
+
115
+ # expand embeddings if needed
116
+ max_pos = self.padding_idx + 1 + seq_len
117
+ if self.weights is None or max_pos > self.weights.size(0):
118
+ # recompute/expand embeddings if needed
119
+ self.weights = self.get_embedding(max_pos, self.embedding_dim, self.padding_idx)
120
+ self.weights = self.weights.to(self._float_tensor)
121
+
122
+ x = self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach()
123
+
124
+ return x
125
+
126
+ def create_position_ids_from_input_ids(
127
+ self, input_ids: torch.Tensor, padding_idx: int, past_key_values_length: Optional[int] = 0
128
+ ):
129
+ """
130
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
131
+ symbols are ignored. This is modified from fairseq's `utils.make_positions`.
132
+ """
133
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
134
+ mask = input_ids.ne(padding_idx).int()
135
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
136
+ return incremental_indices.long() + padding_idx
137
+
138
+
139
+ class TrOCRAttention(nn.Module):
140
+ """Multi-headed attention from 'Attention Is All You Need' paper."""
141
+
142
+ def __init__(
143
+ self,
144
+ config,
145
+ embed_dim: int,
146
+ num_heads: int,
147
+ kdim: int = None,
148
+ vdim: int = None,
149
+ dropout: float = 0.0,
150
+ is_decoder: bool = False,
151
+ bias: bool = True,
152
+ is_cross_attention: bool = False,
153
+ ):
154
+ super().__init__()
155
+ self.embed_dim = embed_dim
156
+ self.kdim = kdim if kdim is not None else embed_dim
157
+ self.vdim = vdim if vdim is not None else embed_dim
158
+ self.num_heads = num_heads
159
+ self.dropout = dropout
160
+ self.head_dim = embed_dim // num_heads
161
+ if not (self.head_dim * num_heads == self.embed_dim):
162
+ raise ValueError(
163
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
164
+ f" {num_heads})."
165
+ )
166
+ self.scaling = self.head_dim**-0.5
167
+ self.is_decoder = is_decoder
168
+
169
+ self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias)
170
+ self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias)
171
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
172
+
173
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
174
+
175
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
176
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
177
+
178
+ def forward(
179
+ self,
180
+ hidden_states: torch.Tensor,
181
+ key_value_states: Optional[torch.Tensor] = None,
182
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
183
+ attention_mask: Optional[torch.Tensor] = None,
184
+ layer_head_mask: Optional[torch.Tensor] = None,
185
+ output_attentions: bool = False,
186
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
187
+ """Input shape: Batch x Time x Channel"""
188
+
189
+ # if key_value_states are provided this layer is used as a cross-attention layer
190
+ # for the decoder
191
+ is_cross_attention = key_value_states is not None
192
+ bsz, tgt_len, embed_dim = hidden_states.size()
193
+
194
+ # get query proj
195
+ query_states = self.q_proj(hidden_states) * self.scaling
196
+ # get key, value proj
197
+ if is_cross_attention and past_key_value is not None:
198
+ # reuse k,v, cross_attentions
199
+ key_states = past_key_value[0]
200
+ value_states = past_key_value[1]
201
+ elif is_cross_attention:
202
+ # cross_attentions
203
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
204
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
205
+ elif past_key_value is not None:
206
+ # reuse k, v, self_attention
207
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
208
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
209
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
210
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
211
+ else:
212
+ # self_attention
213
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
214
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
215
+
216
+ if self.is_decoder:
217
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
218
+ # Further calls to cross_attention layer can then reuse all cross-attention
219
+ # key/value_states (first "if" case)
220
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
221
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
222
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
223
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
224
+ past_key_value = (key_states, value_states)
225
+
226
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
227
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
228
+ key_states = key_states.view(*proj_shape)
229
+ value_states = value_states.view(*proj_shape)
230
+
231
+ src_len = key_states.size(1)
232
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
233
+
234
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
235
+ raise ValueError(
236
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
237
+ f" {attn_weights.size()}"
238
+ )
239
+
240
+ if attention_mask is not None:
241
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
242
+ raise ValueError(
243
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
244
+ )
245
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
246
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
247
+
248
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
249
+
250
+ if layer_head_mask is not None:
251
+ if layer_head_mask.size() != (self.num_heads,):
252
+ raise ValueError(
253
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
254
+ f" {layer_head_mask.size()}"
255
+ )
256
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
257
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
258
+
259
+ if output_attentions:
260
+ # this operation is a bit awkward, but it's required to
261
+ # make sure that attn_weights keeps its gradient.
262
+ # In order to do so, attn_weights have to be reshaped
263
+ # twice and have to be reused in the following
264
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
265
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
266
+ else:
267
+ attn_weights_reshaped = None
268
+
269
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
270
+
271
+ attn_output = torch.bmm(attn_probs, value_states)
272
+
273
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
274
+ raise ValueError(
275
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
276
+ f" {attn_output.size()}"
277
+ )
278
+
279
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
280
+ attn_output = attn_output.transpose(1, 2)
281
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
282
+
283
+ attn_output = self.out_proj(attn_output)
284
+
285
+ return attn_output, attn_weights_reshaped, past_key_value
286
+
287
+
288
+ class TrOCRDecoderLayer(nn.Module):
289
+ def __init__(self, config: TrOCRConfig):
290
+ super().__init__()
291
+ self.embed_dim = config.hidden_size
292
+
293
+ self.self_attn = TrOCRAttention(
294
+ config,
295
+ embed_dim=self.embed_dim,
296
+ num_heads=config.decoder_attention_heads,
297
+ dropout=config.attention_dropout,
298
+ is_decoder=True,
299
+ )
300
+ self.dropout = config.dropout
301
+ self.activation_fn = ACT2FN[config.activation_function]
302
+ self.activation_dropout = config.activation_dropout
303
+
304
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
305
+
306
+ if config.is_decoder:
307
+ self.encoder_attn = TrOCRAttention(
308
+ config,
309
+ embed_dim=self.embed_dim,
310
+ num_heads=config.decoder_attention_heads,
311
+ kdim=config.cross_attention_hidden_size,
312
+ vdim=config.cross_attention_hidden_size,
313
+ dropout=config.attention_dropout,
314
+ is_decoder=True,
315
+ is_cross_attention=True,
316
+ )
317
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
318
+
319
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
320
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
321
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
322
+
323
+ def forward(
324
+ self,
325
+ hidden_states: torch.Tensor,
326
+ attention_mask: Optional[torch.Tensor] = None,
327
+ encoder_hidden_states: Optional[torch.Tensor] = None,
328
+ encoder_attention_mask: Optional[torch.Tensor] = None,
329
+ layer_head_mask: Optional[torch.Tensor] = None,
330
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
331
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
332
+ output_attentions: Optional[bool] = False,
333
+ use_cache: Optional[bool] = True,
334
+ ):
335
+ """
336
+ Args:
337
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
338
+ attention_mask (`torch.FloatTensor`): attention mask of size
339
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
340
+ encoder_hidden_states (`torch.FloatTensor`):
341
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
342
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
343
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
344
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
345
+ `(encoder_attention_heads,)`.
346
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
347
+ size *(decoder_attention_heads,)*.
348
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
349
+ output_attentions (`bool`, *optional*):
350
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
351
+ returned tensors for more detail.
352
+ """
353
+ residual = hidden_states
354
+
355
+ # Self Attention
356
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
357
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
358
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
359
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
360
+ hidden_states=hidden_states,
361
+ past_key_value=self_attn_past_key_value,
362
+ attention_mask=attention_mask,
363
+ layer_head_mask=layer_head_mask,
364
+ output_attentions=output_attentions,
365
+ )
366
+
367
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
368
+ hidden_states = residual + hidden_states
369
+ hidden_states = self.self_attn_layer_norm(hidden_states)
370
+
371
+ # Cross-Attention Block
372
+ cross_attn_present_key_value = None
373
+ cross_attn_weights = None
374
+
375
+ if encoder_hidden_states is not None:
376
+ residual = hidden_states
377
+
378
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
379
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
380
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
381
+ hidden_states=hidden_states,
382
+ key_value_states=encoder_hidden_states,
383
+ attention_mask=encoder_attention_mask,
384
+ layer_head_mask=cross_attn_layer_head_mask,
385
+ past_key_value=cross_attn_past_key_value,
386
+ output_attentions=output_attentions,
387
+ )
388
+
389
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
390
+ hidden_states = residual + hidden_states
391
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
392
+
393
+ # add cross-attn to positions 3,4 of present_key_value tuple
394
+ present_key_value = present_key_value + cross_attn_present_key_value
395
+
396
+ # Fully Connected
397
+ residual = hidden_states
398
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
399
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
400
+ hidden_states = self.fc2(hidden_states)
401
+
402
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
403
+ hidden_states = residual + hidden_states
404
+ hidden_states = self.final_layer_norm(hidden_states)
405
+
406
+ outputs = (hidden_states,)
407
+
408
+ if output_attentions:
409
+ outputs += (self_attn_weights, cross_attn_weights)
410
+
411
+ if use_cache:
412
+ outputs += (present_key_value,)
413
+
414
+ return outputs
415
+
416
+
417
+ class TrOCRPreTrainedModel(PreTrainedModel):
418
+ config_class = TrOCRConfig
419
+ base_model_prefix = "model"
420
+ supports_gradient_checkpointing = True
421
+ _no_split_modules = ["TrOCRDecoderLayer"]
422
+
423
+ def _init_weights(self, module):
424
+ std = self.config.init_std
425
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
426
+ module.weight.data.normal_(mean=0.0, std=std)
427
+ if module.bias is not None:
428
+ module.bias.data.zero_()
429
+ elif isinstance(module, nn.Embedding):
430
+ module.weight.data.normal_(mean=0.0, std=std)
431
+ if module.padding_idx is not None:
432
+ module.weight.data[module.padding_idx].zero_()
433
+
434
+
435
+ TROCR_START_DOCSTRING = r"""
436
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
437
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
438
+ etc.)
439
+
440
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
441
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
442
+ and behavior.
443
+
444
+ Parameters:
445
+ config ([`TrOCRConfig`]):
446
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
447
+ load the weights associated with the model, only the configuration. Check out the
448
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
449
+ """
450
+
451
+
452
+ class TrOCRDecoder(TrOCRPreTrainedModel):
453
+ """
454
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TrOCRDecoderLayer`]
455
+
456
+ Args:
457
+ config: TrOCRConfig
458
+ """
459
+
460
+ def __init__(self, config: TrOCRConfig):
461
+ super().__init__(config)
462
+ self.dropout = config.dropout
463
+ self.layerdrop = config.decoder_layerdrop
464
+ self.padding_idx = config.pad_token_id
465
+ embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0
466
+
467
+ self.embed_tokens = TrOCRScaledWordEmbedding(
468
+ config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=embed_scale
469
+ )
470
+
471
+ if config.use_learned_position_embeddings:
472
+ self.embed_positions = TrOCRLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size)
473
+ else:
474
+ self.embed_positions = TrOCRSinusoidalPositionalEmbedding(
475
+ config.max_position_embeddings + self.padding_idx + 1,
476
+ config.hidden_size,
477
+ self.padding_idx,
478
+ )
479
+
480
+ if config.layernorm_embedding:
481
+ self.layernorm_embedding = nn.LayerNorm(config.hidden_size)
482
+ else:
483
+ self.layernorm_embedding = None
484
+
485
+ self.layers = nn.ModuleList([TrOCRDecoderLayer(config) for _ in range(config.decoder_layers)])
486
+
487
+ self.gradient_checkpointing = False
488
+ # Initialize weights and apply final processing
489
+ self.post_init()
490
+
491
+ def get_input_embeddings(self):
492
+ return self.embed_tokens
493
+
494
+ def set_input_embeddings(self, value):
495
+ self.embed_tokens = value
496
+
497
+ def forward(
498
+ self,
499
+ input_ids=None,
500
+ attention_mask=None,
501
+ encoder_hidden_states=None,
502
+ encoder_attention_mask=None,
503
+ head_mask=None,
504
+ cross_attn_head_mask=None,
505
+ past_key_values=None,
506
+ inputs_embeds=None,
507
+ use_cache=None,
508
+ output_attentions=None,
509
+ output_hidden_states=None,
510
+ return_dict=None,
511
+ ):
512
+ r"""
513
+ Args:
514
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
515
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
516
+ provide it.
517
+
518
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
519
+ [`PreTrainedTokenizer.__call__`] for details.
520
+
521
+ [What are input IDs?](../glossary#input-ids)
522
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
523
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
524
+
525
+ - 1 for tokens that are **not masked**,
526
+ - 0 for tokens that are **masked**.
527
+
528
+ [What are attention masks?](../glossary#attention-mask)
529
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
530
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
531
+ of the decoder.
532
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
533
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
534
+ selected in `[0, 1]`:
535
+
536
+ - 1 for tokens that are **not masked**,
537
+ - 0 for tokens that are **masked**.
538
+
539
+ [What are attention masks?](../glossary#attention-mask)
540
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
541
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
542
+
543
+ - 1 indicates the head is **not masked**,
544
+ - 0 indicates the head is **masked**.
545
+
546
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
547
+ Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
548
+ on hidden heads. Mask values selected in `[0, 1]`:
549
+
550
+ - 1 indicates the head is **not masked**,
551
+ - 0 indicates the head is **masked**.
552
+
553
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
554
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
555
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
556
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
557
+
558
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
559
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
560
+
561
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
562
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
563
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
564
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
565
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
566
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
567
+ than the model's internal embedding lookup matrix.
568
+ output_attentions (`bool`, *optional*):
569
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
570
+ returned tensors for more detail.
571
+ output_hidden_states (`bool`, *optional*):
572
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
573
+ for more detail.
574
+ return_dict (`bool`, *optional*):
575
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
576
+ """
577
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
578
+ output_hidden_states = (
579
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
580
+ )
581
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
582
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
583
+
584
+ # retrieve input_ids and inputs_embeds
585
+ if input_ids is not None and inputs_embeds is not None:
586
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
587
+ elif input_ids is not None:
588
+ input = input_ids
589
+ input_ids = input_ids.view(-1, input.shape[-1])
590
+ elif inputs_embeds is not None:
591
+ input_shape = inputs_embeds.size()[:-1]
592
+ input = inputs_embeds[:, :, -1]
593
+ else:
594
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
595
+
596
+ # past_key_values_length
597
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
598
+
599
+ if inputs_embeds is None:
600
+ inputs_embeds = self.embed_tokens(input_ids)
601
+
602
+ if self.config.use_learned_position_embeddings:
603
+ embed_pos = self.embed_positions(input, past_key_values_length=past_key_values_length)
604
+ else:
605
+ embed_pos = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
606
+
607
+ hidden_states = inputs_embeds + embed_pos
608
+
609
+ if self.layernorm_embedding is not None:
610
+ hidden_states = self.layernorm_embedding(hidden_states)
611
+
612
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
613
+
614
+ input_shape = input.shape
615
+
616
+ attention_mask = _prepare_4d_causal_attention_mask(
617
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
618
+ )
619
+
620
+ # expand encoder attention mask
621
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
622
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
623
+ encoder_attention_mask = _prepare_4d_attention_mask(
624
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
625
+ )
626
+
627
+ if self.gradient_checkpointing and self.training:
628
+ if use_cache:
629
+ logger.warning_once(
630
+ "`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`..."
631
+ )
632
+ use_cache = False
633
+
634
+ # decoder layers
635
+ all_hidden_states = () if output_hidden_states else None
636
+ all_self_attns = () if output_attentions else None
637
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
638
+ next_decoder_cache = () if use_cache else None
639
+
640
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
641
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
642
+ if attn_mask is not None:
643
+ if attn_mask.size()[0] != (len(self.layers)):
644
+ raise ValueError(
645
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
646
+ f" {head_mask.size()[0]}."
647
+ )
648
+ for idx, decoder_layer in enumerate(self.layers):
649
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
650
+ if output_hidden_states:
651
+ all_hidden_states += (hidden_states,)
652
+ if self.training:
653
+ dropout_probability = torch.rand([])
654
+ if dropout_probability < self.layerdrop:
655
+ continue
656
+
657
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
658
+
659
+ if self.gradient_checkpointing and self.training:
660
+ layer_outputs = self._gradient_checkpointing_func(
661
+ decoder_layer.__call__,
662
+ hidden_states,
663
+ attention_mask,
664
+ encoder_hidden_states,
665
+ encoder_attention_mask,
666
+ head_mask[idx] if head_mask is not None else None,
667
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
668
+ None,
669
+ output_attentions,
670
+ use_cache,
671
+ )
672
+ else:
673
+ layer_outputs = decoder_layer(
674
+ hidden_states,
675
+ attention_mask=attention_mask,
676
+ encoder_hidden_states=encoder_hidden_states,
677
+ encoder_attention_mask=encoder_attention_mask,
678
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
679
+ cross_attn_layer_head_mask=(
680
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
681
+ ),
682
+ past_key_value=past_key_value,
683
+ output_attentions=output_attentions,
684
+ use_cache=use_cache,
685
+ )
686
+ hidden_states = layer_outputs[0]
687
+
688
+ if use_cache:
689
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
690
+
691
+ if output_attentions:
692
+ all_self_attns += (layer_outputs[1],)
693
+
694
+ if encoder_hidden_states is not None:
695
+ all_cross_attentions += (layer_outputs[2],)
696
+
697
+ # add hidden states from the last decoder layer
698
+ if output_hidden_states:
699
+ all_hidden_states += (hidden_states,)
700
+
701
+ next_cache = next_decoder_cache if use_cache else None
702
+ if not return_dict:
703
+ return tuple(
704
+ v
705
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
706
+ if v is not None
707
+ )
708
+ return BaseModelOutputWithPastAndCrossAttentions(
709
+ last_hidden_state=hidden_states,
710
+ past_key_values=next_cache,
711
+ hidden_states=all_hidden_states,
712
+ attentions=all_self_attns,
713
+ cross_attentions=all_cross_attentions,
714
+ )
715
+
716
+
717
+ @add_start_docstrings(
718
+ "The TrOCR Model with a language modeling head. Can be used for summarization.",
719
+ TROCR_START_DOCSTRING,
720
+ )
721
+ class TrOCRDecoderWrapper(TrOCRPreTrainedModel):
722
+ """
723
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
724
+ used in combination with the [`EncoderDecoderModel`] framework.
725
+ """
726
+
727
+ def __init__(self, config):
728
+ super().__init__(config)
729
+ self.decoder = TrOCRDecoder(config)
730
+
731
+ def forward(self, *args, **kwargs):
732
+ return self.decoder(*args, **kwargs)
733
+
734
+
735
+ @add_start_docstrings(
736
+ "The TrOCR Decoder with a language modeling head. Can be used as the decoder part of [`EncoderDecoderModel`] and"
737
+ " [`VisionEncoderDecoder`].",
738
+ TROCR_START_DOCSTRING,
739
+ )
740
+ class TrOCRForCausalLM(TrOCRPreTrainedModel, GenerationMixin):
741
+ _tied_weights_keys = ["output_projection.weight"]
742
+
743
+ def __init__(self, config):
744
+ config = copy.deepcopy(config)
745
+ config.is_decoder = True
746
+ config.is_encoder_decoder = False
747
+ super().__init__(config)
748
+ self.model = TrOCRDecoderWrapper(config)
749
+
750
+ self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
751
+
752
+ # Initialize weights and apply final processing
753
+ self.post_init()
754
+
755
+ def get_input_embeddings(self):
756
+ return self.model.decoder.embed_tokens
757
+
758
+ def set_input_embeddings(self, value):
759
+ self.model.decoder.embed_tokens = value
760
+
761
+ def get_output_embeddings(self):
762
+ return self.output_projection
763
+
764
+ def set_output_embeddings(self, new_embeddings):
765
+ self.output_projection = new_embeddings
766
+
767
+ def set_decoder(self, decoder):
768
+ self.model.decoder = decoder
769
+
770
+ def get_decoder(self):
771
+ return self.model.decoder
772
+
773
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
774
+ def forward(
775
+ self,
776
+ input_ids: Optional[torch.LongTensor] = None,
777
+ attention_mask: Optional[torch.Tensor] = None,
778
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
779
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
780
+ head_mask: Optional[torch.Tensor] = None,
781
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
782
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
783
+ inputs_embeds: Optional[torch.FloatTensor] = None,
784
+ labels: Optional[torch.LongTensor] = None,
785
+ use_cache: Optional[bool] = None,
786
+ output_attentions: Optional[bool] = None,
787
+ output_hidden_states: Optional[bool] = None,
788
+ return_dict: Optional[bool] = None,
789
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
790
+ r"""
791
+ Args:
792
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
793
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
794
+ provide it.
795
+
796
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
797
+ [`PreTrainedTokenizer.__call__`] for details.
798
+
799
+ [What are input IDs?](../glossary#input-ids)
800
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
801
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
802
+
803
+ - 1 for tokens that are **not masked**,
804
+ - 0 for tokens that are **masked**.
805
+
806
+ [What are attention masks?](../glossary#attention-mask)
807
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
808
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
809
+ if the model is configured as a decoder.
810
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
811
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
812
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
813
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
814
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
815
+
816
+ - 1 indicates the head is **not masked**,
817
+ - 0 indicates the head is **masked**.
818
+
819
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
820
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
821
+
822
+ - 1 indicates the head is **not masked**,
823
+ - 0 indicates the head is **masked**.
824
+
825
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
826
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
827
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
828
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
829
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
830
+
831
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
832
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
833
+
834
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
835
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
836
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
837
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
838
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
839
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
840
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
841
+ use_cache (`bool`, *optional*):
842
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
843
+ (see `past_key_values`).
844
+
845
+ - 1 for tokens that are **not masked**,
846
+ - 0 for tokens that are **masked**.
847
+ output_attentions (`bool`, *optional*):
848
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
849
+ returned tensors for more detail.
850
+ output_hidden_states (`bool`, *optional*):
851
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
852
+ for more detail.
853
+ return_dict (`bool`, *optional*):
854
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
855
+
856
+ Returns:
857
+
858
+ Example:
859
+
860
+ ```python
861
+ >>> from transformers import (
862
+ ... TrOCRConfig,
863
+ ... TrOCRProcessor,
864
+ ... TrOCRForCausalLM,
865
+ ... ViTConfig,
866
+ ... ViTModel,
867
+ ... VisionEncoderDecoderModel,
868
+ ... )
869
+ >>> import requests
870
+ >>> from PIL import Image
871
+
872
+ >>> # TrOCR is a decoder model and should be used within a VisionEncoderDecoderModel
873
+ >>> # init vision2text model with random weights
874
+ >>> encoder = ViTModel(ViTConfig())
875
+ >>> decoder = TrOCRForCausalLM(TrOCRConfig())
876
+ >>> model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)
877
+
878
+ >>> # If you want to start from the pretrained model, load the checkpoint with `VisionEncoderDecoderModel`
879
+ >>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
880
+ >>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
881
+
882
+ >>> # load image from the IAM dataset
883
+ >>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
884
+ >>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
885
+ >>> pixel_values = processor(image, return_tensors="pt").pixel_values
886
+ >>> text = "industry, ' Mr. Brown commented icily. ' Let us have a"
887
+
888
+ >>> # training
889
+ >>> model.config.decoder_start_token_id = processor.tokenizer.eos_token_id
890
+ >>> model.config.pad_token_id = processor.tokenizer.pad_token_id
891
+ >>> model.config.vocab_size = model.config.decoder.vocab_size
892
+
893
+ >>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
894
+ >>> outputs = model(pixel_values, labels=labels)
895
+ >>> loss = outputs.loss
896
+ >>> round(loss.item(), 2)
897
+ 5.30
898
+
899
+ >>> # inference
900
+ >>> generated_ids = model.generate(pixel_values)
901
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
902
+ >>> generated_text
903
+ 'industry, " Mr. Brown commented icily. " Let us have a'
904
+ ```"""
905
+
906
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
907
+ output_hidden_states = (
908
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
909
+ )
910
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
911
+
912
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
913
+ outputs = self.model.decoder(
914
+ input_ids=input_ids,
915
+ attention_mask=attention_mask,
916
+ encoder_hidden_states=encoder_hidden_states,
917
+ encoder_attention_mask=encoder_attention_mask,
918
+ head_mask=head_mask,
919
+ cross_attn_head_mask=cross_attn_head_mask,
920
+ past_key_values=past_key_values,
921
+ inputs_embeds=inputs_embeds,
922
+ use_cache=use_cache,
923
+ output_attentions=output_attentions,
924
+ output_hidden_states=output_hidden_states,
925
+ return_dict=return_dict,
926
+ )
927
+
928
+ logits = self.output_projection(outputs[0])
929
+
930
+ loss = None
931
+ if labels is not None:
932
+ loss_fct = CrossEntropyLoss()
933
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
934
+
935
+ if not return_dict:
936
+ output = (logits,) + outputs[1:]
937
+ return (loss,) + output if loss is not None else output
938
+
939
+ return CausalLMOutputWithCrossAttentions(
940
+ loss=loss,
941
+ logits=logits,
942
+ past_key_values=outputs.past_key_values,
943
+ hidden_states=outputs.hidden_states,
944
+ attentions=outputs.attentions,
945
+ cross_attentions=outputs.cross_attentions,
946
+ )
947
+
948
+ @staticmethod
949
+ def _reorder_cache(past_key_values, beam_idx):
950
+ reordered_past = ()
951
+ for layer_past in past_key_values:
952
+ reordered_past += (
953
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
954
+ )
955
+ return reordered_past
956
+
957
+
958
+ __all__ = ["TrOCRForCausalLM", "TrOCRPreTrainedModel"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/trocr/processing_trocr.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for TrOCR.
17
+ """
18
+
19
+ import warnings
20
+ from contextlib import contextmanager
21
+ from typing import List, Union
22
+
23
+ from ...image_processing_utils import BatchFeature
24
+ from ...image_utils import ImageInput
25
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
26
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
27
+
28
+
29
+ class TrOCRProcessorKwargs(ProcessingKwargs, total=False):
30
+ _defaults = {}
31
+
32
+
33
+ class TrOCRProcessor(ProcessorMixin):
34
+ r"""
35
+ Constructs a TrOCR processor which wraps a vision image processor and a TrOCR tokenizer into a single processor.
36
+
37
+ [`TrOCRProcessor`] offers all the functionalities of [`ViTImageProcessor`/`DeiTImageProcessor`] and
38
+ [`RobertaTokenizer`/`XLMRobertaTokenizer`]. See the [`~TrOCRProcessor.__call__`] and [`~TrOCRProcessor.decode`] for
39
+ more information.
40
+
41
+ Args:
42
+ image_processor ([`ViTImageProcessor`/`DeiTImageProcessor`], *optional*):
43
+ An instance of [`ViTImageProcessor`/`DeiTImageProcessor`]. The image processor is a required input.
44
+ tokenizer ([`RobertaTokenizer`/`XLMRobertaTokenizer`], *optional*):
45
+ An instance of [`RobertaTokenizer`/`XLMRobertaTokenizer`]. The tokenizer is a required input.
46
+ """
47
+
48
+ attributes = ["image_processor", "tokenizer"]
49
+ image_processor_class = "AutoImageProcessor"
50
+ tokenizer_class = "AutoTokenizer"
51
+
52
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
53
+ feature_extractor = None
54
+ if "feature_extractor" in kwargs:
55
+ warnings.warn(
56
+ "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
57
+ " instead.",
58
+ FutureWarning,
59
+ )
60
+ feature_extractor = kwargs.pop("feature_extractor")
61
+
62
+ image_processor = image_processor if image_processor is not None else feature_extractor
63
+ if image_processor is None:
64
+ raise ValueError("You need to specify an `image_processor`.")
65
+ if tokenizer is None:
66
+ raise ValueError("You need to specify a `tokenizer`.")
67
+
68
+ super().__init__(image_processor, tokenizer)
69
+ self.current_processor = self.image_processor
70
+ self._in_target_context_manager = False
71
+
72
+ def __call__(
73
+ self,
74
+ images: ImageInput = None,
75
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
76
+ audio=None,
77
+ videos=None,
78
+ **kwargs: Unpack[TrOCRProcessorKwargs],
79
+ ) -> BatchFeature:
80
+ """
81
+ When used in normal mode, this method forwards all its arguments to AutoImageProcessor's
82
+ [`~AutoImageProcessor.__call__`] and returns its output. If used in the context
83
+ [`~TrOCRProcessor.as_target_processor`] this method forwards all its arguments to TrOCRTokenizer's
84
+ [`~TrOCRTokenizer.__call__`]. Please refer to the doctsring of the above two methods for more information.
85
+ """
86
+ # For backward compatibility
87
+ if self._in_target_context_manager:
88
+ return self.current_processor(images, **kwargs)
89
+
90
+ if images is None and text is None:
91
+ raise ValueError("You need to specify either an `images` or `text` input to process.")
92
+
93
+ output_kwargs = self._merge_kwargs(
94
+ TrOCRProcessorKwargs,
95
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
96
+ **kwargs,
97
+ )
98
+
99
+ if images is not None:
100
+ inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
101
+ if text is not None:
102
+ encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
103
+
104
+ if text is None:
105
+ return inputs
106
+ elif images is None:
107
+ return encodings
108
+ else:
109
+ inputs["labels"] = encodings["input_ids"]
110
+ return inputs
111
+
112
+ def batch_decode(self, *args, **kwargs):
113
+ """
114
+ This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer
115
+ to the docstring of this method for more information.
116
+ """
117
+ return self.tokenizer.batch_decode(*args, **kwargs)
118
+
119
+ def decode(self, *args, **kwargs):
120
+ """
121
+ This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
122
+ docstring of this method for more information.
123
+ """
124
+ return self.tokenizer.decode(*args, **kwargs)
125
+
126
+ @contextmanager
127
+ def as_target_processor(self):
128
+ """
129
+ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning TrOCR.
130
+ """
131
+ warnings.warn(
132
+ "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
133
+ "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
134
+ "your images inputs, or in a separate call."
135
+ )
136
+ self._in_target_context_manager = True
137
+ self.current_processor = self.tokenizer
138
+ yield
139
+ self.current_processor = self.image_processor
140
+ self._in_target_context_manager = False
141
+
142
+ @property
143
+ def feature_extractor_class(self):
144
+ warnings.warn(
145
+ "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
146
+ FutureWarning,
147
+ )
148
+ return self.image_processor_class
149
+
150
+ @property
151
+ def feature_extractor(self):
152
+ warnings.warn(
153
+ "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
154
+ FutureWarning,
155
+ )
156
+ return self.image_processor
157
+
158
+
159
+ __all__ = ["TrOCRProcessor"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_tvp import *
22
+ from .image_processing_tvp import *
23
+ from .modeling_tvp import *
24
+ from .processing_tvp import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/configuration_tvp.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Intel AIA Team Authors, and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License=, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing=, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS=,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND=, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """TVP model configuration"""
16
+
17
+ import copy
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+ from ...utils.backbone_utils import verify_backbone_config_arguments
22
+ from ..auto import CONFIG_MAPPING
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class TvpConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`TvpModel`]. It is used to instantiate an Tvp
31
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
32
+ defaults will yield a similar configuration to that of the Tvp
33
+ [Intel/tvp-base](https://huggingface.co/Intel/tvp-base) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ backbone_config (`PretrainedConfig` or `dict`, *optional*):
41
+ The configuration of the backbone model.
42
+ backbone (`str`, *optional*):
43
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
44
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
45
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
46
+ use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
47
+ Whether to use pretrained weights for the backbone.
48
+ use_timm_backbone (`bool`, *optional*, defaults to `False`):
49
+ Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
50
+ library.
51
+ backbone_kwargs (`dict`, *optional*):
52
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
53
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
54
+ distance_loss_weight (`float`, *optional*, defaults to 1.0):
55
+ The weight of distance loss.
56
+ duration_loss_weight (`float`, *optional*, defaults to 0.1):
57
+ The weight of duration loss.
58
+ visual_prompter_type (`str`, *optional*, defaults to `"framepad"`):
59
+ Visual prompt type. The type of padding. Framepad means padding on each frame. Should be one of "framepad"
60
+ or "framedownpad"
61
+ visual_prompter_apply (`str`, *optional*, defaults to `"replace"`):
62
+ The way of applying visual prompt. Replace means use the value of prompt to change the original value in
63
+ visual inputs. Should be one of "replace", or "add", or "remove".
64
+ visual_prompt_size (`int`, *optional*, defaults to 96):
65
+ The size of visual prompt.
66
+ max_img_size (`int`, *optional*, defaults to 448):
67
+ The maximum size of frame.
68
+ num_frames (`int`, *optional*, defaults to 48):
69
+ The number of frames extracted from a video.
70
+ vocab_size (`int`, *optional*, defaults to 30522):
71
+ Vocabulary size of the Tvp text model. Defines the number of different tokens that can be represented by
72
+ the `inputs_ids` passed when calling [`TvpModel`].
73
+ hidden_size (`int`, *optional*, defaults to 768):
74
+ Dimensionality of the encoder layers.
75
+ intermediate_size (`int`, *optional*, defaults to 3072):
76
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
77
+ num_hidden_layers (`int`, *optional*, defaults to 12):
78
+ Number of hidden layers in the Transformer encoder.
79
+ num_attention_heads (`int`, *optional*, defaults to 12):
80
+ Number of attention heads for each attention layer in the Transformer encoder.
81
+ max_position_embeddings (`int`, *optional*, defaults to 512):
82
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
83
+ just in case (e.g., 512 or 1024 or 2048).
84
+ max_grid_col_position_embeddings (`int`, *optional*, defaults to 100):
85
+ The largest number of horizontal patches from a video frame.
86
+ max_grid_row_position_embeddings (`int`, *optional*, defaults to 100):
87
+ The largest number of vertical patches from a video frame.
88
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
89
+ The dropout probability of hidden layers.
90
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
91
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
92
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
93
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
94
+ The epsilon used by the layer normalization layers.
95
+ initializer_range (`float`, *optional*, defaults to 0.02):
96
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
97
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
98
+ The dropout probability of attention layers.
99
+ """
100
+
101
+ model_type = "tvp"
102
+
103
+ def __init__(
104
+ self,
105
+ backbone_config=None,
106
+ backbone=None,
107
+ use_pretrained_backbone=False,
108
+ use_timm_backbone=False,
109
+ backbone_kwargs=None,
110
+ distance_loss_weight=1.0,
111
+ duration_loss_weight=0.1,
112
+ visual_prompter_type="framepad",
113
+ visual_prompter_apply="replace",
114
+ visual_prompt_size=96,
115
+ max_img_size=448,
116
+ num_frames=48,
117
+ vocab_size=30522,
118
+ hidden_size=768,
119
+ intermediate_size=3072,
120
+ num_hidden_layers=12,
121
+ num_attention_heads=12,
122
+ max_position_embeddings=512,
123
+ max_grid_col_position_embeddings=100,
124
+ max_grid_row_position_embeddings=100,
125
+ hidden_dropout_prob=0.1,
126
+ hidden_act="gelu",
127
+ layer_norm_eps=1e-12,
128
+ initializer_range=0.02,
129
+ attention_probs_dropout_prob=0.1,
130
+ **kwargs,
131
+ ):
132
+ super().__init__(**kwargs)
133
+ if backbone_config is None and backbone is None:
134
+ logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
135
+ backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
136
+ elif isinstance(backbone_config, dict):
137
+ backbone_model_type = backbone_config.get("model_type")
138
+ config_class = CONFIG_MAPPING[backbone_model_type]
139
+ backbone_config = config_class.from_dict(backbone_config)
140
+
141
+ verify_backbone_config_arguments(
142
+ use_timm_backbone=use_timm_backbone,
143
+ use_pretrained_backbone=use_pretrained_backbone,
144
+ backbone=backbone,
145
+ backbone_config=backbone_config,
146
+ backbone_kwargs=backbone_kwargs,
147
+ )
148
+
149
+ self.backbone_config = backbone_config
150
+ self.backbone = backbone
151
+ self.use_pretrained_backbone = use_pretrained_backbone
152
+ self.use_timm_backbone = use_timm_backbone
153
+ self.backbone_kwargs = backbone_kwargs
154
+ self.distance_loss_weight = distance_loss_weight
155
+ self.duration_loss_weight = duration_loss_weight
156
+ self.visual_prompter_type = visual_prompter_type
157
+ self.visual_prompter_apply = visual_prompter_apply
158
+ self.visual_prompt_size = visual_prompt_size
159
+ self.max_img_size = max_img_size
160
+ self.num_frames = num_frames
161
+ self.vocab_size = vocab_size
162
+ self.hidden_size = hidden_size
163
+ self.intermediate_size = intermediate_size
164
+ self.num_hidden_layers = num_hidden_layers
165
+ self.num_attention_heads = num_attention_heads
166
+ self.max_position_embeddings = max_position_embeddings
167
+ self.max_grid_col_position_embeddings = max_grid_col_position_embeddings
168
+ self.max_grid_row_position_embeddings = max_grid_row_position_embeddings
169
+ self.layer_norm_eps = layer_norm_eps
170
+ self.hidden_dropout_prob = hidden_dropout_prob
171
+ self.hidden_act = hidden_act
172
+ self.initializer_range = initializer_range
173
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
174
+
175
+ @classmethod
176
+ def from_backbone_config(cls, backbone_config: PretrainedConfig, **kwargs):
177
+ """Instantiate a [`TvpConfig`] (or a derived class) from a pre-trained backbone model configuration.
178
+
179
+ Args:
180
+ backbone_config ([`PretrainedConfig`]):
181
+ The backbone configuration.
182
+ Returns:
183
+ [`TvpConfig`]: An instance of a configuration object
184
+ """
185
+ return cls(backbone_config=backbone_config, **kwargs)
186
+
187
+ def to_dict(self):
188
+ """
189
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
190
+
191
+ Returns:
192
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
193
+ """
194
+ output = copy.deepcopy(self.__dict__)
195
+ if output["backbone_config"] is not None:
196
+ output["backbone_config"] = self.backbone_config.to_dict()
197
+ output["model_type"] = self.__class__.model_type
198
+ return output
199
+
200
+
201
+ __all__ = ["TvpConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/image_processing_tvp.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Intel AIA Team Authors, and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License=, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing=, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS=,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND=, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Image processor class for TVP."""
16
+
17
+ from typing import Dict, Iterable, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import (
23
+ PaddingMode,
24
+ flip_channel_order,
25
+ pad,
26
+ resize,
27
+ to_channel_dimension_format,
28
+ )
29
+ from ...image_utils import (
30
+ IMAGENET_STANDARD_MEAN,
31
+ IMAGENET_STANDARD_STD,
32
+ ChannelDimension,
33
+ ImageInput,
34
+ PILImageResampling,
35
+ get_image_size,
36
+ is_valid_image,
37
+ to_numpy_array,
38
+ valid_images,
39
+ validate_preprocess_arguments,
40
+ )
41
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
42
+
43
+
44
+ if is_vision_available():
45
+ import PIL
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ # Copied from transformers.models.vivit.image_processing_vivit.make_batched
52
+ def make_batched(videos) -> List[List[ImageInput]]:
53
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
54
+ return videos
55
+
56
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
57
+ return [videos]
58
+
59
+ elif is_valid_image(videos):
60
+ return [[videos]]
61
+
62
+ raise ValueError(f"Could not make batched video from {videos}")
63
+
64
+
65
+ def get_resize_output_image_size(
66
+ input_image: np.ndarray,
67
+ max_size: int = 448,
68
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
69
+ ) -> Tuple[int, int]:
70
+ height, width = get_image_size(input_image, input_data_format)
71
+ if height >= width:
72
+ ratio = width * 1.0 / height
73
+ new_height = max_size
74
+ new_width = new_height * ratio
75
+ else:
76
+ ratio = height * 1.0 / width
77
+ new_width = max_size
78
+ new_height = new_width * ratio
79
+ size = (int(new_height), int(new_width))
80
+
81
+ return size
82
+
83
+
84
+ class TvpImageProcessor(BaseImageProcessor):
85
+ r"""
86
+ Constructs a Tvp image processor.
87
+
88
+ Args:
89
+ do_resize (`bool`, *optional*, defaults to `True`):
90
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
91
+ `do_resize` parameter in the `preprocess` method.
92
+ size (`Dict[str, int]` *optional*, defaults to `{"longest_edge": 448}`):
93
+ Size of the output image after resizing. The longest edge of the image will be resized to
94
+ `size["longest_edge"]` while maintaining the aspect ratio of the original image. Can be overriden by
95
+ `size` in the `preprocess` method.
96
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
97
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
98
+ `preprocess` method.
99
+ do_center_crop (`bool`, *optional*, defaults to `True`):
100
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
101
+ parameter in the `preprocess` method.
102
+ crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 448, "width": 448}`):
103
+ Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
104
+ `preprocess` method.
105
+ do_rescale (`bool`, *optional*, defaults to `True`):
106
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
107
+ parameter in the `preprocess` method.
108
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
109
+ Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
110
+ in the `preprocess` method.
111
+ do_pad (`bool`, *optional*, defaults to `True`):
112
+ Whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess` method.
113
+ pad_size (`Dict[str, int]`, *optional*, defaults to `{"height": 448, "width": 448}`):
114
+ Size of the image after applying the padding. Can be overridden by the `pad_size` parameter in the
115
+ `preprocess` method.
116
+ constant_values (`Union[float, Iterable[float]]`, *optional*, defaults to 0):
117
+ The fill value to use when padding the image.
118
+ pad_mode (`PaddingMode`, *optional*, defaults to `PaddingMode.CONSTANT`):
119
+ Use what kind of mode in padding.
120
+ do_normalize (`bool`, *optional*, defaults to `True`):
121
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
122
+ method.
123
+ do_flip_channel_order (`bool`, *optional*, defaults to `True`):
124
+ Whether to flip the color channels from RGB to BGR. Can be overridden by the `do_flip_channel_order`
125
+ parameter in the `preprocess` method.
126
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
127
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
128
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
129
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
130
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
131
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
132
+ """
133
+
134
+ model_input_names = ["pixel_values"]
135
+
136
+ def __init__(
137
+ self,
138
+ do_resize: bool = True,
139
+ size: Dict[str, int] = None,
140
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
141
+ do_center_crop: bool = True,
142
+ crop_size: Dict[str, int] = None,
143
+ do_rescale: bool = True,
144
+ rescale_factor: Union[int, float] = 1 / 255,
145
+ do_pad: bool = True,
146
+ pad_size: Dict[str, int] = None,
147
+ constant_values: Union[float, Iterable[float]] = 0,
148
+ pad_mode: PaddingMode = PaddingMode.CONSTANT,
149
+ do_normalize: bool = True,
150
+ do_flip_channel_order: bool = True,
151
+ image_mean: Optional[Union[float, List[float]]] = None,
152
+ image_std: Optional[Union[float, List[float]]] = None,
153
+ **kwargs,
154
+ ) -> None:
155
+ super().__init__(**kwargs)
156
+ size = size if size is not None else {"longest_edge": 448}
157
+ crop_size = crop_size if crop_size is not None else {"height": 448, "width": 448}
158
+ pad_size = pad_size if pad_size is not None else {"height": 448, "width": 448}
159
+
160
+ self.do_resize = do_resize
161
+ self.size = size
162
+ self.do_center_crop = do_center_crop
163
+ self.crop_size = crop_size
164
+ self.resample = resample
165
+ self.do_rescale = do_rescale
166
+ self.rescale_factor = rescale_factor
167
+ self.do_pad = do_pad
168
+ self.pad_size = pad_size
169
+ self.constant_values = constant_values
170
+ self.pad_mode = pad_mode
171
+ self.do_normalize = do_normalize
172
+ self.do_flip_channel_order = do_flip_channel_order
173
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
174
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
175
+
176
+ def resize(
177
+ self,
178
+ image: np.ndarray,
179
+ size: Dict[str, int],
180
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
181
+ data_format: Optional[Union[str, ChannelDimension]] = None,
182
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
183
+ **kwargs,
184
+ ) -> np.ndarray:
185
+ """
186
+ Resize an image.
187
+
188
+ Args:
189
+ image (`np.ndarray`):
190
+ Image to resize.
191
+ size (`Dict[str, int]`):
192
+ Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
193
+ have the size `(h, w)`. If `size` is of the form `{"longest_edge": s}`, the output image will have its
194
+ longest edge of length `s` while keeping the aspect ratio of the original image.
195
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
196
+ Resampling filter to use when resiizing the image.
197
+ data_format (`str` or `ChannelDimension`, *optional*):
198
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
199
+ input_data_format (`str` or `ChannelDimension`, *optional*):
200
+ The channel dimension format of the input image. If not provided, it will be inferred.
201
+ """
202
+ size = get_size_dict(size, default_to_square=False)
203
+ if "height" in size and "width" in size:
204
+ output_size = (size["height"], size["width"])
205
+ elif "longest_edge" in size:
206
+ output_size = get_resize_output_image_size(image, size["longest_edge"], input_data_format)
207
+ else:
208
+ raise ValueError(f"Size must have 'height' and 'width' or 'longest_edge' as keys. Got {size.keys()}")
209
+
210
+ return resize(
211
+ image,
212
+ size=output_size,
213
+ resample=resample,
214
+ data_format=data_format,
215
+ input_data_format=input_data_format,
216
+ **kwargs,
217
+ )
218
+
219
+ def pad_image(
220
+ self,
221
+ image: np.ndarray,
222
+ pad_size: Dict[str, int] = None,
223
+ constant_values: Union[float, Iterable[float]] = 0,
224
+ pad_mode: PaddingMode = PaddingMode.CONSTANT,
225
+ data_format: Optional[Union[str, ChannelDimension]] = None,
226
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
227
+ **kwargs,
228
+ ):
229
+ """
230
+ Pad an image with zeros to the given size.
231
+
232
+ Args:
233
+ image (`np.ndarray`):
234
+ Image to pad.
235
+ pad_size (`Dict[str, int]`)
236
+ Size of the output image with pad.
237
+ constant_values (`Union[float, Iterable[float]]`)
238
+ The fill value to use when padding the image.
239
+ pad_mode (`PaddingMode`)
240
+ The pad mode, default to PaddingMode.CONSTANT
241
+ data_format (`ChannelDimension` or `str`, *optional*)
242
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
243
+ input_data_format (`ChannelDimension` or `str`, *optional*):
244
+ The channel dimension format of the input image. If not provided, it will be inferred.
245
+ """
246
+ height, width = get_image_size(image, channel_dim=input_data_format)
247
+ max_height = pad_size.get("height", height)
248
+ max_width = pad_size.get("width", width)
249
+
250
+ pad_right, pad_bottom = max_width - width, max_height - height
251
+ if pad_right < 0 or pad_bottom < 0:
252
+ raise ValueError("The padding size must be greater than image size")
253
+
254
+ padding = ((0, pad_bottom), (0, pad_right))
255
+ padded_image = pad(
256
+ image,
257
+ padding,
258
+ mode=pad_mode,
259
+ constant_values=constant_values,
260
+ data_format=data_format,
261
+ input_data_format=input_data_format,
262
+ )
263
+
264
+ return padded_image
265
+
266
+ def _preprocess_image(
267
+ self,
268
+ image: ImageInput,
269
+ do_resize: bool = None,
270
+ size: Dict[str, int] = None,
271
+ resample: PILImageResampling = None,
272
+ do_center_crop: bool = None,
273
+ crop_size: Dict[str, int] = None,
274
+ do_rescale: bool = None,
275
+ rescale_factor: float = None,
276
+ do_pad: bool = True,
277
+ pad_size: Dict[str, int] = None,
278
+ constant_values: Union[float, Iterable[float]] = None,
279
+ pad_mode: PaddingMode = None,
280
+ do_normalize: bool = None,
281
+ do_flip_channel_order: bool = None,
282
+ image_mean: Optional[Union[float, List[float]]] = None,
283
+ image_std: Optional[Union[float, List[float]]] = None,
284
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
285
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
286
+ **kwargs,
287
+ ) -> np.ndarray:
288
+ """Preprocesses a single image."""
289
+
290
+ validate_preprocess_arguments(
291
+ do_rescale=do_rescale,
292
+ rescale_factor=rescale_factor,
293
+ do_normalize=do_normalize,
294
+ image_mean=image_mean,
295
+ image_std=image_std,
296
+ do_pad=do_pad,
297
+ size_divisibility=pad_size, # here the pad() method simply requires the pad_size argument.
298
+ do_center_crop=do_center_crop,
299
+ crop_size=crop_size,
300
+ do_resize=do_resize,
301
+ size=size,
302
+ resample=resample,
303
+ )
304
+
305
+ # All transformations expect numpy arrays.
306
+ image = to_numpy_array(image)
307
+
308
+ if do_resize:
309
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
310
+
311
+ if do_center_crop:
312
+ image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
313
+
314
+ if do_rescale:
315
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
316
+
317
+ if do_normalize:
318
+ image = self.normalize(
319
+ image=image.astype(np.float32), mean=image_mean, std=image_std, input_data_format=input_data_format
320
+ )
321
+
322
+ if do_pad:
323
+ image = self.pad_image(
324
+ image=image,
325
+ pad_size=pad_size,
326
+ constant_values=constant_values,
327
+ pad_mode=pad_mode,
328
+ input_data_format=input_data_format,
329
+ )
330
+
331
+ # the pretrained checkpoints assume images are BGR, not RGB
332
+ if do_flip_channel_order:
333
+ image = flip_channel_order(image=image, input_data_format=input_data_format)
334
+
335
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
336
+
337
+ return image
338
+
339
+ @filter_out_non_signature_kwargs()
340
+ def preprocess(
341
+ self,
342
+ videos: Union[ImageInput, List[ImageInput], List[List[ImageInput]]],
343
+ do_resize: bool = None,
344
+ size: Dict[str, int] = None,
345
+ resample: PILImageResampling = None,
346
+ do_center_crop: bool = None,
347
+ crop_size: Dict[str, int] = None,
348
+ do_rescale: bool = None,
349
+ rescale_factor: float = None,
350
+ do_pad: bool = None,
351
+ pad_size: Dict[str, int] = None,
352
+ constant_values: Union[float, Iterable[float]] = None,
353
+ pad_mode: PaddingMode = None,
354
+ do_normalize: bool = None,
355
+ do_flip_channel_order: bool = None,
356
+ image_mean: Optional[Union[float, List[float]]] = None,
357
+ image_std: Optional[Union[float, List[float]]] = None,
358
+ return_tensors: Optional[Union[str, TensorType]] = None,
359
+ data_format: ChannelDimension = ChannelDimension.FIRST,
360
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
361
+ ) -> PIL.Image.Image:
362
+ """
363
+ Preprocess an image or batch of images.
364
+
365
+ Args:
366
+ videos (`ImageInput` or `List[ImageInput]` or `List[List[ImageInput]]`):
367
+ Frames to preprocess.
368
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
369
+ Whether to resize the image.
370
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
371
+ Size of the image after applying resize.
372
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
373
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
374
+ has an effect if `do_resize` is set to `True`.
375
+ do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
376
+ Whether to centre crop the image.
377
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
378
+ Size of the image after applying the centre crop.
379
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
380
+ Whether to rescale the image values between [0 - 1].
381
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
382
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
383
+ do_pad (`bool`, *optional*, defaults to `True`):
384
+ Whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess` method.
385
+ pad_size (`Dict[str, int]`, *optional*, defaults to `{"height": 448, "width": 448}`):
386
+ Size of the image after applying the padding. Can be overridden by the `pad_size` parameter in the
387
+ `preprocess` method.
388
+ constant_values (`Union[float, Iterable[float]]`, *optional*, defaults to 0):
389
+ The fill value to use when padding the image.
390
+ pad_mode (`PaddingMode`, *optional*, defaults to "PaddingMode.CONSTANT"):
391
+ Use what kind of mode in padding.
392
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
393
+ Whether to normalize the image.
394
+ do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):
395
+ Whether to flip the channel order of the image.
396
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
397
+ Image mean.
398
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
399
+ Image standard deviation.
400
+ return_tensors (`str` or `TensorType`, *optional*):
401
+ The type of tensors to return. Can be one of:
402
+ - Unset: Return a list of `np.ndarray`.
403
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
404
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
405
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
406
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
407
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
408
+ The channel dimension format for the output image. Can be one of:
409
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
410
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
411
+ - Unset: Use the inferred channel dimension format of the input image.
412
+ input_data_format (`ChannelDimension` or `str`, *optional*):
413
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
414
+ from the input image. Can be one of:
415
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
416
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
417
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
418
+ """
419
+ do_resize = do_resize if do_resize is not None else self.do_resize
420
+ resample = resample if resample is not None else self.resample
421
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
422
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
423
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
424
+ do_pad = do_pad if do_pad is not None else self.do_pad
425
+ pad_size = pad_size if pad_size is not None else self.pad_size
426
+ constant_values = constant_values if constant_values is not None else self.constant_values
427
+ pad_mode = pad_mode if pad_mode else self.pad_mode
428
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
429
+ do_flip_channel_order = (
430
+ do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
431
+ )
432
+ image_mean = image_mean if image_mean is not None else self.image_mean
433
+ image_std = image_std if image_std is not None else self.image_std
434
+
435
+ size = size if size is not None else self.size
436
+ size = get_size_dict(size, default_to_square=False)
437
+ crop_size = crop_size if crop_size is not None else self.crop_size
438
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
439
+
440
+ if not valid_images(videos):
441
+ raise ValueError(
442
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
443
+ "torch.Tensor, tf.Tensor or jax.ndarray."
444
+ )
445
+
446
+ videos = make_batched(videos)
447
+
448
+ videos = [
449
+ np.array(
450
+ [
451
+ self._preprocess_image(
452
+ image=img,
453
+ do_resize=do_resize,
454
+ size=size,
455
+ resample=resample,
456
+ do_center_crop=do_center_crop,
457
+ crop_size=crop_size,
458
+ do_rescale=do_rescale,
459
+ rescale_factor=rescale_factor,
460
+ do_pad=do_pad,
461
+ pad_size=pad_size,
462
+ constant_values=constant_values,
463
+ pad_mode=pad_mode,
464
+ do_normalize=do_normalize,
465
+ do_flip_channel_order=do_flip_channel_order,
466
+ image_mean=image_mean,
467
+ image_std=image_std,
468
+ data_format=data_format,
469
+ input_data_format=input_data_format,
470
+ )
471
+ for img in video
472
+ ]
473
+ )
474
+ for video in videos
475
+ ]
476
+
477
+ data = {"pixel_values": videos}
478
+ return BatchFeature(data=data, tensor_type=return_tensors)
479
+
480
+
481
+ __all__ = ["TvpImageProcessor"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/modeling_tvp.py ADDED
@@ -0,0 +1,985 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Intel AIA Team Authors, and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License=, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing=, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS=,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND=, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch TVP Model"""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+
25
+ from ...activations import ACT2FN
26
+ from ...file_utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
27
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ModelOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...pytorch_utils import prune_linear_layer
30
+ from ...utils import logging
31
+ from ...utils.backbone_utils import load_backbone
32
+ from .configuration_tvp import TvpConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ @dataclass
39
+ class TvpVideoGroundingOutput(ModelOutput):
40
+ """
41
+ Args:
42
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
43
+ Temporal-Distance IoU loss for video grounding.
44
+ logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
45
+ Contains start_time/duration and end_time/duration. It is the time slot of the videos corresponding to the
46
+ input texts.
47
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
48
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
49
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
50
+ the model at the output of each layer plus the optional initial embedding outputs.
51
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
52
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
53
+ sequence_length)`.
54
+ """
55
+
56
+ loss: Optional[torch.FloatTensor] = None
57
+ logits: torch.FloatTensor = None
58
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
59
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
60
+
61
+
62
+ class TvpLoss(nn.Module):
63
+ """
64
+ This class computes the losses for `TvpForVideoGrounding`. The process happens in two steps: 1) we compute
65
+ hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched
66
+ ground-truth / prediction (supervise class and box).
67
+
68
+ Args:
69
+ losses (`List[str]`):
70
+ List of all the losses to be applied.
71
+ """
72
+
73
+ def __init__(self, losses):
74
+ super().__init__()
75
+ self.loss_map = {
76
+ "iou": self.loss_iou,
77
+ "distance": self.loss_distance,
78
+ "duration": self.loss_duration,
79
+ }
80
+ for loss in losses:
81
+ if loss not in self.loss_map:
82
+ raise ValueError(f"Loss {loss} not supported")
83
+
84
+ self.losses = losses
85
+
86
+ def loss_iou(self, start_time, end_time, candidates_start_time, candidates_end_time, duration):
87
+ """
88
+ Measure the intersection over union.
89
+ """
90
+ inter = torch.min(candidates_end_time, end_time) - torch.max(candidates_start_time, start_time)
91
+ union = torch.max(candidates_end_time, end_time) - torch.min(candidates_start_time, start_time)
92
+ iou = 1 - inter.clamp(min=0) / union
93
+
94
+ return iou
95
+
96
+ def loss_distance(self, start_time, end_time, candidates_start_time, candidates_end_time, duration):
97
+ """
98
+ Measure the distance of mid points.
99
+ """
100
+ mid_candidates = torch.div(torch.add(candidates_start_time, candidates_end_time), 2.0)
101
+ mid_groundtruth = torch.div(torch.add(start_time, end_time), 2.0)
102
+ distance_diff = torch.div(
103
+ torch.max(mid_candidates, mid_groundtruth) - torch.min(mid_candidates, mid_groundtruth), duration
104
+ ).clamp(min=0.2)
105
+
106
+ return distance_diff
107
+
108
+ def loss_duration(self, start_time, end_time, candidates_start_time, candidates_end_time, duration):
109
+ """
110
+ Measure the difference of duration.
111
+ """
112
+ duration_candidates = torch.sub(candidates_end_time, candidates_start_time)
113
+ duration_groundtruth = torch.sub(end_time, start_time)
114
+ duration_diff = torch.square(torch.div(torch.sub(duration_candidates, duration_groundtruth), duration))
115
+ duration_diff = duration_diff.clamp(min=0.4)
116
+
117
+ return duration_diff
118
+
119
+ def forward(self, logits, labels):
120
+ """
121
+ This performs the loss computation.
122
+
123
+ Args:
124
+ logits (`torch.FloatTensor`):
125
+ The output logits of head module.
126
+ labels (`List[torch.FloatTensor]`):
127
+ List of tensors ([start, end, duration]), which contains start time, end time of the video corresponding to the text, and also the duration.
128
+ """
129
+ duration, start_time, end_time = labels
130
+ candidates = torch.mul(logits, duration)
131
+ candidates_start_time, candidates_end_time = candidates[:, 0].float(), candidates[:, 1].float()
132
+
133
+ losses_dict = {}
134
+ for loss in self.losses:
135
+ losses_dict.update(
136
+ {loss: self.loss_map[loss](start_time, end_time, candidates_start_time, candidates_end_time, duration)}
137
+ )
138
+
139
+ return losses_dict
140
+
141
+
142
+ class TvpVisionModel(nn.Module):
143
+ def __init__(self, config):
144
+ super().__init__()
145
+ self.backbone = load_backbone(config)
146
+
147
+ if config.backbone_config is not None:
148
+ in_channels = config.backbone_config.hidden_sizes[-1]
149
+ elif hasattr(self.backbone, "config") and hasattr(self.backbone.config, "hidden_sizes"):
150
+ in_channels = self.backbone.config.hidden_sizes[-1]
151
+ elif hasattr(self.backbone, "config") and hasattr(self.backbone.config, "hidden_size"):
152
+ in_channels = self.backbone.config.hidden_size
153
+ else:
154
+ raise ValueError("Backbone config not found")
155
+
156
+ self.grid_encoder_conv = nn.Conv2d(
157
+ in_channels,
158
+ config.hidden_size,
159
+ kernel_size=3,
160
+ stride=1,
161
+ padding=1,
162
+ groups=1,
163
+ bias=False,
164
+ )
165
+
166
+ def forward(self, pixel_values):
167
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
168
+ # (batch_size * num_frames, num_channels, height, width)
169
+ pixel_values = pixel_values.view(batch_size * num_frames, num_channels, height, width)
170
+ grid_feat_outputs = self.backbone(pixel_values)["feature_maps"][0]
171
+ grid = self.grid_encoder_conv(grid_feat_outputs)
172
+ grid = nn.functional.max_pool2d(grid, kernel_size=2, stride=2)
173
+ grid = nn.functional.relu(grid, inplace=True)
174
+ new_channel, new_height, new_width = grid.shape[-3:]
175
+ # (batch_size, num_frames, num_channels, height, width)
176
+ grid = grid.view(batch_size, num_frames, new_channel, new_height, new_width)
177
+ # (batch_size, num_frames, height, width, num_channels)
178
+ grid = grid.permute(0, 1, 3, 4, 2)
179
+ return grid
180
+
181
+
182
+ class TvpVisualInputEmbedding(nn.Module):
183
+ """
184
+ Takes input of both image and video (multi-frame)
185
+ """
186
+
187
+ def __init__(self, config):
188
+ super().__init__()
189
+ # sequence embedding
190
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
191
+ self.row_position_embeddings = nn.Embedding(config.max_grid_row_position_embeddings, config.hidden_size)
192
+ self.col_position_embeddings = nn.Embedding(config.max_grid_col_position_embeddings, config.hidden_size)
193
+ self.token_type_embeddings = nn.Embedding(1, config.hidden_size)
194
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
195
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
196
+ self.max_grid_row_position_embeddings = config.max_grid_row_position_embeddings
197
+ self.max_grid_col_position_embeddings = config.max_grid_col_position_embeddings
198
+
199
+ def interpolate_pos_encoding(self, embedding: torch.Tensor, height: int, width: int) -> torch.Tensor:
200
+ """
201
+ This method allows to interpolate the pre-trained pad weights , to be able to use the model on collection of high
202
+ resolution images (high resolution videos).
203
+
204
+ """
205
+ h0 = w0 = 1
206
+ # if height dimension is to be interpolated
207
+ if height > self.max_grid_row_position_embeddings:
208
+ h0 = height / self.max_grid_row_position_embeddings
209
+ # if width dimension is to be interpolated
210
+ if width > self.max_grid_col_position_embeddings:
211
+ w0 = width / self.max_grid_col_position_embeddings
212
+ embedding = embedding.permute(0, 3, 1, 2) # (batch_size, hidden_dim, height, width)
213
+ embedding = nn.functional.interpolate(
214
+ embedding,
215
+ scale_factor=(h0, w0),
216
+ mode="bicubic",
217
+ align_corners=False,
218
+ )
219
+ embedding = embedding.permute(0, 2, 3, 1) # (batch_size, height, width, hidden_dim)
220
+ return embedding
221
+
222
+ def add_2d_positional_embeddings(self, grid, interpolate_pos_encoding: bool = False):
223
+ """
224
+ Args:
225
+ grid: (batch_size, height, width, hidden_dim)
226
+ interpolate_pos_encoding: (`bool`, *optional*, defaults to `False`):
227
+ Whether to interpolate the pre-trained position encodings.
228
+ Returns:
229
+ grid + col_position_embeddings.view(*col_shape): (batch_size, *, height, width, hidden_dim)
230
+ """
231
+ batch_size, height, width, hidden_dim = grid.shape
232
+
233
+ # add row-wise position embeddings
234
+ # (height, )
235
+ row_height = min(self.max_grid_row_position_embeddings, height)
236
+ row_position_ids = torch.arange(row_height, dtype=torch.long, device=grid.device)
237
+ # (height, hidden_dim)
238
+ row_position_embeddings = self.row_position_embeddings(row_position_ids)
239
+ row_shape = (1,) * (len(grid.shape) - 3) + (row_height, 1, hidden_dim)
240
+ # (batch_size, height, 1, hidden_dim)
241
+ row_position_embeddings = row_position_embeddings.view(*row_shape)
242
+
243
+ # add column-wise position embeddings
244
+ row_width = min(self.max_grid_col_position_embeddings, width)
245
+ col_position_ids = torch.arange(row_width, dtype=torch.long, device=grid.device)
246
+ # (width, hidden_dim)
247
+ col_position_embeddings = self.col_position_embeddings(col_position_ids)
248
+ col_shape = (batch_size, 1, row_width, hidden_dim)
249
+ # (batch_size, 1, width, hidden_dim)
250
+ col_position_embeddings = col_position_embeddings.view(*col_shape)
251
+ # (batch_size, height, width, hidden_dim)
252
+ positional_embeddings = row_position_embeddings + col_position_embeddings
253
+
254
+ # This interpolation gets triggered ONLY when the input image dim is larger in any dimenstion than the original position embeddings
255
+ if interpolate_pos_encoding and (
256
+ height > self.max_grid_row_position_embeddings or width > self.max_grid_col_position_embeddings
257
+ ):
258
+ grid = grid + self.interpolate_pos_encoding(positional_embeddings, height, width)
259
+ else:
260
+ grid = grid + positional_embeddings
261
+ return grid
262
+
263
+ def forward(self, grid, interpolate_pos_encoding: bool = False):
264
+ """
265
+ Args:
266
+ grid: Array of shape (batch_size, num_frames, height, width, num_channels).
267
+ It contains processed frames extracted from videos, and is generated by Tvp image preprocessor. Note,
268
+ num_frames can be 1
269
+ interpolate_pos_encoding: (bool, *optional*, defaults to `False`):
270
+ Whether to interpolate the pre-trained position encodings.
271
+
272
+ Returns:
273
+ embeddings: The embedding of grid with size (batch_size, height*width, num_channels)
274
+
275
+ """
276
+ batch_size, num_frames, height, width, num_channels = grid.shape
277
+ # temporal mean pooling, (batch_size, height, width, hidden_size)
278
+ grid = grid.mean(1)
279
+ grid = self.add_2d_positional_embeddings(grid, interpolate_pos_encoding=interpolate_pos_encoding)
280
+ # image token sequence, (batch_size, height*width, num_channels)
281
+ visual_tokens = grid.view(batch_size, -1, num_channels)
282
+ visual_tokens_shape = visual_tokens.shape[:-1]
283
+ device = visual_tokens.device
284
+
285
+ # image token type embeddings.
286
+ token_type_ids = torch.zeros(visual_tokens_shape, dtype=torch.long, device=device)
287
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
288
+
289
+ embeddings = visual_tokens + token_type_embeddings
290
+ embeddings = self.layer_norm(embeddings)
291
+ embeddings = self.dropout(embeddings)
292
+ return embeddings
293
+
294
+
295
+ class TvpTextInputEmbeddings(nn.Module):
296
+ """Construct the embeddings from word, position and token_type embeddings."""
297
+
298
+ def __init__(self, config):
299
+ super().__init__()
300
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
301
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
302
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
303
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
304
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
305
+
306
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
307
+ if input_ids is not None:
308
+ input_shape = input_ids.size()
309
+ else:
310
+ input_shape = inputs_embeds.size()[:-1]
311
+
312
+ seq_length = input_shape[1]
313
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
314
+ if position_ids is None:
315
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=device)
316
+ position_ids = position_ids.unsqueeze(0).expand(input_shape)
317
+ if token_type_ids is None:
318
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
319
+
320
+ if inputs_embeds is None:
321
+ inputs_embeds = self.word_embeddings(input_ids)
322
+ position_embeddings = self.position_embeddings(position_ids)
323
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
324
+
325
+ embeddings = inputs_embeds + position_embeddings + token_type_embeddings
326
+ embeddings = self.layer_norm(embeddings)
327
+ embeddings = self.dropout(embeddings)
328
+ return embeddings
329
+
330
+
331
+ class TvpAttention(nn.Module):
332
+ def __init__(self, config):
333
+ super().__init__()
334
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
335
+ raise ValueError(
336
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}"
337
+ )
338
+
339
+ self.num_attention_heads = config.num_attention_heads
340
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
341
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
342
+
343
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
344
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
345
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
346
+ self.attn_dropout = nn.Dropout(config.attention_probs_dropout_prob)
347
+
348
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
349
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
350
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
351
+ self.pruned_heads = set()
352
+
353
+ def prune_heads(self, heads):
354
+ if len(heads) == 0:
355
+ return
356
+ mask = torch.ones(self.num_attention_heads, self.attention_head_size)
357
+ heads = set(heads) - self.pruned_heads # Convert to set and remove already pruned heads
358
+ for head in heads:
359
+ # Compute how many pruned heads are before the head and move the index accordingly
360
+ head = head - sum(1 if h < head else 0 for h in self.pruned_heads)
361
+ mask[head] = 0
362
+ mask = mask.view(-1).contiguous().eq(1)
363
+ index = torch.arange(len(mask))[mask].long()
364
+
365
+ # Prune linear layers
366
+ self.query = prune_linear_layer(self.query, index)
367
+ self.key = prune_linear_layer(self.key, index)
368
+ self.value = prune_linear_layer(self.value, index)
369
+ self.dense = prune_linear_layer(self.dense, index, dim=1)
370
+
371
+ # Update hyper params and store pruned heads
372
+ self.num_attention_heads = self.num_attention_heads - len(heads)
373
+ self.all_head_size = self.attention_head_size * self.num_attention_heads
374
+ self.pruned_heads = self.pruned_heads.union(heads)
375
+
376
+ def _reshape(self, tensor: torch.Tensor, sequence_length: int, batch_size: int):
377
+ return (
378
+ tensor.view(batch_size, sequence_length, self.num_attention_heads, self.attention_head_size)
379
+ .transpose(1, 2)
380
+ .contiguous()
381
+ )
382
+
383
+ def forward(
384
+ self,
385
+ hidden_states,
386
+ attention_mask=None,
387
+ head_mask=None,
388
+ output_attentions: Optional[bool] = None,
389
+ ):
390
+ batch_size, sequence_length = hidden_states.shape[:2]
391
+ mixed_query_layer = self.query(hidden_states)
392
+
393
+ mixed_key_layer = self.key(hidden_states)
394
+ mixed_value_layer = self.value(hidden_states)
395
+
396
+ query_layer = self._reshape(mixed_query_layer, sequence_length, batch_size)
397
+ key_layer = self._reshape(mixed_key_layer, sequence_length, batch_size)
398
+ value_layer = self._reshape(mixed_value_layer, sequence_length, batch_size)
399
+
400
+ # Take the dot product between "query" and "key" to get the raw attention scores.
401
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
402
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
403
+ if attention_mask is not None:
404
+ attention_scores = attention_scores + attention_mask
405
+
406
+ # Normalize the attention scores to probabilities.
407
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
408
+
409
+ # This is actually dropping out entire tokens to attend to, which might
410
+ # seem a bit unusual, but is taken from the original Transformer paper.
411
+ attention_probs = self.attn_dropout(attention_probs)
412
+
413
+ # Mask heads if we want to
414
+ if head_mask is not None:
415
+ attention_probs = attention_probs * head_mask
416
+
417
+ attn_output = torch.matmul(attention_probs, value_layer)
418
+ attn_output = attn_output.transpose(1, 2).contiguous()
419
+ attn_output = attn_output.reshape(batch_size, sequence_length, self.all_head_size)
420
+
421
+ attn_output = self.dense(attn_output)
422
+ attn_output = self.dropout(attn_output)
423
+ attn_output = self.layer_norm(attn_output + hidden_states)
424
+ # add attentions if we output them
425
+ outputs = (attn_output, attention_probs) if output_attentions else (attn_output,)
426
+ return outputs
427
+
428
+
429
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Tvp
430
+ class TvpIntermediate(nn.Module):
431
+ def __init__(self, config):
432
+ super().__init__()
433
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
434
+ if isinstance(config.hidden_act, str):
435
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
436
+ else:
437
+ self.intermediate_act_fn = config.hidden_act
438
+
439
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
440
+ hidden_states = self.dense(hidden_states)
441
+ hidden_states = self.intermediate_act_fn(hidden_states)
442
+ return hidden_states
443
+
444
+
445
+ class TvpOutputLayer(nn.Module):
446
+ def __init__(self, config):
447
+ super().__init__()
448
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
449
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
450
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
451
+
452
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
453
+ hidden_states = self.dense(hidden_states)
454
+ hidden_states = self.dropout(hidden_states)
455
+ hidden_states = self.layer_norm(hidden_states + input_tensor)
456
+ return hidden_states
457
+
458
+
459
+ class TvpEncodeLayer(nn.Module):
460
+ def __init__(self, config):
461
+ super().__init__()
462
+ self.attention = TvpAttention(config)
463
+ self.intermediate = TvpIntermediate(config)
464
+ self.output = TvpOutputLayer(config)
465
+
466
+ def forward(
467
+ self,
468
+ hidden_states,
469
+ attention_mask=None,
470
+ head_mask=None,
471
+ output_attentions: Optional[bool] = None,
472
+ ):
473
+ self_attention_outputs = self.attention(
474
+ hidden_states,
475
+ attention_mask,
476
+ head_mask,
477
+ output_attentions=output_attentions,
478
+ )
479
+ attention_output = self_attention_outputs[0]
480
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
481
+ intermediate_output = self.intermediate(attention_output)
482
+ layer_output = self.output(intermediate_output, attention_output)
483
+ outputs = (layer_output,) + outputs
484
+ return outputs
485
+
486
+
487
+ class TvpEncoder(nn.Module):
488
+ def __init__(self, config):
489
+ super().__init__()
490
+ self.config = config
491
+ self.layer = nn.ModuleList([TvpEncodeLayer(config) for _ in range(config.num_hidden_layers)])
492
+ self.gradient_checkpointing = False
493
+
494
+ def forward(
495
+ self,
496
+ hidden_states,
497
+ attention_mask=None,
498
+ head_mask: Optional[torch.FloatTensor] = None,
499
+ output_attentions: Optional[bool] = None,
500
+ output_hidden_states: Optional[bool] = None,
501
+ return_dict: Optional[bool] = None,
502
+ ):
503
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
504
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
505
+ output_hidden_states = (
506
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
507
+ )
508
+ all_hidden_states = ()
509
+ all_attentions = ()
510
+
511
+ for i, layer_module in enumerate(self.layer):
512
+ if output_hidden_states:
513
+ all_hidden_states = all_hidden_states + (hidden_states,)
514
+
515
+ if self.gradient_checkpointing and self.training:
516
+ layer_outputs = self._gradient_checkpointing_func(
517
+ layer_module.__call__,
518
+ hidden_states,
519
+ attention_mask,
520
+ (head_mask[i] if head_mask is not None else None),
521
+ output_attentions,
522
+ )
523
+ else:
524
+ layer_outputs = layer_module(hidden_states, attention_mask, head_mask[i], output_attentions)
525
+
526
+ hidden_states = layer_outputs[0]
527
+ if output_attentions:
528
+ all_attentions = all_attentions + (layer_outputs[1],)
529
+
530
+ # Add last layer
531
+ if output_hidden_states:
532
+ all_hidden_states = all_hidden_states + (hidden_states,)
533
+
534
+ if not return_dict:
535
+ outputs = (hidden_states,)
536
+ if output_hidden_states:
537
+ outputs = outputs + (all_hidden_states,)
538
+ if output_attentions:
539
+ outputs = outputs + (all_attentions,)
540
+ return outputs # last-layer hidden state, (all hidden states), (all attentions)
541
+
542
+ return BaseModelOutput(
543
+ last_hidden_state=hidden_states,
544
+ hidden_states=all_hidden_states if output_hidden_states else None,
545
+ attentions=all_attentions if output_attentions else None,
546
+ )
547
+
548
+
549
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->Tvp
550
+ class TvpPooler(nn.Module):
551
+ def __init__(self, config):
552
+ super().__init__()
553
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
554
+ self.activation = nn.Tanh()
555
+
556
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
557
+ # We "pool" the model by simply taking the hidden state corresponding
558
+ # to the first token.
559
+ first_token_tensor = hidden_states[:, 0]
560
+ pooled_output = self.dense(first_token_tensor)
561
+ pooled_output = self.activation(pooled_output)
562
+ return pooled_output
563
+
564
+
565
+ class TvpPreTrainedModel(PreTrainedModel):
566
+ """An abstract class to handle weights initialization and
567
+ a simple interface for downloading and loading pretrained models.
568
+ """
569
+
570
+ config_class = TvpConfig
571
+ base_model_prefix = "model"
572
+ supports_gradient_checkpointing = True
573
+
574
+ def _init_weights(self, module):
575
+ """Initialize the weights"""
576
+ if isinstance(module, (nn.Linear, nn.Embedding)):
577
+ # Slightly different from the TF version which uses truncated_normal for initialization
578
+ # cf https://github.com/pytorch/pytorch/pull/5617
579
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
580
+ elif isinstance(module, nn.LayerNorm):
581
+ module.bias.data.zero_()
582
+ module.weight.data.fill_(1.0)
583
+
584
+ if isinstance(module, nn.Linear) and module.bias is not None:
585
+ module.bias.data.zero_()
586
+
587
+ if isinstance(module, nn.Conv2d):
588
+ nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
589
+ if module.bias is not None:
590
+ nn.init.constant_(module.bias, 0)
591
+
592
+
593
+ TVP_START_DOCSTRING = r"""
594
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
595
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
596
+ behavior.
597
+
598
+ Parameters:
599
+ config ([`TvpConfig`]): Model configuration class with all the parameters of the model.
600
+ Initializing with a config file does not load the weights associated with the model, only the
601
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
602
+ """
603
+
604
+ TVP_INPUTS_DOCSTRING = r"""
605
+ Args:
606
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
607
+ Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
608
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
609
+ IDs?](../glossary#input-ids)
610
+
611
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
612
+ Pixel values. Pixel values can be obtained using [`TvpImageProcessor`]. See [`TvpImageProcessor.__call__`]
613
+ for details.
614
+
615
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
616
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
617
+ - 1 for tokens that are **not masked**,
618
+ - 0 for tokens that are **masked**.
619
+ [What are attention masks?](../glossary#attention-mask)
620
+
621
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
622
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
623
+ - 1 indicates the head is **not masked**,
624
+ - 0 indicates the head is **masked**.
625
+
626
+ output_attentions (`bool`, *optional*):
627
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
628
+ tensors for more detail.
629
+
630
+ output_hidden_states (`bool`, *optional*):
631
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
632
+ more detail.
633
+
634
+ return_dict (`bool`, *optional*):
635
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
636
+
637
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
638
+ Whether to interpolate the pre-trained image pad prompter encodings and positional encodings.
639
+ """
640
+
641
+
642
+ class TvpFrameDownPadPrompter(nn.Module):
643
+ """
644
+ Pad frames extracted from videos only at the bottom.
645
+ """
646
+
647
+ def __init__(self, config):
648
+ if config.visual_prompter_apply not in ("add", "replace", "remove"):
649
+ raise ValueError("`visual_prompter_apply` must be in (add, replace, remove)")
650
+
651
+ super().__init__()
652
+ self.visual_prompt_size = config.visual_prompt_size
653
+ self.frame_num = config.frame_num
654
+ self.max_img_size = config.max_img_size
655
+ self.visual_prompter_apply = config.visual_prompter_apply
656
+
657
+ self.pad_down = nn.Parameter(
658
+ torch.randn([1, config.frame_num, 3, config.visual_prompt_size, config.max_img_size])
659
+ )
660
+
661
+ def forward(self, pixel_values):
662
+ if self.visual_prompter_apply != "add":
663
+ visual_prompt_mask = torch.ones(
664
+ [self.max_img_size, self.max_img_size], dtype=pixel_values.dtype, device=pixel_values.device
665
+ )
666
+ visual_prompt_mask[self.max_img_size - self.visual_prompt_size : self.max_img_size, :] = 0.0
667
+ pixel_values *= visual_prompt_mask
668
+ if self.visual_prompter_apply != "remove":
669
+ prompt = torch.zeros(
670
+ [pixel_values.shape[0], pixel_values.shape[1], 3, self.max_img_size, self.max_img_size],
671
+ device=pixel_values.device,
672
+ )
673
+ start_point = self.max_img_size - self.visual_prompt_size
674
+ prompt[:, :, :, start_point : self.max_img_size, :] = self.pad_down
675
+ pixel_values += prompt.to(pixel_values.dtype)
676
+ return pixel_values
677
+
678
+
679
+ class TvpFramePadPrompter(nn.Module):
680
+ """
681
+ Pad frames extracted from videos in the surroundings.
682
+ """
683
+
684
+ def __init__(self, config):
685
+ if config.visual_prompter_apply not in ("add", "replace", "remove"):
686
+ raise ValueError("`visual_prompter_apply` must be in (add, replace, remove)")
687
+
688
+ super().__init__()
689
+ self.num_frames = config.num_frames
690
+ self.max_img_size = config.max_img_size
691
+ self.visual_prompter_apply = config.visual_prompter_apply
692
+ self.base_size = config.max_img_size - config.visual_prompt_size * 2
693
+ self.pad_up = nn.Parameter(
694
+ torch.randn([1, config.num_frames, 3, config.visual_prompt_size, config.max_img_size])
695
+ )
696
+ self.pad_down = nn.Parameter(
697
+ torch.randn([1, config.num_frames, 3, config.visual_prompt_size, config.max_img_size])
698
+ )
699
+ self.pad_left = nn.Parameter(
700
+ torch.randn(
701
+ [
702
+ 1,
703
+ config.num_frames,
704
+ 3,
705
+ config.max_img_size - config.visual_prompt_size * 2,
706
+ config.visual_prompt_size,
707
+ ]
708
+ )
709
+ )
710
+ self.pad_right = nn.Parameter(
711
+ torch.randn(
712
+ [
713
+ 1,
714
+ config.num_frames,
715
+ 3,
716
+ config.max_img_size - config.visual_prompt_size * 2,
717
+ config.visual_prompt_size,
718
+ ]
719
+ )
720
+ )
721
+
722
+ def interpolate_pad_encoding(self, prompt: torch.Tensor, height: int, width: int) -> torch.Tensor:
723
+ """
724
+ This method allows to interpolate the pre-trained pad weights, to be able to use the model on collection of high
725
+ resolution images (high resolution videos).
726
+
727
+ """
728
+
729
+ # creates scale factor from height and width of original image wrt to the config.max_img_size
730
+ h0, w0 = height / self.max_img_size, width / self.max_img_size
731
+
732
+ batch, num_frames, channels, prompt_height, prompt_width = prompt.shape
733
+
734
+ # reshaping the batch and num_frames dimension into a single one (i.e (b,frames,c,h,w)-->(b*frames,c,h,w)), to apply bicubic interpolation
735
+ prompt = prompt.reshape(batch * num_frames, channels, prompt_height, prompt_width)
736
+ prompt = nn.functional.interpolate(
737
+ prompt,
738
+ scale_factor=(h0, w0),
739
+ mode="bicubic",
740
+ align_corners=False,
741
+ )
742
+ # reversing back to (batch,frames,channels,height,width), where height and width is the new interpolated height and width
743
+ prompt = prompt.reshape(batch, num_frames, channels, height, width)
744
+ return prompt
745
+
746
+ def forward(self, pixel_values, interpolate_pad_encoding: bool = False):
747
+ height, width = (
748
+ (pixel_values.shape[-2], pixel_values.shape[-1])
749
+ if interpolate_pad_encoding
750
+ else (self.max_img_size, self.max_img_size)
751
+ )
752
+ if self.visual_prompter_apply not in ("add", "remove", "replace"):
753
+ raise ValueError(f"Invalid visual_prompter_apply value {self.visual_prompter_apply}")
754
+ if self.visual_prompter_apply in ("replace", "remove"):
755
+ visual_prompt_mask = torch.ones([height, width], dtype=pixel_values.dtype, device=pixel_values.device)
756
+ pixel_values *= visual_prompt_mask
757
+ if self.visual_prompter_apply in ("replace", "add"):
758
+ base = torch.zeros(1, self.num_frames, 3, self.base_size, self.base_size, device=pixel_values.device)
759
+
760
+ prompt = torch.cat([self.pad_left, base, self.pad_right], dim=4)
761
+ prompt = torch.cat([self.pad_up, prompt, self.pad_down], dim=3)
762
+ prompt = torch.cat(pixel_values.size(0) * [prompt])
763
+ if interpolate_pad_encoding:
764
+ prompt = self.interpolate_pad_encoding(prompt, height, width)
765
+ pixel_values = pixel_values + prompt.to(pixel_values.dtype)
766
+ return pixel_values
767
+
768
+
769
+ TVP_PROMPTER_CLASSES_MAPPING = {
770
+ "framedownpad": TvpFrameDownPadPrompter,
771
+ "framepad": TvpFramePadPrompter,
772
+ }
773
+
774
+
775
+ @add_start_docstrings(
776
+ "The bare Tvp Model transformer outputting BaseModelOutputWithPooling object without any specific head on" " top.",
777
+ TVP_START_DOCSTRING,
778
+ )
779
+ class TvpModel(TvpPreTrainedModel):
780
+ def __init__(self, config):
781
+ super().__init__(config)
782
+ self.config = config
783
+ self.vision_model = TvpVisionModel(config)
784
+ self.embeddings = TvpTextInputEmbeddings(config)
785
+ self.visual_embeddings = TvpVisualInputEmbedding(config)
786
+ self.encoder = TvpEncoder(config)
787
+ self.pooler = TvpPooler(config)
788
+ self.text_prompt = nn.Parameter(torch.randn([1, 10, config.hidden_size]))
789
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
790
+ if config.visual_prompter_type not in TVP_PROMPTER_CLASSES_MAPPING:
791
+ raise ValueError("`visual_prompter_type` must be in (framedownpad, framepad)")
792
+ self.visual_prompter = TVP_PROMPTER_CLASSES_MAPPING[config.visual_prompter_type](config)
793
+
794
+ self.post_init()
795
+
796
+ def get_input_embeddings(self):
797
+ return self.embeddings.word_embeddings
798
+
799
+ def set_input_embeddings(self, value):
800
+ self.embeddings.word_embeddings = value
801
+
802
+ def _prune_heads(self, heads_to_prune):
803
+ """Prunes heads of the model.
804
+ heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel
805
+ """
806
+ for layer, heads in heads_to_prune.items():
807
+ self.encoder.layer[layer].attention.prune_heads(heads)
808
+
809
+ @add_start_docstrings_to_model_forward(TVP_INPUTS_DOCSTRING)
810
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=TvpConfig)
811
+ def forward(
812
+ self,
813
+ input_ids: Optional[torch.LongTensor] = None,
814
+ pixel_values: Optional[torch.FloatTensor] = None,
815
+ attention_mask: Optional[torch.LongTensor] = None,
816
+ head_mask: Optional[torch.FloatTensor] = None,
817
+ output_attentions: Optional[bool] = None,
818
+ output_hidden_states: Optional[bool] = None,
819
+ return_dict: Optional[bool] = None,
820
+ interpolate_pos_encoding: bool = False,
821
+ ):
822
+ r"""
823
+ Returns:
824
+
825
+ Examples:
826
+ ```python
827
+ >>> import torch
828
+ >>> from transformers import AutoConfig, AutoTokenizer, TvpModel
829
+
830
+ >>> model = TvpModel.from_pretrained("Jiqing/tiny-random-tvp")
831
+
832
+ >>> tokenizer = AutoTokenizer.from_pretrained("Jiqing/tiny-random-tvp")
833
+
834
+ >>> pixel_values = torch.rand(1, 1, 3, 448, 448)
835
+ >>> text_inputs = tokenizer("This is an example input", return_tensors="pt")
836
+ >>> output = model(text_inputs.input_ids, pixel_values, text_inputs.attention_mask)
837
+ ```"""
838
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
839
+ # Add visual prompt, it compensates for the spatiotemporal information loss in 2D visual features.
840
+ pixel_values = self.vision_model(
841
+ self.visual_prompter(pixel_values, interpolate_pad_encoding=interpolate_pos_encoding)
842
+ )
843
+ # (batch_size, sequence_length, hidden_size)
844
+ text_embedding_output = self.embeddings(input_ids=input_ids)
845
+ # (batch_size, visual_sequence_length, hidden_size)
846
+ visual_embedding_output = self.visual_embeddings(
847
+ pixel_values, interpolate_pos_encoding=interpolate_pos_encoding
848
+ )
849
+
850
+ if attention_mask is not None:
851
+ # (batch_size, visual_sequence_length)
852
+ visual_attention_mask = attention_mask.new_ones(visual_embedding_output.shape[:2])
853
+ pt_mask = torch.ones(attention_mask.shape[0], 10).to(
854
+ device=attention_mask.device, dtype=attention_mask.dtype
855
+ )
856
+ attention_mask = torch.cat([pt_mask, attention_mask, visual_attention_mask], dim=-1)
857
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
858
+ # ourselves in which case we just need to make it broadcastable to all heads.
859
+ attention_mask = self.get_extended_attention_mask(attention_mask, input_ids.size()).to(input_ids.device)
860
+ text_prompt = self.text_prompt.expand(text_embedding_output.shape[0], -1, -1)
861
+ # (batch_size, sequence_length + visual_sequence_length, hidden_size)
862
+ embedding_output = torch.cat([text_prompt, text_embedding_output, visual_embedding_output], dim=1)
863
+
864
+ encoder_outputs = self.encoder(
865
+ embedding_output,
866
+ attention_mask=attention_mask,
867
+ head_mask=self.get_head_mask(head_mask, self.config.num_hidden_layers),
868
+ output_attentions=output_attentions,
869
+ output_hidden_states=output_hidden_states,
870
+ return_dict=return_dict,
871
+ )
872
+ last_hidden_state = encoder_outputs.last_hidden_state if return_dict else encoder_outputs[0]
873
+ pooled_output = self.pooler(last_hidden_state)
874
+ last_hidden_state = self.dropout(last_hidden_state)
875
+ pooled_output = self.dropout(pooled_output)
876
+ if not return_dict:
877
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
878
+ return BaseModelOutputWithPooling(
879
+ last_hidden_state=last_hidden_state,
880
+ pooler_output=pooled_output,
881
+ hidden_states=encoder_outputs.hidden_states,
882
+ attentions=encoder_outputs.attentions,
883
+ )
884
+
885
+
886
+ class TvpVideoGroundingHead(nn.Module):
887
+ def __init__(self, config):
888
+ super().__init__()
889
+ self.layer_0 = nn.Linear(config.hidden_size, config.hidden_size * 2)
890
+ self.layer_1 = nn.Linear(config.hidden_size * 2, 2)
891
+ self.activation_0 = nn.ReLU()
892
+ self.activation_1 = nn.Sigmoid()
893
+
894
+ def forward(self, pooler_output):
895
+ logits = self.activation_0(self.layer_0(pooler_output))
896
+ logits = self.activation_1(self.layer_1(logits))
897
+ return logits
898
+
899
+
900
+ @add_start_docstrings(
901
+ """
902
+ Tvp Model with a video grounding head on top computing IoU, distance, and duration loss.
903
+ """,
904
+ TVP_START_DOCSTRING,
905
+ )
906
+ class TvpForVideoGrounding(TvpPreTrainedModel):
907
+ def __init__(self, config):
908
+ super().__init__(config)
909
+ self.config = config
910
+ self.model = TvpModel(config)
911
+ self.video_grounding_head = TvpVideoGroundingHead(config)
912
+
913
+ self.post_init()
914
+
915
+ @add_start_docstrings_to_model_forward(TVP_INPUTS_DOCSTRING)
916
+ @replace_return_docstrings(output_type=TvpVideoGroundingOutput, config_class=TvpConfig)
917
+ def forward(
918
+ self,
919
+ input_ids: Optional[torch.LongTensor] = None,
920
+ pixel_values: Optional[torch.FloatTensor] = None,
921
+ attention_mask: Optional[torch.LongTensor] = None,
922
+ labels: Tuple[torch.Tensor] = None,
923
+ head_mask: Optional[torch.FloatTensor] = None,
924
+ output_attentions: Optional[bool] = None,
925
+ output_hidden_states: Optional[bool] = None,
926
+ return_dict: Optional[bool] = None,
927
+ interpolate_pos_encoding: bool = False,
928
+ ):
929
+ r"""
930
+ labels (`torch.FloatTensor` of shape `(batch_size, 3)`, *optional*):
931
+ The labels contains duration, start time, and end time of the video corresponding to the text.
932
+ Returns:
933
+
934
+ Examples:
935
+ ```python
936
+ >>> import torch
937
+ >>> from transformers import AutoConfig, AutoTokenizer, TvpForVideoGrounding
938
+
939
+ >>> model = TvpForVideoGrounding.from_pretrained("Jiqing/tiny-random-tvp")
940
+
941
+ >>> tokenizer = AutoTokenizer.from_pretrained("Jiqing/tiny-random-tvp")
942
+
943
+ >>> pixel_values = torch.rand(1, 1, 3, 448, 448)
944
+ >>> text_inputs = tokenizer("This is an example input", return_tensors="pt")
945
+ >>> output = model(text_inputs.input_ids, pixel_values, text_inputs.attention_mask)
946
+ ```"""
947
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
948
+ outputs = self.model(
949
+ input_ids,
950
+ pixel_values,
951
+ attention_mask,
952
+ head_mask=head_mask,
953
+ output_attentions=output_attentions,
954
+ output_hidden_states=output_hidden_states,
955
+ return_dict=return_dict,
956
+ interpolate_pos_encoding=interpolate_pos_encoding,
957
+ )
958
+ pooler_output = outputs[1]
959
+ logits = self.video_grounding_head(pooler_output)
960
+
961
+ loss = None
962
+ if labels is not None:
963
+ criterion = TvpLoss(["iou", "distance", "duration"])
964
+ criterion.to(self.device)
965
+ loss_dict = criterion(logits, labels)
966
+ loss = (
967
+ loss_dict["iou"]
968
+ + self.config.distance_loss_weight * loss_dict["distance"]
969
+ + self.config.duration_loss_weight * loss_dict["duration"]
970
+ )
971
+ if not return_dict:
972
+ outputs = (logits,) + outputs[2:]
973
+ if loss is not None:
974
+ outputs = (loss,) + outputs
975
+ return outputs
976
+
977
+ return TvpVideoGroundingOutput(
978
+ loss=loss,
979
+ logits=logits,
980
+ hidden_states=outputs.hidden_states,
981
+ attentions=outputs.attentions,
982
+ )
983
+
984
+
985
+ __all__ = ["TvpModel", "TvpPreTrainedModel", "TvpForVideoGrounding"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/tvp/processing_tvp.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Intel AIA Team Authors, and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License=, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing=, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS=,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND=, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for TVP.
17
+ """
18
+
19
+ from ...processing_utils import ProcessorMixin
20
+ from ...tokenization_utils_base import BatchEncoding
21
+
22
+
23
+ class TvpProcessor(ProcessorMixin):
24
+ r"""
25
+ Constructs an TVP processor which wraps a TVP image processor and a Bert tokenizer into a single processor.
26
+
27
+ [`TvpProcessor`] offers all the functionalities of [`TvpImageProcessor`] and [`BertTokenizerFast`]. See the
28
+ [`~TvpProcessor.__call__`] and [`~TvpProcessor.decode`] for more information.
29
+
30
+ Args:
31
+ image_processor ([`TvpImageProcessor`], *optional*):
32
+ The image processor is a required input.
33
+ tokenizer ([`BertTokenizerFast`], *optional*):
34
+ The tokenizer is a required input.
35
+ """
36
+
37
+ attributes = ["image_processor", "tokenizer"]
38
+ image_processor_class = "TvpImageProcessor"
39
+ tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
40
+
41
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
42
+ if image_processor is None:
43
+ raise ValueError("You need to specify an `image_processor`.")
44
+ if tokenizer is None:
45
+ raise ValueError("You need to specify a `tokenizer`.")
46
+
47
+ super().__init__(image_processor, tokenizer)
48
+
49
+ def __call__(self, text=None, videos=None, return_tensors=None, **kwargs):
50
+ """
51
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
52
+ and `kwargs` arguments to BertTokenizerFast's [`~BertTokenizerFast.__call__`] if `text` is not `None` to encode
53
+ the text. To prepare the image(s), this method forwards the `videos` and `kwargs` arguments to
54
+ TvpImageProcessor's [`~TvpImageProcessor.__call__`] if `videos` is not `None`. Please refer to the doctsring of
55
+ the above two methods for more information.
56
+
57
+ Args:
58
+ text (`str`, `List[str]`, `List[List[str]]`):
59
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
60
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
61
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
62
+ videos (`List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, `List[List[PIL.Image.Image]]`, `List[List[np.ndarrray]]`,:
63
+ `List[List[torch.Tensor]]`): The video or batch of videos to be prepared. Each video should be a list
64
+ of frames, which can be either PIL images or NumPy arrays. In case of NumPy arrays/PyTorch tensors,
65
+ each frame should be of shape (H, W, C), where H and W are frame height and width, and C is a number of
66
+ channels.
67
+
68
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
69
+ If set, will return tensors of a particular framework. Acceptable values are:
70
+
71
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
72
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
73
+ - `'np'`: Return NumPy `np.ndarray` objects.
74
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
75
+
76
+ Returns:
77
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
78
+
79
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
80
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
81
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
82
+ `None`).
83
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `videos` is not `None`.
84
+ """
85
+
86
+ max_text_length = kwargs.pop("max_text_length", None)
87
+
88
+ if text is None and videos is None:
89
+ raise ValueError("You have to specify either text or videos. Both cannot be none.")
90
+
91
+ encoding = {}
92
+ if text is not None:
93
+ textual_input = self.tokenizer.batch_encode_plus(
94
+ text,
95
+ truncation=True,
96
+ padding="max_length",
97
+ max_length=max_text_length,
98
+ pad_to_max_length=True,
99
+ return_tensors=return_tensors,
100
+ return_token_type_ids=False,
101
+ **kwargs,
102
+ )
103
+ encoding.update(textual_input)
104
+
105
+ if videos is not None:
106
+ image_features = self.image_processor(videos, return_tensors=return_tensors, **kwargs)
107
+ encoding.update(image_features)
108
+
109
+ return BatchEncoding(data=encoding, tensor_type=return_tensors)
110
+
111
+ def batch_decode(self, *args, **kwargs):
112
+ """
113
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
114
+ refer to the docstring of this method for more information.
115
+ """
116
+ return self.tokenizer.batch_decode(*args, **kwargs)
117
+
118
+ def decode(self, *args, **kwargs):
119
+ """
120
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
121
+ the docstring of this method for more information.
122
+ """
123
+ return self.tokenizer.decode(*args, **kwargs)
124
+
125
+ def post_process_video_grounding(self, logits, video_durations):
126
+ """
127
+ Compute the time of the video.
128
+
129
+ Args:
130
+ logits (`torch.Tensor`):
131
+ The logits output of TvpForVideoGrounding.
132
+ video_durations (`float`):
133
+ The video's duration.
134
+
135
+ Returns:
136
+ start (`float`):
137
+ The start time of the video.
138
+ end (`float`):
139
+ The end time of the video.
140
+ """
141
+ start, end = (
142
+ round(logits.tolist()[0][0] * video_durations, 1),
143
+ round(logits.tolist()[0][1] * video_durations, 1),
144
+ )
145
+
146
+ return start, end
147
+
148
+ @property
149
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
150
+ def model_input_names(self):
151
+ tokenizer_input_names = self.tokenizer.model_input_names
152
+ image_processor_input_names = self.image_processor.model_input_names
153
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
154
+
155
+
156
+ __all__ = ["TvpProcessor"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_udop import *
22
+ from .modeling_udop import *
23
+ from .processing_udop import *
24
+ from .tokenization_udop import *
25
+ from .tokenization_udop_fast import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/configuration_udop.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """UDOP model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class UdopConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`UdopForConditionalGeneration`]. It is used to
27
+ instantiate a UDOP model according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the UDOP
29
+ [microsoft/udop-large](https://huggingface.co/microsoft/udop-large) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Arguments:
35
+ vocab_size (`int`, *optional*, defaults to 33201):
36
+ Vocabulary size of the UDOP model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`UdopForConditionalGeneration`].
38
+ d_model (`int`, *optional*, defaults to 1024):
39
+ Size of the encoder layers and the pooler layer.
40
+ d_kv (`int`, *optional*, defaults to 64):
41
+ Size of the key, query, value projections per attention head. The `inner_dim` of the projection layer will
42
+ be defined as `num_heads * d_kv`.
43
+ d_ff (`int`, *optional*, defaults to 4096):
44
+ Size of the intermediate feed forward layer in each `UdopBlock`.
45
+ num_layers (`int`, *optional*, defaults to 24):
46
+ Number of hidden layers in the Transformer encoder and decoder.
47
+ num_decoder_layers (`int`, *optional*):
48
+ Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
49
+ num_heads (`int`, *optional*, defaults to 16):
50
+ Number of attention heads for each attention layer in the Transformer encoder and decoder.
51
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
52
+ The number of buckets to use for each attention layer.
53
+ relative_attention_max_distance (`int`, *optional*, defaults to 128):
54
+ The maximum distance of the longer sequences for the bucket separation.
55
+ relative_bias_args (`List[dict]`, *optional*, defaults to `[{'type': '1d'}, {'type': 'horizontal'}, {'type': 'vertical'}]`):
56
+ A list of dictionaries containing the arguments for the relative bias layers.
57
+ dropout_rate (`float`, *optional*, defaults to 0.1):
58
+ The ratio for all dropout layers.
59
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-06):
60
+ The epsilon used by the layer normalization layers.
61
+ initializer_factor (`float`, *optional*, defaults to 1.0):
62
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
63
+ testing).
64
+ feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
65
+ Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. Udopv1.1 uses the
66
+ `"gated-gelu"` feed forward projection. Original Udop uses `"relu"`.
67
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
68
+ Whether the model should behave as an encoder/decoder or not.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models).
71
+ pad_token_id (`int`, *optional*, defaults to 0):
72
+ The id of the padding token in the vocabulary.
73
+ eos_token_id (`int`, *optional*, defaults to 1):
74
+ The id of the end-of-sequence token in the vocabulary.
75
+ max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
76
+ The maximum absolute position embeddings for relative position encoding.
77
+ image_size (`int`, *optional*, defaults to 224):
78
+ The size of the input images.
79
+ patch_size (`int`, *optional*, defaults to 16):
80
+ The patch size used by the vision encoder.
81
+ num_channels (`int`, *optional*, defaults to 3):
82
+ The number of channels in the input images.
83
+ """
84
+
85
+ model_type = "udop"
86
+ keys_to_ignore_at_inference = ["past_key_values"]
87
+ attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
88
+
89
+ def __init__(
90
+ self,
91
+ vocab_size=33201,
92
+ d_model=1024,
93
+ d_kv=64,
94
+ d_ff=4096,
95
+ num_layers=24,
96
+ num_decoder_layers=None,
97
+ num_heads=16,
98
+ relative_attention_num_buckets=32,
99
+ relative_attention_max_distance=128,
100
+ relative_bias_args=[{"type": "1d"}, {"type": "horizontal"}, {"type": "vertical"}],
101
+ dropout_rate=0.1,
102
+ layer_norm_epsilon=1e-6,
103
+ initializer_factor=1.0,
104
+ feed_forward_proj="relu",
105
+ is_encoder_decoder=True,
106
+ use_cache=True,
107
+ pad_token_id=0,
108
+ eos_token_id=1,
109
+ max_2d_position_embeddings=1024,
110
+ image_size=224,
111
+ patch_size=16,
112
+ num_channels=3,
113
+ **kwargs,
114
+ ):
115
+ self.vocab_size = vocab_size
116
+ self.d_model = d_model
117
+ self.d_kv = d_kv
118
+ self.d_ff = d_ff
119
+ self.num_layers = num_layers
120
+ self.num_decoder_layers = (
121
+ num_decoder_layers if num_decoder_layers is not None else self.num_layers
122
+ ) # default = symmetry
123
+ self.num_heads = num_heads
124
+ self.relative_attention_num_buckets = relative_attention_num_buckets
125
+ self.relative_attention_max_distance = relative_attention_max_distance
126
+ self.dropout_rate = dropout_rate
127
+ self.layer_norm_epsilon = layer_norm_epsilon
128
+ self.initializer_factor = initializer_factor
129
+ self.feed_forward_proj = feed_forward_proj
130
+ self.use_cache = use_cache
131
+
132
+ # UDOP attributes
133
+ self.max_2d_position_embeddings = max_2d_position_embeddings
134
+ self.image_size = image_size
135
+ self.patch_size = patch_size
136
+ self.num_channels = num_channels
137
+ if not isinstance(relative_bias_args, list):
138
+ raise TypeError("`relative_bias_args` should be a list of dictionaries.")
139
+ self.relative_bias_args = relative_bias_args
140
+
141
+ act_info = self.feed_forward_proj.split("-")
142
+ self.dense_act_fn = act_info[-1]
143
+ self.is_gated_act = act_info[0] == "gated"
144
+
145
+ if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
146
+ raise ValueError(
147
+ f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
148
+ "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
149
+ "'gated-gelu' or 'relu'"
150
+ )
151
+
152
+ super().__init__(
153
+ pad_token_id=pad_token_id,
154
+ eos_token_id=eos_token_id,
155
+ is_encoder_decoder=is_encoder_decoder,
156
+ **kwargs,
157
+ )
158
+
159
+
160
+ __all__ = ["UdopConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/convert_udop_to_hf.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert UDOP checkpoints from the original repository. URL: https://github.com/microsoft/i-Code/tree/main/i-Code-Doc"""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+ from huggingface_hub import hf_hub_download
21
+ from PIL import Image
22
+ from torchvision import transforms as T
23
+
24
+ from transformers import (
25
+ LayoutLMv3ImageProcessor,
26
+ UdopConfig,
27
+ UdopForConditionalGeneration,
28
+ UdopProcessor,
29
+ UdopTokenizer,
30
+ )
31
+ from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
32
+
33
+
34
+ def original_transform(image, image_size=224):
35
+ transform = T.Compose(
36
+ [
37
+ T.Resize([image_size, image_size]),
38
+ T.ToTensor(),
39
+ T.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD),
40
+ ]
41
+ )
42
+
43
+ image = transform(image)
44
+ return image
45
+
46
+
47
+ def get_image():
48
+ filepath = hf_hub_download(
49
+ repo_id="hf-internal-testing/fixtures_docvqa", filename="document_2.png", repo_type="dataset"
50
+ )
51
+ image = Image.open(filepath).convert("RGB")
52
+
53
+ return image
54
+
55
+
56
+ def prepare_dummy_inputs(tokenizer, image_processor):
57
+ prompt = "Question answering. What is the name of the company?"
58
+ prompt = "Question answering. In which year is the report made?"
59
+ prompt_ids = tokenizer.encode(prompt, add_special_tokens=False)
60
+
61
+ image = get_image()
62
+ # words, boxes = apply_tesseract(image, lang=None)
63
+ # fmt: off
64
+ words = ['7', 'ITC', 'Limited', 'REPORT', 'AND', 'ACCOUNTS', '2013', 'ITC’s', 'Brands:', 'An', 'Asset', 'for', 'the', 'Nation', 'The', 'consumer', 'needs', 'and', 'aspirations', 'they', 'fulfil,', 'the', 'benefit', 'they', 'generate', 'for', 'millions', 'across', 'ITC’s', 'value', 'chains,', 'the', 'future-ready', 'capabilities', 'that', 'support', 'them,', 'and', 'the', 'value', 'that', 'they', 'create', 'for', 'the', 'country,', 'have', 'made', 'ITC’s', 'brands', 'national', 'assets,', 'adding', 'to', 'India’s', 'competitiveness.', 'It', 'is', 'ITC’s', 'aspiration', 'to', 'be', 'the', 'No', '1', 'FMCG', 'player', 'in', 'the', 'country,', 'driven', 'by', 'its', 'new', 'FMCG', 'businesses.', 'A', 'recent', 'Nielsen', 'report', 'has', 'highlighted', 'that', "ITC's", 'new', 'FMCG', 'businesses', 'are', 'the', 'fastest', 'growing', 'among', 'the', 'top', 'consumer', 'goods', 'companies', 'operating', 'in', 'India.', 'ITC', 'takes', 'justifiable', 'pride', 'that,', 'along', 'with', 'generating', 'economic', 'value,', 'these', 'celebrated', 'Indian', 'brands', 'also', 'drive', 'the', 'creation', 'of', 'larger', 'societal', 'capital', 'through', 'the', 'virtuous', 'cycle', 'of', 'sustainable', 'and', 'inclusive', 'growth.', 'DI', 'WILLS', '*', ';', 'LOVE', 'DELIGHTFULLY', 'SOFT', 'SKIN?', 'aia', 'Ans', 'Source:', 'https://www.industrydocuments.ucsf.edu/docs/snbx0223']
65
+ boxes = [[0, 45, 67, 80], [72, 56, 109, 67], [116, 56, 189, 67], [198, 59, 253, 66], [257, 59, 285, 66], [289, 59, 365, 66], [372, 59, 407, 66], [74, 136, 161, 158], [175, 137, 306, 158], [318, 137, 363, 158], [374, 137, 472, 158], [483, 136, 529, 158], [540, 137, 593, 158], [608, 137, 717, 158], [73, 194, 100, 203], [106, 196, 177, 203], [183, 194, 227, 203], [233, 194, 259, 203], [265, 194, 344, 205], [74, 211, 104, 222], [109, 210, 141, 221], [147, 211, 169, 220], [175, 210, 223, 220], [229, 211, 259, 222], [265, 211, 329, 222], [334, 210, 352, 220], [74, 227, 127, 236], [133, 229, 180, 236], [187, 227, 221, 236], [226, 227, 264, 236], [270, 227, 320, 237], [327, 227, 349, 236], [74, 243, 161, 254], [166, 243, 249, 254], [254, 243, 281, 252], [286, 244, 342, 254], [74, 260, 112, 270], [119, 260, 145, 269], [151, 260, 174, 269], [179, 260, 217, 269], [222, 260, 249, 269], [254, 260, 285, 271], [290, 260, 335, 269], [340, 259, 359, 269], [74, 276, 95, 284], [101, 276, 156, 287], [164, 276, 198, 284], [203, 276, 244, 284], [251, 275, 285, 284], [291, 276, 340, 284], [74, 292, 129, 301], [135, 292, 185, 302], [192, 292, 242, 303], [248, 292, 261, 301], [267, 292, 312, 301], [74, 308, 195, 319], [75, 335, 82, 344], [88, 335, 98, 344], [105, 335, 138, 344], [144, 335, 214, 346], [220, 336, 233, 344], [239, 335, 256, 344], [262, 335, 283, 344], [290, 335, 309, 344], [316, 335, 320, 344], [74, 351, 119, 360], [126, 352, 170, 362], [176, 352, 186, 360], [192, 352, 214, 360], [220, 352, 276, 362], [282, 352, 326, 360], [333, 352, 349, 362], [74, 368, 89, 377], [95, 370, 124, 377], [129, 367, 175, 377], [181, 368, 266, 377], [272, 368, 283, 376], [289, 368, 333, 377], [74, 384, 126, 393], [134, 385, 175, 395], [181, 384, 206, 393], [212, 384, 292, 395], [298, 384, 325, 393], [330, 384, 366, 393], [74, 403, 103, 409], [109, 400, 154, 409], [161, 401, 241, 409], [247, 403, 269, 409], [275, 401, 296, 409], [302, 400, 349, 409], [74, 417, 131, 428], [137, 419, 186, 428], [192, 417, 214, 426], [219, 417, 242, 428], [248, 419, 319, 426], [74, 433, 119, 444], [125, 433, 204, 444], [210, 433, 278, 444], [285, 433, 295, 441], [302, 433, 340, 442], [75, 449, 98, 458], [104, 449, 142, 458], [146, 449, 215, 460], [221, 449, 258, 460], [263, 449, 293, 459], [300, 449, 339, 460], [74, 466, 101, 474], [108, 466, 185, 476], [191, 466, 261, 474], [267, 466, 309, 476], [315, 466, 354, 474], [74, 482, 151, 491], [158, 482, 201, 491], [208, 482, 258, 491], [263, 482, 292, 491], [298, 482, 333, 491], [338, 482, 360, 491], [74, 498, 131, 507], [137, 498, 150, 507], [156, 498, 197, 509], [202, 498, 257, 507], [263, 498, 310, 509], [74, 515, 128, 525], [134, 515, 156, 523], [161, 515, 218, 523], [223, 515, 261, 525], [267, 514, 280, 523], [74, 531, 156, 540], [162, 531, 188, 540], [195, 531, 257, 540], [263, 531, 315, 542], [871, 199, 878, 202], [883, 199, 908, 202], [894, 251, 904, 257], [841, 268, 841, 270], [784, 373, 811, 378], [816, 373, 896, 378], [784, 381, 811, 387], [815, 381, 847, 387], [645, 908, 670, 915], [692, 908, 712, 915], [220, 984, 285, 993], [293, 983, 779, 996]]
66
+ # fmt: on
67
+ text_list = []
68
+ bbox_list = []
69
+ for text, box in zip(words, boxes):
70
+ if text == "":
71
+ continue
72
+ sub_tokens = tokenizer.tokenize(text)
73
+ for sub_token in sub_tokens:
74
+ text_list.append(sub_token)
75
+ bbox_list.append(box)
76
+
77
+ input_ids = tokenizer.convert_tokens_to_ids(text_list)
78
+
79
+ input_ids = prompt_ids + input_ids
80
+ bbox = [[0, 0, 0, 0]] * len(prompt_ids) + bbox_list
81
+
82
+ pixel_values = image_processor(image, return_tensors="pt").pixel_values
83
+ original_pixel_values = original_transform(image, image_size=image_processor.size["height"]).unsqueeze(0)
84
+ # verify pixel values
85
+ assert torch.allclose(original_pixel_values, pixel_values)
86
+ print("Pixel values are ok!")
87
+
88
+ return torch.tensor(input_ids).unsqueeze(0), torch.tensor(bbox).unsqueeze(0).float(), pixel_values
89
+
90
+
91
+ def convert_udop_checkpoint(model_name, pytorch_dump_folder_path=None, push_to_hub=False):
92
+ # model_name to checkpoint_path
93
+ name_to_checkpoint_path = {
94
+ "udop-large": "/Users/nielsrogge/Documents/UDOP/udop-unimodel-large-224/pytorch_model.bin",
95
+ "udop-large-512": "/Users/nielsrogge/Documents/UDOP/udop-unimodel-large-512/pytorch_model.bin",
96
+ "udop-large-512-300k": "/Users/nielsrogge/Documents/UDOP/udop-unimodel-large-512-300k-steps/pytorch_model.bin",
97
+ }
98
+
99
+ # load original state dict
100
+ checkpoint_path = name_to_checkpoint_path[model_name]
101
+ state_dict = torch.load(checkpoint_path, map_location="cpu")
102
+
103
+ print("Checkpoint path:", checkpoint_path)
104
+
105
+ # create HF model
106
+ image_size = 512 if "512" in model_name else 224
107
+ config = UdopConfig(decoder_start_token_id=0, image_size=image_size)
108
+ model = UdopForConditionalGeneration(config)
109
+ model.eval()
110
+
111
+ # rename keys
112
+ state_dict = {k.replace("cell2dembedding", "cell_2d_embedding"): v for k, v in state_dict.items()}
113
+
114
+ # load weights
115
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
116
+ print("Missing keys:", missing_keys)
117
+ print("Unexpected keys:", unexpected_keys)
118
+ assert missing_keys == ["encoder.embed_patches.proj.weight", "encoder.embed_patches.proj.bias"]
119
+ assert unexpected_keys == ["pos_embed"]
120
+
121
+ # Add extra_ids to the special token list
122
+ # NOTE special tokens have a unique order
123
+ # see https://github.com/huggingface/transformers/issues/29591 for details
124
+ # fmt: off
125
+ additional_special_tokens = ['<extra_id_99>', '<extra_id_98>', '<extra_id_97>', '<extra_id_96>', '<extra_id_95>', '<extra_id_94>', '<extra_id_93>', '<extra_id_92>', '<extra_id_91>', '<extra_id_90>', '<extra_id_89>', '<extra_id_88>', '<extra_id_87>', '<extra_id_86>', '<extra_id_85>', '<extra_id_84>', '<extra_id_83>', '<extra_id_82>', '<extra_id_81>', '<extra_id_80>', '<extra_id_79>', '<extra_id_78>', '<extra_id_77>', '<extra_id_76>', '<extra_id_75>', '<extra_id_74>', '<extra_id_73>', '<extra_id_72>', '<extra_id_71>', '<extra_id_70>', '<extra_id_69>', '<extra_id_68>', '<extra_id_67>', '<extra_id_66>', '<extra_id_65>', '<extra_id_64>', '<extra_id_63>', '<extra_id_62>', '<extra_id_61>', '<extra_id_60>', '<extra_id_59>', '<extra_id_58>', '<extra_id_57>', '<extra_id_56>', '<extra_id_55>', '<extra_id_54>', '<extra_id_53>', '<extra_id_52>', '<extra_id_51>', '<extra_id_50>', '<extra_id_49>', '<extra_id_48>', '<extra_id_47>', '<extra_id_46>', '<extra_id_45>', '<extra_id_44>', '<extra_id_43>', '<extra_id_42>', '<extra_id_41>', '<extra_id_40>', '<extra_id_39>', '<extra_id_38>', '<extra_id_37>', '<extra_id_36>', '<extra_id_35>', '<extra_id_34>', '<extra_id_33>', '<extra_id_32>', '<extra_id_31>', '<extra_id_30>', '<extra_id_29>', '<extra_id_28>', '<extra_id_27>', '<extra_id_26>', '<extra_id_25>', '<extra_id_24>', '<extra_id_23>', '<extra_id_22>', '<extra_id_21>', '<extra_id_20>', '<extra_id_19>', '<extra_id_18>', '<extra_id_17>', '<extra_id_16>', '<extra_id_15>', '<extra_id_14>', '<extra_id_13>', '<extra_id_12>', '<extra_id_11>', '<extra_id_10>', '<extra_id_9>', '<extra_id_8>', '<extra_id_7>', '<extra_id_6>', '<extra_id_5>', '<extra_id_4>', '<extra_id_3>', '<extra_id_2>', '<extra_id_1>', '<extra_id_0>', '<extra_l_id_99>', '<extra_l_id_98>', '<extra_l_id_97>', '<extra_l_id_96>', '<extra_l_id_95>', '<extra_l_id_94>', '<extra_l_id_93>', '<extra_l_id_92>', '<extra_l_id_91>', '<extra_l_id_90>', '<extra_l_id_89>', '<extra_l_id_88>', '<extra_l_id_87>', '<extra_l_id_86>', '<extra_l_id_85>', '<extra_l_id_84>', '<extra_l_id_83>', '<extra_l_id_82>', '<extra_l_id_81>', '<extra_l_id_80>', '<extra_l_id_79>', '<extra_l_id_78>', '<extra_l_id_77>', '<extra_l_id_76>', '<extra_l_id_75>', '<extra_l_id_74>', '<extra_l_id_73>', '<extra_l_id_72>', '<extra_l_id_71>', '<extra_l_id_70>', '<extra_l_id_69>', '<extra_l_id_68>', '<extra_l_id_67>', '<extra_l_id_66>', '<extra_l_id_65>', '<extra_l_id_64>', '<extra_l_id_63>', '<extra_l_id_62>', '<extra_l_id_61>', '<extra_l_id_60>', '<extra_l_id_59>', '<extra_l_id_58>', '<extra_l_id_57>', '<extra_l_id_56>', '<extra_l_id_55>', '<extra_l_id_54>', '<extra_l_id_53>', '<extra_l_id_52>', '<extra_l_id_51>', '<extra_l_id_50>', '<extra_l_id_49>', '<extra_l_id_48>', '<extra_l_id_47>', '<extra_l_id_46>', '<extra_l_id_45>', '<extra_l_id_44>', '<extra_l_id_43>', '<extra_l_id_42>', '<extra_l_id_41>', '<extra_l_id_40>', '<extra_l_id_39>', '<extra_l_id_38>', '<extra_l_id_37>', '<extra_l_id_36>', '<extra_l_id_35>', '<extra_l_id_34>', '<extra_l_id_33>', '<extra_l_id_32>', '<extra_l_id_31>', '<extra_l_id_30>', '<extra_l_id_29>', '<extra_l_id_28>', '<extra_l_id_27>', '<extra_l_id_26>', '<extra_l_id_25>', '<extra_l_id_24>', '<extra_l_id_23>', '<extra_l_id_22>', '<extra_l_id_21>', '<extra_l_id_20>', '<extra_l_id_19>', '<extra_l_id_18>', '<extra_l_id_17>', '<extra_l_id_16>', '<extra_l_id_15>', '<extra_l_id_14>', '<extra_l_id_13>', '<extra_l_id_12>', '<extra_l_id_11>', '<extra_l_id_10>', '<extra_l_id_9>', '<extra_l_id_8>', '<extra_l_id_7>', '<extra_l_id_6>', '<extra_l_id_5>', '<extra_l_id_4>', '<extra_l_id_3>', '<extra_l_id_2>', '<extra_l_id_1>', '<extra_l_id_0>', '</extra_l_id_99>', '</extra_l_id_98>', '</extra_l_id_97>', '</extra_l_id_96>', '</extra_l_id_95>', '</extra_l_id_94>', '</extra_l_id_93>', '</extra_l_id_92>', '</extra_l_id_91>', '</extra_l_id_90>', '</extra_l_id_89>', '</extra_l_id_88>', '</extra_l_id_87>', '</extra_l_id_86>', '</extra_l_id_85>', '</extra_l_id_84>', '</extra_l_id_83>', '</extra_l_id_82>', '</extra_l_id_81>', '</extra_l_id_80>', '</extra_l_id_79>', '</extra_l_id_78>', '</extra_l_id_77>', '</extra_l_id_76>', '</extra_l_id_75>', '</extra_l_id_74>', '</extra_l_id_73>', '</extra_l_id_72>', '</extra_l_id_71>', '</extra_l_id_70>', '</extra_l_id_69>', '</extra_l_id_68>', '</extra_l_id_67>', '</extra_l_id_66>', '</extra_l_id_65>', '</extra_l_id_64>', '</extra_l_id_63>', '</extra_l_id_62>', '</extra_l_id_61>', '</extra_l_id_60>', '</extra_l_id_59>', '</extra_l_id_58>', '</extra_l_id_57>', '</extra_l_id_56>', '</extra_l_id_55>', '</extra_l_id_54>', '</extra_l_id_53>', '</extra_l_id_52>', '</extra_l_id_51>', '</extra_l_id_50>', '</extra_l_id_49>', '</extra_l_id_48>', '</extra_l_id_47>', '</extra_l_id_46>', '</extra_l_id_45>', '</extra_l_id_44>', '</extra_l_id_43>', '</extra_l_id_42>', '</extra_l_id_41>', '</extra_l_id_40>', '</extra_l_id_39>', '</extra_l_id_38>', '</extra_l_id_37>', '</extra_l_id_36>', '</extra_l_id_35>', '</extra_l_id_34>', '</extra_l_id_33>', '</extra_l_id_32>', '</extra_l_id_31>', '</extra_l_id_30>', '</extra_l_id_29>', '</extra_l_id_28>', '</extra_l_id_27>', '</extra_l_id_26>', '</extra_l_id_25>', '</extra_l_id_24>', '</extra_l_id_23>', '</extra_l_id_22>', '</extra_l_id_21>', '</extra_l_id_20>', '</extra_l_id_19>', '</extra_l_id_18>', '</extra_l_id_17>', '</extra_l_id_16>', '</extra_l_id_15>', '</extra_l_id_14>', '</extra_l_id_13>', '</extra_l_id_12>', '</extra_l_id_11>', '</extra_l_id_10>', '</extra_l_id_9>', '</extra_l_id_8>', '</extra_l_id_7>', '</extra_l_id_6>', '</extra_l_id_5>', '</extra_l_id_4>', '</extra_l_id_3>', '</extra_l_id_2>', '</extra_l_id_1>', '</extra_l_id_0>', '<extra_t_id_99>', '<extra_t_id_98>', '<extra_t_id_97>', '<extra_t_id_96>', '<extra_t_id_95>', '<extra_t_id_94>', '<extra_t_id_93>', '<extra_t_id_92>', '<extra_t_id_91>', '<extra_t_id_90>', '<extra_t_id_89>', '<extra_t_id_88>', '<extra_t_id_87>', '<extra_t_id_86>', '<extra_t_id_85>', '<extra_t_id_84>', '<extra_t_id_83>', '<extra_t_id_82>', '<extra_t_id_81>', '<extra_t_id_80>', '<extra_t_id_79>', '<extra_t_id_78>', '<extra_t_id_77>', '<extra_t_id_76>', '<extra_t_id_75>', '<extra_t_id_74>', '<extra_t_id_73>', '<extra_t_id_72>', '<extra_t_id_71>', '<extra_t_id_70>', '<extra_t_id_69>', '<extra_t_id_68>', '<extra_t_id_67>', '<extra_t_id_66>', '<extra_t_id_65>', '<extra_t_id_64>', '<extra_t_id_63>', '<extra_t_id_62>', '<extra_t_id_61>', '<extra_t_id_60>', '<extra_t_id_59>', '<extra_t_id_58>', '<extra_t_id_57>', '<extra_t_id_56>', '<extra_t_id_55>', '<extra_t_id_54>', '<extra_t_id_53>', '<extra_t_id_52>', '<extra_t_id_51>', '<extra_t_id_50>', '<extra_t_id_49>', '<extra_t_id_48>', '<extra_t_id_47>', '<extra_t_id_46>', '<extra_t_id_45>', '<extra_t_id_44>', '<extra_t_id_43>', '<extra_t_id_42>', '<extra_t_id_41>', '<extra_t_id_40>', '<extra_t_id_39>', '<extra_t_id_38>', '<extra_t_id_37>', '<extra_t_id_36>', '<extra_t_id_35>', '<extra_t_id_34>', '<extra_t_id_33>', '<extra_t_id_32>', '<extra_t_id_31>', '<extra_t_id_30>', '<extra_t_id_29>', '<extra_t_id_28>', '<extra_t_id_27>', '<extra_t_id_26>', '<extra_t_id_25>', '<extra_t_id_24>', '<extra_t_id_23>', '<extra_t_id_22>', '<extra_t_id_21>', '<extra_t_id_20>', '<extra_t_id_19>', '<extra_t_id_18>', '<extra_t_id_17>', '<extra_t_id_16>', '<extra_t_id_15>', '<extra_t_id_14>', '<extra_t_id_13>', '<extra_t_id_12>', '<extra_t_id_11>', '<extra_t_id_10>', '<extra_t_id_9>', '<extra_t_id_8>', '<extra_t_id_7>', '<extra_t_id_6>', '<extra_t_id_5>', '<extra_t_id_4>', '<extra_t_id_3>', '<extra_t_id_2>', '<extra_t_id_1>', '<extra_t_id_0>', '</extra_t_id_99>', '</extra_t_id_98>', '</extra_t_id_97>', '</extra_t_id_96>', '</extra_t_id_95>', '</extra_t_id_94>', '</extra_t_id_93>', '</extra_t_id_92>', '</extra_t_id_91>', '</extra_t_id_90>', '</extra_t_id_89>', '</extra_t_id_88>', '</extra_t_id_87>', '</extra_t_id_86>', '</extra_t_id_85>', '</extra_t_id_84>', '</extra_t_id_83>', '</extra_t_id_82>', '</extra_t_id_81>', '</extra_t_id_80>', '</extra_t_id_79>', '</extra_t_id_78>', '</extra_t_id_77>', '</extra_t_id_76>', '</extra_t_id_75>', '</extra_t_id_74>', '</extra_t_id_73>', '</extra_t_id_72>', '</extra_t_id_71>', '</extra_t_id_70>', '</extra_t_id_69>', '</extra_t_id_68>', '</extra_t_id_67>', '</extra_t_id_66>', '</extra_t_id_65>', '</extra_t_id_64>', '</extra_t_id_63>', '</extra_t_id_62>', '</extra_t_id_61>', '</extra_t_id_60>', '</extra_t_id_59>', '</extra_t_id_58>', '</extra_t_id_57>', '</extra_t_id_56>', '</extra_t_id_55>', '</extra_t_id_54>', '</extra_t_id_53>', '</extra_t_id_52>', '</extra_t_id_51>', '</extra_t_id_50>', '</extra_t_id_49>', '</extra_t_id_48>', '</extra_t_id_47>', '</extra_t_id_46>', '</extra_t_id_45>', '</extra_t_id_44>', '</extra_t_id_43>', '</extra_t_id_42>', '</extra_t_id_41>', '</extra_t_id_40>', '</extra_t_id_39>', '</extra_t_id_38>', '</extra_t_id_37>', '</extra_t_id_36>', '</extra_t_id_35>', '</extra_t_id_34>', '</extra_t_id_33>', '</extra_t_id_32>', '</extra_t_id_31>', '</extra_t_id_30>', '</extra_t_id_29>', '</extra_t_id_28>', '</extra_t_id_27>', '</extra_t_id_26>', '</extra_t_id_25>', '</extra_t_id_24>', '</extra_t_id_23>', '</extra_t_id_22>', '</extra_t_id_21>', '</extra_t_id_20>', '</extra_t_id_19>', '</extra_t_id_18>', '</extra_t_id_17>', '</extra_t_id_16>', '</extra_t_id_15>', '</extra_t_id_14>', '</extra_t_id_13>', '</extra_t_id_12>', '</extra_t_id_11>', '</extra_t_id_10>', '</extra_t_id_9>', '</extra_t_id_8>', '</extra_t_id_7>', '</extra_t_id_6>', '</extra_t_id_5>', '</extra_t_id_4>', '</extra_t_id_3>', '</extra_t_id_2>', '</extra_t_id_1>', '</extra_t_id_0>', '<loc_500>', '<loc_499>', '<loc_498>', '<loc_497>', '<loc_496>', '<loc_495>', '<loc_494>', '<loc_493>', '<loc_492>', '<loc_491>', '<loc_490>', '<loc_489>', '<loc_488>', '<loc_487>', '<loc_486>', '<loc_485>', '<loc_484>', '<loc_483>', '<loc_482>', '<loc_481>', '<loc_480>', '<loc_479>', '<loc_478>', '<loc_477>', '<loc_476>', '<loc_475>', '<loc_474>', '<loc_473>', '<loc_472>', '<loc_471>', '<loc_470>', '<loc_469>', '<loc_468>', '<loc_467>', '<loc_466>', '<loc_465>', '<loc_464>', '<loc_463>', '<loc_462>', '<loc_461>', '<loc_460>', '<loc_459>', '<loc_458>', '<loc_457>', '<loc_456>', '<loc_455>', '<loc_454>', '<loc_453>', '<loc_452>', '<loc_451>', '<loc_450>', '<loc_449>', '<loc_448>', '<loc_447>', '<loc_446>', '<loc_445>', '<loc_444>', '<loc_443>', '<loc_442>', '<loc_441>', '<loc_440>', '<loc_439>', '<loc_438>', '<loc_437>', '<loc_436>', '<loc_435>', '<loc_434>', '<loc_433>', '<loc_432>', '<loc_431>', '<loc_430>', '<loc_429>', '<loc_428>', '<loc_427>', '<loc_426>', '<loc_425>', '<loc_424>', '<loc_423>', '<loc_422>', '<loc_421>', '<loc_420>', '<loc_419>', '<loc_418>', '<loc_417>', '<loc_416>', '<loc_415>', '<loc_414>', '<loc_413>', '<loc_412>', '<loc_411>', '<loc_410>', '<loc_409>', '<loc_408>', '<loc_407>', '<loc_406>', '<loc_405>', '<loc_404>', '<loc_403>', '<loc_402>', '<loc_401>', '<loc_400>', '<loc_399>', '<loc_398>', '<loc_397>', '<loc_396>', '<loc_395>', '<loc_394>', '<loc_393>', '<loc_392>', '<loc_391>', '<loc_390>', '<loc_389>', '<loc_388>', '<loc_387>', '<loc_386>', '<loc_385>', '<loc_384>', '<loc_383>', '<loc_382>', '<loc_381>', '<loc_380>', '<loc_379>', '<loc_378>', '<loc_377>', '<loc_376>', '<loc_375>', '<loc_374>', '<loc_373>', '<loc_372>', '<loc_371>', '<loc_370>', '<loc_369>', '<loc_368>', '<loc_367>', '<loc_366>', '<loc_365>', '<loc_364>', '<loc_363>', '<loc_362>', '<loc_361>', '<loc_360>', '<loc_359>', '<loc_358>', '<loc_357>', '<loc_356>', '<loc_355>', '<loc_354>', '<loc_353>', '<loc_352>', '<loc_351>', '<loc_350>', '<loc_349>', '<loc_348>', '<loc_347>', '<loc_346>', '<loc_345>', '<loc_344>', '<loc_343>', '<loc_342>', '<loc_341>', '<loc_340>', '<loc_339>', '<loc_338>', '<loc_337>', '<loc_336>', '<loc_335>', '<loc_334>', '<loc_333>', '<loc_332>', '<loc_331>', '<loc_330>', '<loc_329>', '<loc_328>', '<loc_327>', '<loc_326>', '<loc_325>', '<loc_324>', '<loc_323>', '<loc_322>', '<loc_321>', '<loc_320>', '<loc_319>', '<loc_318>', '<loc_317>', '<loc_316>', '<loc_315>', '<loc_314>', '<loc_313>', '<loc_312>', '<loc_311>', '<loc_310>', '<loc_309>', '<loc_308>', '<loc_307>', '<loc_306>', '<loc_305>', '<loc_304>', '<loc_303>', '<loc_302>', '<loc_301>', '<loc_300>', '<loc_299>', '<loc_298>', '<loc_297>', '<loc_296>', '<loc_295>', '<loc_294>', '<loc_293>', '<loc_292>', '<loc_291>', '<loc_290>', '<loc_289>', '<loc_288>', '<loc_287>', '<loc_286>', '<loc_285>', '<loc_284>', '<loc_283>', '<loc_282>', '<loc_281>', '<loc_280>', '<loc_279>', '<loc_278>', '<loc_277>', '<loc_276>', '<loc_275>', '<loc_274>', '<loc_273>', '<loc_272>', '<loc_271>', '<loc_270>', '<loc_269>', '<loc_268>', '<loc_267>', '<loc_266>', '<loc_265>', '<loc_264>', '<loc_263>', '<loc_262>', '<loc_261>', '<loc_260>', '<loc_259>', '<loc_258>', '<loc_257>', '<loc_256>', '<loc_255>', '<loc_254>', '<loc_253>', '<loc_252>', '<loc_251>', '<loc_250>', '<loc_249>', '<loc_248>', '<loc_247>', '<loc_246>', '<loc_245>', '<loc_244>', '<loc_243>', '<loc_242>', '<loc_241>', '<loc_240>', '<loc_239>', '<loc_238>', '<loc_237>', '<loc_236>', '<loc_235>', '<loc_234>', '<loc_233>', '<loc_232>', '<loc_231>', '<loc_230>', '<loc_229>', '<loc_228>', '<loc_227>', '<loc_226>', '<loc_225>', '<loc_224>', '<loc_223>', '<loc_222>', '<loc_221>', '<loc_220>', '<loc_219>', '<loc_218>', '<loc_217>', '<loc_216>', '<loc_215>', '<loc_214>', '<loc_213>', '<loc_212>', '<loc_211>', '<loc_210>', '<loc_209>', '<loc_208>', '<loc_207>', '<loc_206>', '<loc_205>', '<loc_204>', '<loc_203>', '<loc_202>', '<loc_201>', '<loc_200>', '<loc_199>', '<loc_198>', '<loc_197>', '<loc_196>', '<loc_195>', '<loc_194>', '<loc_193>', '<loc_192>', '<loc_191>', '<loc_190>', '<loc_189>', '<loc_188>', '<loc_187>', '<loc_186>', '<loc_185>', '<loc_184>', '<loc_183>', '<loc_182>', '<loc_181>', '<loc_180>', '<loc_179>', '<loc_178>', '<loc_177>', '<loc_176>', '<loc_175>', '<loc_174>', '<loc_173>', '<loc_172>', '<loc_171>', '<loc_170>', '<loc_169>', '<loc_168>', '<loc_167>', '<loc_166>', '<loc_165>', '<loc_164>', '<loc_163>', '<loc_162>', '<loc_161>', '<loc_160>', '<loc_159>', '<loc_158>', '<loc_157>', '<loc_156>', '<loc_155>', '<loc_154>', '<loc_153>', '<loc_152>', '<loc_151>', '<loc_150>', '<loc_149>', '<loc_148>', '<loc_147>', '<loc_146>', '<loc_145>', '<loc_144>', '<loc_143>', '<loc_142>', '<loc_141>', '<loc_140>', '<loc_139>', '<loc_138>', '<loc_137>', '<loc_136>', '<loc_135>', '<loc_134>', '<loc_133>', '<loc_132>', '<loc_131>', '<loc_130>', '<loc_129>', '<loc_128>', '<loc_127>', '<loc_126>', '<loc_125>', '<loc_124>', '<loc_123>', '<loc_122>', '<loc_121>', '<loc_120>', '<loc_119>', '<loc_118>', '<loc_117>', '<loc_116>', '<loc_115>', '<loc_114>', '<loc_113>', '<loc_112>', '<loc_111>', '<loc_110>', '<loc_109>', '<loc_108>', '<loc_107>', '<loc_106>', '<loc_105>', '<loc_104>', '<loc_103>', '<loc_102>', '<loc_101>', '<loc_100>', '<loc_99>', '<loc_98>', '<loc_97>', '<loc_96>', '<loc_95>', '<loc_94>', '<loc_93>', '<loc_92>', '<loc_91>', '<loc_90>', '<loc_89>', '<loc_88>', '<loc_87>', '<loc_86>', '<loc_85>', '<loc_84>', '<loc_83>', '<loc_82>', '<loc_81>', '<loc_80>', '<loc_79>', '<loc_78>', '<loc_77>', '<loc_76>', '<loc_75>', '<loc_74>', '<loc_73>', '<loc_72>', '<loc_71>', '<loc_70>', '<loc_69>', '<loc_68>', '<loc_67>', '<loc_66>', '<loc_65>', '<loc_64>', '<loc_63>', '<loc_62>', '<loc_61>', '<loc_60>', '<loc_59>', '<loc_58>', '<loc_57>', '<loc_56>', '<loc_55>', '<loc_54>', '<loc_53>', '<loc_52>', '<loc_51>', '<loc_50>', '<loc_49>', '<loc_48>', '<loc_47>', '<loc_46>', '<loc_45>', '<loc_44>', '<loc_43>', '<loc_42>', '<loc_41>', '<loc_40>', '<loc_39>', '<loc_38>', '<loc_37>', '<loc_36>', '<loc_35>', '<loc_34>', '<loc_33>', '<loc_32>', '<loc_31>', '<loc_30>', '<loc_29>', '<loc_28>', '<loc_27>', '<loc_26>', '<loc_25>', '<loc_24>', '<loc_23>', '<loc_22>', '<loc_21>', '<loc_20>', '<loc_19>', '<loc_18>', '<loc_17>', '<loc_16>', '<loc_15>', '<loc_14>', '<loc_13>', '<loc_12>', '<loc_11>', '<loc_10>', '<loc_9>', '<loc_8>', '<loc_7>', '<loc_6>', '<loc_5>', '<loc_4>', '<loc_3>', '<loc_2>', '<loc_1>', '<loc_0>', '<other_199>', '<other_198>', '<other_197>', '<other_196>', '<other_195>', '<other_194>', '<other_193>', '<other_192>', '<other_191>', '<other_190>', '<other_189>', '<other_188>', '<other_187>', '<other_186>', '<other_185>', '<other_184>', '<other_183>', '<other_182>', '<other_181>', '<other_180>', '<other_179>', '<other_178>', '<other_177>', '<other_176>', '<other_175>', '<other_174>', '<other_173>', '<other_172>', '<other_171>', '<other_170>', '<other_169>', '<other_168>', '<other_167>', '<other_166>', '<other_165>', '<other_164>', '<other_163>', '<other_162>', '<other_161>', '<other_160>', '<other_159>', '<other_158>', '<other_157>', '<other_156>', '<other_155>', '<other_154>', '<other_153>', '<other_152>', '<other_151>', '<other_150>', '<other_149>', '<other_148>', '<other_147>', '<other_146>', '<other_145>', '<other_144>', '<other_143>', '<other_142>', '<other_141>', '<other_140>', '<other_139>', '<other_138>', '<other_137>', '<other_136>', '<other_135>', '<other_134>', '<other_133>', '<other_132>', '<other_131>', '<other_130>', '<other_129>', '<other_128>', '<other_127>', '<other_126>', '<other_125>', '<other_124>', '<other_123>', '<other_122>', '<other_121>', '<other_120>', '<other_119>', '<other_118>', '<other_117>', '<other_116>', '<other_115>', '<other_114>', '<other_113>', '<other_112>', '<other_111>', '<other_110>', '<other_109>', '<other_108>', '<other_107>', '<other_106>', '<other_105>', '<other_104>', '<other_103>', '<other_102>', '<other_101>', '<other_100>', '<other_99>', '<other_98>', '<other_97>', '<other_96>', '<other_95>', '<other_94>', '<other_93>', '<other_92>', '<other_91>', '<other_90>', '<other_89>', '<other_88>', '<other_87>', '<other_86>', '<other_85>', '<other_84>', '<other_83>', '<other_82>', '<other_81>', '<other_80>', '<other_79>', '<other_78>', '<other_77>', '<other_76>', '<other_75>', '<other_74>', '<other_73>', '<other_72>', '<other_71>', '<other_70>', '<other_69>', '<other_68>', '<other_67>', '<other_66>', '<other_65>', '<other_64>', '<other_63>', '<other_62>', '<other_61>', '<other_60>', '<other_59>', '<other_58>', '<other_57>', '<other_56>', '<other_55>', '<other_54>', '<other_53>', '<other_52>', '<other_51>', '<other_50>', '<other_49>', '<other_48>', '<other_47>', '<other_46>', '<other_45>', '<other_44>', '<other_43>', '<other_42>', '<other_41>', '<other_40>', '<other_39>', '<other_38>', '<other_37>', '<other_36>', '<other_35>', '<other_34>', '<other_33>', '<other_32>', '<other_31>', '<other_30>', '<other_29>', '<other_28>', '<other_27>', '<other_26>', '<other_25>', '<other_24>', '<other_23>', '<other_22>', '<other_21>', '<other_20>', '<other_19>', '<other_18>', '<other_17>', '<other_16>', '<other_15>', '<other_14>', '<other_13>', '<other_12>', '<other_11>', '<other_10>', '<other_9>', '<other_8>', '<other_7>', '<other_6>', '<other_5>', '<other_4>', '<other_3>', '<other_2>', '<other_1>', '<other_0>']
126
+ # fmt: on
127
+
128
+ tokenizer = UdopTokenizer.from_pretrained(
129
+ "/Users/nielsrogge/Documents/UDOP/udop-unimodel-large-512",
130
+ legacy=True,
131
+ additional_special_tokens=additional_special_tokens,
132
+ )
133
+ size = {"height": image_size, "width": image_size}
134
+ image_processor = LayoutLMv3ImageProcessor(
135
+ image_mean=IMAGENET_DEFAULT_MEAN, image_std=IMAGENET_DEFAULT_STD, size=size
136
+ )
137
+ processor = UdopProcessor(image_processor=image_processor, tokenizer=tokenizer)
138
+
139
+ # prepare dummy inputs
140
+ input_ids, bbox, image = prepare_dummy_inputs(tokenizer, image_processor)
141
+ prompt = "Question answering. In which year is the report made?"
142
+ encoding = processor(images=get_image(), text=prompt, return_tensors="pt")
143
+
144
+ input_ids = encoding.input_ids
145
+ try:
146
+ EXPECTED_INPUT_IDS = torch.tensor([[11860, 18243, 5, 86, 84, 215, 19, 8, 934, 263, 58, 1, 489, 27, 3838, 7363, 4083, 14536, 3430, 5686, 5911, 17161, 134, 2038, 27, 3838, 22, 7, 4688, 7, 10, 389, 18202, 21, 8, 11046, 37, 3733, 523, 11, 38, 2388, 1628, 3, 13133, 23334, 6, 8, 1656, 79, 3806, 21, 4040, 640, 27, 3838, 22, 7, 701, 16534, 6, 8, 3, 76, 2693, 18, 23015, 5644, 24, 380, 3, 6015, 6, 11, 8, 701, 24, 79, 482, 21, 3, 88, 684, 6, 43, 263, 27, 3838, 22, 7, 3635, 1157, 4089, 6, 2651, 12, 1547, 22, 7, 3265, 655, 5, 19, 27, 3838, 22, 7, 38, 2388, 257, 12, 36, 8, 465, 209, 13409, 12150, 1959, 16, 8, 684, 6, 6737, 57, 165, 126, 13409, 12150, 1623, 5, 71, 1100, 30298, 934, 65, 12566, 24, 27, 3838, 31, 7, 126, 13409, 12150, 1623, 33, 8, 10391, 1710, 859, 8, 420, 3733, 4968, 688, 2699, 16, 1547, 5, 27, 3838, 1217, 131, 99, 23, 179, 6064, 24, 6, 590, 28, 3, 11600, 1456, 701, 6, 175, 9443, 2557, 3635, 92, 1262, 8, 3409, 13, 2186, 3, 27908, 1784, 190, 8, 3, 5771, 17, 13281, 4005, 13, 5086, 11, 13066, 1170, 5, 10826, 16309, 134, 3, 2, 276, 26, 3, 55, 391, 13570, 5, 10315, 309, 3577, 19114, 371, 4254, 5121, 5055, 6245, 3, 10047, 3162, 58, 3, 9, 61, 1713, 2703, 476, 667, 25158, 301, 6058, 6038, 476, 3765, 9149, 10, 4893, 1303, 1986, 5, 13580, 7, 8224, 28244, 7, 5, 76, 75, 7, 89, 5, 15, 1259, 87, 7171, 7, 87, 7, 29, 115, 226, 4305, 2773, 1]]) # fmt: skip
147
+ torch.testing.assert_close(EXPECTED_INPUT_IDS, input_ids)
148
+ bbox = encoding.bbox.float()
149
+ pixel_values = encoding.pixel_values
150
+ except Exception:
151
+ print("Input_ids don't match, preparing dummy inputs")
152
+ input_ids, bbox, pixel_values = prepare_dummy_inputs(tokenizer, image_processor)
153
+
154
+ # Verify single forward pass
155
+ print("Testing single forward pass..")
156
+ with torch.no_grad():
157
+ decoder_input_ids = torch.tensor([[101]])
158
+ outputs = model(input_ids=input_ids, bbox=bbox, pixel_values=pixel_values, decoder_input_ids=decoder_input_ids)
159
+ print("Shape of logits:", outputs.logits.shape)
160
+ print("First values of logits:", outputs.logits[0, :3, :3])
161
+
162
+ # tensor([[-18.5262, 1.5087, -15.7051]]) on linux
163
+ # tensor([[-19.4976, 0.8515, -17.1873]]) on mac
164
+ try:
165
+ assert torch.allclose(outputs.logits[0, :3, :3], torch.tensor([[-18.5262, 1.5087, -15.7051]]), atol=1e-4)
166
+ print("Looks ok!")
167
+ except Exception:
168
+ print("logits don't match let's try to generate")
169
+
170
+ # Verify autoregressive decoding
171
+ print("Testing generation...")
172
+ model_kwargs = {"bbox": bbox, "pixel_values": pixel_values}
173
+ outputs = model.generate(input_ids=input_ids, **model_kwargs, max_new_tokens=20)
174
+
175
+ print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
176
+
177
+ # autoregressive decoding with original input data
178
+ print("Testing generation with original inputs...")
179
+ filepath = hf_hub_download(repo_id="nielsr/test-image", filename="input_ids_udop.pt", repo_type="dataset")
180
+ input_ids = torch.load(filepath)
181
+ filepath = hf_hub_download(repo_id="nielsr/test-image", filename="bbox_udop.pt", repo_type="dataset")
182
+ bbox = torch.load(filepath)
183
+ pixel_values_filename = "pixel_values_udop_512.pt" if "512" in model_name else "pixel_values_udop_224.pt"
184
+ filepath = hf_hub_download(repo_id="nielsr/test-image", filename=pixel_values_filename, repo_type="dataset")
185
+ pixel_values = torch.load(filepath)
186
+
187
+ print("Decoded input ids:", tokenizer.decode(input_ids[0], skip_special_tokens=True))
188
+ print("Bbox shape:", bbox.shape)
189
+
190
+ model_kwargs = {"bbox": bbox, "pixel_values": pixel_values}
191
+ outputs = model.generate(input_ids=input_ids, **model_kwargs, max_new_tokens=20)
192
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
193
+ print("Generated:", generated_text)
194
+
195
+ if pytorch_dump_folder_path is not None:
196
+ model.save_pretrained(pytorch_dump_folder_path)
197
+ processor.save_pretrained(pytorch_dump_folder_path)
198
+
199
+ if push_to_hub:
200
+ model.push_to_hub(f"microsoft/{model_name}")
201
+ processor.push_to_hub(f"microsoft/{model_name}")
202
+ # BIG note here: to save the fast tokenizer files in the repo on the hub, you need to do the following:
203
+ # see https://discuss.huggingface.co/t/convert-slow-xlmrobertatokenizer-to-fast-one/20876
204
+
205
+
206
+ if __name__ == "__main__":
207
+ parser = argparse.ArgumentParser()
208
+ # Required parameters
209
+ parser.add_argument(
210
+ "--model_name",
211
+ default="udop-large",
212
+ type=str,
213
+ choices=["udop-large", "udop-large-512", "udop-large-512-300k"],
214
+ help=("Name of the UDOP model you'd like to convert."),
215
+ )
216
+ parser.add_argument(
217
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
218
+ )
219
+ parser.add_argument(
220
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
221
+ )
222
+
223
+ args = parser.parse_args()
224
+ convert_udop_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/modeling_udop.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/processing_udop.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for UDOP.
17
+ """
18
+
19
+ from typing import List, Optional, Union
20
+
21
+ from transformers import logging
22
+
23
+ from ...image_processing_utils import BatchFeature
24
+ from ...image_utils import ImageInput
25
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
26
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ class UdopTextKwargs(TextKwargs, total=False):
33
+ word_labels: Optional[Union[List[int], List[List[int]]]]
34
+ boxes: Union[List[List[int]], List[List[List[int]]]]
35
+
36
+
37
+ class UdopProcessorKwargs(ProcessingKwargs, total=False):
38
+ text_kwargs: UdopTextKwargs
39
+ _defaults = {
40
+ "text_kwargs": {
41
+ "add_special_tokens": True,
42
+ "padding": False,
43
+ "truncation": False,
44
+ "stride": 0,
45
+ "return_overflowing_tokens": False,
46
+ "return_special_tokens_mask": False,
47
+ "return_offsets_mapping": False,
48
+ "return_length": False,
49
+ "verbose": True,
50
+ },
51
+ "images_kwargs": {},
52
+ }
53
+
54
+
55
+ class UdopProcessor(ProcessorMixin):
56
+ r"""
57
+ Constructs a UDOP processor which combines a LayoutLMv3 image processor and a UDOP tokenizer into a single processor.
58
+
59
+ [`UdopProcessor`] offers all the functionalities you need to prepare data for the model.
60
+
61
+ It first uses [`LayoutLMv3ImageProcessor`] to resize, rescale and normalize document images, and optionally applies OCR
62
+ to get words and normalized bounding boxes. These are then provided to [`UdopTokenizer`] or [`UdopTokenizerFast`],
63
+ which turns the words and bounding boxes into token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`.
64
+ Optionally, one can provide integer `word_labels`, which are turned into token-level `labels` for token
65
+ classification tasks (such as FUNSD, CORD).
66
+
67
+ Additionally, it also supports passing `text_target` and `text_pair_target` to the tokenizer, which can be used to
68
+ prepare labels for language modeling tasks.
69
+
70
+ Args:
71
+ image_processor (`LayoutLMv3ImageProcessor`):
72
+ An instance of [`LayoutLMv3ImageProcessor`]. The image processor is a required input.
73
+ tokenizer (`UdopTokenizer` or `UdopTokenizerFast`):
74
+ An instance of [`UdopTokenizer`] or [`UdopTokenizerFast`]. The tokenizer is a required input.
75
+ """
76
+
77
+ attributes = ["image_processor", "tokenizer"]
78
+ image_processor_class = "LayoutLMv3ImageProcessor"
79
+ tokenizer_class = ("UdopTokenizer", "UdopTokenizerFast")
80
+ # For backward compatibility. See transformers.processing_utils.ProcessorMixin.prepare_and_validate_optional_call_args for more details.
81
+ optional_call_args = ["text_pair"]
82
+
83
+ def __init__(self, image_processor, tokenizer):
84
+ super().__init__(image_processor, tokenizer)
85
+
86
+ def __call__(
87
+ self,
88
+ images: Optional[ImageInput] = None,
89
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
90
+ # The following is to capture `text_pair` argument that may be passed as a positional argument.
91
+ # See transformers.processing_utils.ProcessorMixin.prepare_and_validate_optional_call_args for more details,
92
+ # or this conversation for more context: https://github.com/huggingface/transformers/pull/32544#discussion_r1720208116
93
+ # This behavior is only needed for backward compatibility and will be removed in future versions.
94
+ #
95
+ *args,
96
+ audio=None,
97
+ videos=None,
98
+ **kwargs: Unpack[UdopProcessorKwargs],
99
+ ) -> BatchFeature:
100
+ """
101
+ This method first forwards the `images` argument to [`~UdopImageProcessor.__call__`]. In case
102
+ [`UdopImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
103
+ bounding boxes along with the additional arguments to [`~UdopTokenizer.__call__`] and returns the output,
104
+ together with the prepared `pixel_values`. In case [`UdopImageProcessor`] was initialized with `apply_ocr` set
105
+ to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along with the
106
+ additional arguments to [`~UdopTokenizer.__call__`] and returns the output, together with the prepared
107
+ `pixel_values`.
108
+
109
+ Alternatively, one can pass `text_target` and `text_pair_target` to prepare the targets of UDOP.
110
+
111
+ Please refer to the docstring of the above two methods for more information.
112
+ """
113
+ # verify input
114
+ output_kwargs = self._merge_kwargs(
115
+ UdopProcessorKwargs,
116
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
117
+ **kwargs,
118
+ **self.prepare_and_validate_optional_call_args(*args),
119
+ )
120
+
121
+ boxes = output_kwargs["text_kwargs"].pop("boxes", None)
122
+ word_labels = output_kwargs["text_kwargs"].pop("word_labels", None)
123
+ text_pair = output_kwargs["text_kwargs"].pop("text_pair", None)
124
+ return_overflowing_tokens = output_kwargs["text_kwargs"].get("return_overflowing_tokens", False)
125
+ return_offsets_mapping = output_kwargs["text_kwargs"].get("return_offsets_mapping", False)
126
+ text_target = output_kwargs["text_kwargs"].get("text_target", None)
127
+
128
+ if self.image_processor.apply_ocr and (boxes is not None):
129
+ raise ValueError(
130
+ "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
131
+ )
132
+
133
+ if self.image_processor.apply_ocr and (word_labels is not None):
134
+ raise ValueError(
135
+ "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
136
+ )
137
+
138
+ if return_overflowing_tokens and not return_offsets_mapping:
139
+ raise ValueError("You cannot return overflowing tokens without returning the offsets mapping.")
140
+
141
+ if text_target is not None:
142
+ # use the processor to prepare the targets of UDOP
143
+ return self.tokenizer(
144
+ **output_kwargs["text_kwargs"],
145
+ )
146
+
147
+ else:
148
+ # use the processor to prepare the inputs of UDOP
149
+ # first, apply the image processor
150
+ features = self.image_processor(images=images, **output_kwargs["images_kwargs"])
151
+ features_words = features.pop("words", None)
152
+ features_boxes = features.pop("boxes", None)
153
+
154
+ output_kwargs["text_kwargs"].pop("text_target", None)
155
+ output_kwargs["text_kwargs"].pop("text_pair_target", None)
156
+ output_kwargs["text_kwargs"]["text_pair"] = text_pair
157
+ output_kwargs["text_kwargs"]["boxes"] = boxes if boxes is not None else features_boxes
158
+ output_kwargs["text_kwargs"]["word_labels"] = word_labels
159
+
160
+ # second, apply the tokenizer
161
+ if text is not None and self.image_processor.apply_ocr and text_pair is None:
162
+ if isinstance(text, str):
163
+ text = [text] # add batch dimension (as the image processor always adds a batch dimension)
164
+ output_kwargs["text_kwargs"]["text_pair"] = features_words
165
+
166
+ encoded_inputs = self.tokenizer(
167
+ text=text if text is not None else features_words,
168
+ **output_kwargs["text_kwargs"],
169
+ )
170
+
171
+ # add pixel values
172
+ if return_overflowing_tokens is True:
173
+ features["pixel_values"] = self.get_overflowing_images(
174
+ features["pixel_values"], encoded_inputs["overflow_to_sample_mapping"]
175
+ )
176
+ features.update(encoded_inputs)
177
+
178
+ return features
179
+
180
+ # Copied from transformers.models.layoutlmv3.processing_layoutlmv3.LayoutLMv3Processor.get_overflowing_images
181
+ def get_overflowing_images(self, images, overflow_to_sample_mapping):
182
+ # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
183
+ images_with_overflow = []
184
+ for sample_idx in overflow_to_sample_mapping:
185
+ images_with_overflow.append(images[sample_idx])
186
+
187
+ if len(images_with_overflow) != len(overflow_to_sample_mapping):
188
+ raise ValueError(
189
+ "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
190
+ f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
191
+ )
192
+
193
+ return images_with_overflow
194
+
195
+ # Copied from transformers.models.layoutlmv3.processing_layoutlmv3.LayoutLMv3Processor.batch_decode
196
+ def batch_decode(self, *args, **kwargs):
197
+ """
198
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
199
+ refer to the docstring of this method for more information.
200
+ """
201
+ return self.tokenizer.batch_decode(*args, **kwargs)
202
+
203
+ # Copied from transformers.models.layoutlmv3.processing_layoutlmv3.LayoutLMv3Processor.decode
204
+ def decode(self, *args, **kwargs):
205
+ """
206
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
207
+ to the docstring of this method for more information.
208
+ """
209
+ return self.tokenizer.decode(*args, **kwargs)
210
+
211
+ @property
212
+ def model_input_names(self):
213
+ return ["pixel_values", "input_ids", "bbox", "attention_mask"]
214
+
215
+
216
+ __all__ = ["UdopProcessor"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/tokenization_udop.py ADDED
@@ -0,0 +1,1488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License
15
+ """Tokenization classes for UDOP model."""
16
+
17
+ import os
18
+ import re
19
+ import warnings
20
+ from shutil import copyfile
21
+ from typing import Any, Dict, List, Optional, Tuple, Union
22
+
23
+ import sentencepiece as spm
24
+
25
+ from ...tokenization_utils import PreTrainedTokenizer
26
+ from ...tokenization_utils_base import (
27
+ AddedToken,
28
+ BatchEncoding,
29
+ EncodedInput,
30
+ PreTokenizedInput,
31
+ TextInput,
32
+ TextInputPair,
33
+ TruncationStrategy,
34
+ )
35
+ from ...utils import PaddingStrategy, TensorType, add_end_docstrings, logging
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ SPIECE_UNDERLINE = "▁"
42
+
43
+
44
+ UDOP_ENCODE_KWARGS_DOCSTRING = r"""
45
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
46
+ Whether or not to encode the sequences with the special tokens relative to their model.
47
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
48
+ Activates and controls padding. Accepts the following values:
49
+
50
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
51
+ sequence if provided).
52
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
53
+ acceptable input length for the model if that argument is not provided.
54
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
55
+ lengths).
56
+ truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
57
+ Activates and controls truncation. Accepts the following values:
58
+
59
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
60
+ to the maximum acceptable input length for the model if that argument is not provided. This will
61
+ truncate token by token, removing a token from the longest sequence in the pair if a pair of
62
+ sequences (or a batch of pairs) is provided.
63
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
64
+ maximum acceptable input length for the model if that argument is not provided. This will only
65
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
66
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
67
+ maximum acceptable input length for the model if that argument is not provided. This will only
68
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
69
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
70
+ greater than the model maximum admissible input size).
71
+ max_length (`int`, *optional*):
72
+ Controls the maximum length to use by one of the truncation/padding parameters.
73
+
74
+ If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
75
+ is required by one of the truncation/padding parameters. If the model has no specific maximum input
76
+ length (like XLNet) truncation/padding to a maximum length will be deactivated.
77
+ stride (`int`, *optional*, defaults to 0):
78
+ If set to a number along with `max_length`, the overflowing tokens returned when
79
+ `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
80
+ returned to provide some overlap between truncated and overflowing sequences. The value of this
81
+ argument defines the number of overlapping tokens.
82
+ pad_to_multiple_of (`int`, *optional*):
83
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
84
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
85
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
86
+ If set, will return tensors instead of list of python integers. Acceptable values are:
87
+
88
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
89
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
90
+ - `'np'`: Return Numpy `np.ndarray` objects.
91
+ return_token_type_ids (`bool`, *optional*):
92
+ Whether to return token type IDs. If left to the default, will return the token type IDs according to
93
+ the specific tokenizer's default, defined by the `return_outputs` attribute.
94
+
95
+ [What are token type IDs?](../glossary#token-type-ids)
96
+ return_attention_mask (`bool`, *optional*):
97
+ Whether to return the attention mask. If left to the default, will return the attention mask according
98
+ to the specific tokenizer's default, defined by the `return_outputs` attribute.
99
+
100
+ [What are attention masks?](../glossary#attention-mask)
101
+ return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
102
+ Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
103
+ of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
104
+ of returning overflowing tokens.
105
+ return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
106
+ Whether or not to return special tokens mask information.
107
+ return_offsets_mapping (`bool`, *optional*, defaults to `False`):
108
+ Whether or not to return `(char_start, char_end)` for each token.
109
+
110
+ This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
111
+ Python's tokenizer, this method will raise `NotImplementedError`.
112
+ return_length (`bool`, *optional*, defaults to `False`):
113
+ Whether or not to return the lengths of the encoded inputs.
114
+ verbose (`bool`, *optional*, defaults to `True`):
115
+ Whether or not to print more information and warnings.
116
+ **kwargs: passed to the `self.tokenize()` method
117
+
118
+ Return:
119
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
120
+
121
+ - **input_ids** -- List of token ids to be fed to a model.
122
+
123
+ [What are input IDs?](../glossary#input-ids)
124
+
125
+ - **bbox** -- List of bounding boxes to be fed to a model.
126
+
127
+ - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
128
+ if *"token_type_ids"* is in `self.model_input_names`).
129
+
130
+ [What are token type IDs?](../glossary#token-type-ids)
131
+
132
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
133
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
134
+
135
+ [What are attention masks?](../glossary#attention-mask)
136
+
137
+ - **labels** -- List of labels to be fed to a model. (when `word_labels` is specified).
138
+ - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
139
+ `return_overflowing_tokens=True`).
140
+ - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
141
+ `return_overflowing_tokens=True`).
142
+ - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
143
+ regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
144
+ - **length** -- The length of the inputs (when `return_length=True`).
145
+ """
146
+
147
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
148
+
149
+
150
+ class UdopTokenizer(PreTrainedTokenizer):
151
+ """
152
+ Adapted from [`LayoutXLMTokenizer`] and [`T5Tokenizer`]. Based on
153
+ [SentencePiece](https://github.com/google/sentencepiece).
154
+
155
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
156
+ this superclass for more information regarding those methods.
157
+
158
+ Args:
159
+ vocab_file (`str`):
160
+ Path to the vocabulary file.
161
+
162
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
163
+ The end of sequence token.
164
+
165
+ <Tip>
166
+
167
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
168
+ The token used is the `sep_token`.
169
+
170
+ </Tip>
171
+
172
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
173
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
174
+ token instead.
175
+
176
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
177
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
178
+ sequence classification or for a text and a question for question answering. It is also used as the last
179
+ token of a sequence built with special tokens.
180
+
181
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
182
+ The token used for padding, for example when batching sequences of different lengths.
183
+ sep_token_box (`List[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
184
+ The bounding box to use for the special [SEP] token.
185
+ pad_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
186
+ The bounding box to use for the special [PAD] token.
187
+ pad_token_label (`int`, *optional*, defaults to -100):
188
+ The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
189
+ CrossEntropyLoss.
190
+ only_label_first_subword (`bool`, *optional*, defaults to `True`):
191
+ Whether or not to only label the first subword, in case word labels are provided.
192
+ additional_special_tokens (`List[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
193
+ Additional special tokens used by the tokenizer.
194
+
195
+ sp_model_kwargs (`dict`, *optional*):
196
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
197
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
198
+ to set:
199
+
200
+ - `enable_sampling`: Enable subword regularization.
201
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
202
+
203
+ - `nbest_size = {0,1}`: No sampling is performed.
204
+ - `nbest_size > 1`: samples from the nbest_size results.
205
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
206
+ using forward-filtering-and-backward-sampling algorithm.
207
+
208
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
209
+ BPE-dropout.
210
+ legacy (`bool`, *optional*, defaults to `True`):
211
+ Whether or not the `legacy` behaviour of the tokenizer should be used. Legacy is before the merge of #24622
212
+ which includes fixes to properly handle tokens that appear after special tokens. A simple example:
213
+ - `legacy=True`:
214
+ ```python
215
+ >>> from transformers import T5Tokenizer
216
+
217
+ >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=True)
218
+ >>> tokenizer.encode("Hello <extra_id_0>.")
219
+ [8774, 32099, 3, 5, 1]
220
+ ```
221
+ - `legacy=False`:
222
+ ```python
223
+ >>> from transformers import T5Tokenizer
224
+
225
+ >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=False)
226
+ >>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
227
+ [8774, 32099, 5, 1]
228
+ ```
229
+ Checkout the pull request and the issue [here](https://github.com/huggingface/transformers/pull/24565) for
230
+ more details.
231
+ add_prefix_space (`bool`, *optional*, defaults to `True`):
232
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
233
+ other word.
234
+
235
+
236
+ Attributes:
237
+ sp_model (`SentencePieceProcessor`):
238
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
239
+ """
240
+
241
+ vocab_files_names = VOCAB_FILES_NAMES
242
+ model_input_names = ["input_ids", "attention_mask"]
243
+
244
+ def __init__(
245
+ self,
246
+ vocab_file,
247
+ eos_token="</s>",
248
+ unk_token="<unk>",
249
+ sep_token="</s>",
250
+ pad_token="<pad>",
251
+ sep_token_box=[1000, 1000, 1000, 1000],
252
+ pad_token_box=[0, 0, 0, 0],
253
+ pad_token_label=-100,
254
+ only_label_first_subword=True,
255
+ additional_special_tokens=None,
256
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
257
+ legacy=True,
258
+ add_prefix_space=True,
259
+ **kwargs,
260
+ ) -> None:
261
+ eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
262
+ unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
263
+ sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
264
+ pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
265
+
266
+ self.legacy = legacy
267
+ self.add_prefix_space = add_prefix_space
268
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
269
+
270
+ self.vocab_file = vocab_file
271
+
272
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
273
+ self.sp_model.Load(vocab_file)
274
+
275
+ # additional properties
276
+ self.sep_token_box = sep_token_box
277
+ self.pad_token_box = pad_token_box
278
+ self.pad_token_label = pad_token_label
279
+ self.only_label_first_subword = only_label_first_subword
280
+
281
+ super().__init__(
282
+ eos_token=eos_token,
283
+ unk_token=unk_token,
284
+ sep_token=sep_token,
285
+ pad_token=pad_token,
286
+ sep_token_box=sep_token_box,
287
+ pad_token_box=pad_token_box,
288
+ pad_token_label=pad_token_label,
289
+ only_label_first_subword=only_label_first_subword,
290
+ additional_special_tokens=additional_special_tokens,
291
+ sp_model_kwargs=self.sp_model_kwargs,
292
+ legacy=legacy,
293
+ add_prefix_space=add_prefix_space,
294
+ **kwargs,
295
+ )
296
+
297
+ @property
298
+ def vocab_size(self):
299
+ return len(self.sp_model)
300
+
301
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_vocab
302
+ def get_vocab(self):
303
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
304
+ vocab.update(self.added_tokens_encoder)
305
+ return vocab
306
+
307
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_special_tokens_mask
308
+ def get_special_tokens_mask(
309
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
310
+ ) -> List[int]:
311
+ """
312
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
313
+ special tokens using the tokenizer `prepare_for_model` method.
314
+
315
+ Args:
316
+ token_ids_0 (`List[int]`):
317
+ List of IDs.
318
+ token_ids_1 (`List[int]`, *optional*):
319
+ Optional second list of IDs for sequence pairs.
320
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
321
+ Whether or not the token list is already formatted with special tokens for the model.
322
+
323
+ Returns:
324
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
325
+ """
326
+ if already_has_special_tokens:
327
+ return super().get_special_tokens_mask(
328
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
329
+ )
330
+
331
+ # normal case: some special tokens
332
+ if token_ids_1 is None:
333
+ return ([0] * len(token_ids_0)) + [1]
334
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
335
+
336
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_sentinel_tokens
337
+ def get_sentinel_tokens(self):
338
+ return list(
339
+ set(filter(lambda x: bool(re.search(r"<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
340
+ )
341
+
342
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_sentinel_token_ids
343
+ def get_sentinel_token_ids(self):
344
+ return [self.convert_tokens_to_ids(token) for token in self.get_sentinel_tokens()]
345
+
346
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._add_eos_if_not_present
347
+ def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
348
+ """Do not add eos again if user already added it."""
349
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
350
+ warnings.warn(
351
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
352
+ " eos tokens being added."
353
+ )
354
+ return token_ids
355
+ else:
356
+ return token_ids + [self.eos_token_id]
357
+
358
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.create_token_type_ids_from_sequences
359
+ def create_token_type_ids_from_sequences(
360
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
361
+ ) -> List[int]:
362
+ """
363
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
364
+ use of token type ids, therefore a list of zeros is returned.
365
+
366
+ Args:
367
+ token_ids_0 (`List[int]`):
368
+ List of IDs.
369
+ token_ids_1 (`List[int]`, *optional*):
370
+ Optional second list of IDs for sequence pairs.
371
+
372
+ Returns:
373
+ `List[int]`: List of zeros.
374
+ """
375
+ eos = [self.eos_token_id]
376
+
377
+ if token_ids_1 is None:
378
+ return len(token_ids_0 + eos) * [0]
379
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
380
+
381
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.build_inputs_with_special_tokens
382
+ def build_inputs_with_special_tokens(
383
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
384
+ ) -> List[int]:
385
+ """
386
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
387
+ adding special tokens. A sequence has the following format:
388
+
389
+ - single sequence: `X </s>`
390
+ - pair of sequences: `A </s> B </s>`
391
+
392
+ Args:
393
+ token_ids_0 (`List[int]`):
394
+ List of IDs to which the special tokens will be added.
395
+ token_ids_1 (`List[int]`, *optional*):
396
+ Optional second list of IDs for sequence pairs.
397
+
398
+ Returns:
399
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
400
+ """
401
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
402
+ if token_ids_1 is None:
403
+ return token_ids_0
404
+ else:
405
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
406
+ return token_ids_0 + token_ids_1
407
+
408
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.__getstate__
409
+ def __getstate__(self):
410
+ state = self.__dict__.copy()
411
+ state["sp_model"] = None
412
+ return state
413
+
414
+ def __setstate__(self, d):
415
+ self.__dict__.update(d)
416
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
417
+ self.sp_model.Load(self.vocab_file)
418
+
419
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
420
+ def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
421
+ """
422
+ Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
423
+ first token is special.
424
+ """
425
+ if self.legacy or len(text) == 0:
426
+ return super().tokenize(text, **kwargs)
427
+
428
+ text = text.replace(SPIECE_UNDERLINE, " ")
429
+ if self.add_prefix_space:
430
+ text = SPIECE_UNDERLINE + text
431
+
432
+ tokens = super().tokenize(text, **kwargs)
433
+
434
+ if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
435
+ tokens = tokens[1:]
436
+ return tokens
437
+
438
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
439
+ def _tokenize(self, text, **kwargs):
440
+ """
441
+ Returns a tokenized string.
442
+
443
+ We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
444
+ SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
445
+ `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
446
+ `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
447
+ `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
448
+ """
449
+ if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
450
+ return self.sp_model.encode(text, out_type=str)
451
+
452
+ # 1. Encode string + prefix ex: "<unk> Hey"
453
+ tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
454
+ # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
455
+ return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
456
+
457
+ def _convert_token_to_id(self, token):
458
+ """Converts a token (str) in an id using the vocab."""
459
+ return self.sp_model.piece_to_id(token)
460
+
461
+ def _convert_id_to_token(self, index):
462
+ """Converts an index (integer) in a token (str) using the vocab."""
463
+ return self.sp_model.IdToPiece(index)
464
+
465
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.convert_tokens_to_string
466
+ def convert_tokens_to_string(self, tokens):
467
+ """Converts a sequence of tokens (string) in a single string."""
468
+ # since we manually add the prefix space, we have to remove it when decoding
469
+ if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
470
+ tokens[0] = tokens[0][1:]
471
+
472
+ current_sub_tokens = []
473
+ out_string = ""
474
+ prev_is_special = False
475
+ for token in tokens:
476
+ # make sure that special tokens are not decoded using sentencepiece model
477
+ if token in self.all_special_tokens:
478
+ if not prev_is_special:
479
+ out_string += " "
480
+ out_string += self.sp_model.decode(current_sub_tokens) + token
481
+ prev_is_special = True
482
+ current_sub_tokens = []
483
+ else:
484
+ current_sub_tokens.append(token)
485
+ prev_is_special = False
486
+ out_string += self.sp_model.decode(current_sub_tokens)
487
+ return out_string.strip()
488
+
489
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.save_vocabulary
490
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
491
+ if not os.path.isdir(save_directory):
492
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
493
+ return
494
+ out_vocab_file = os.path.join(
495
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
496
+ )
497
+
498
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
499
+ copyfile(self.vocab_file, out_vocab_file)
500
+ elif not os.path.isfile(self.vocab_file):
501
+ with open(out_vocab_file, "wb") as fi:
502
+ content_spiece_model = self.sp_model.serialized_model_proto()
503
+ fi.write(content_spiece_model)
504
+
505
+ return (out_vocab_file,)
506
+
507
+ @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
508
+ def __call__(
509
+ self,
510
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
511
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
512
+ boxes: Union[List[List[int]], List[List[List[int]]]] = None,
513
+ word_labels: Optional[Union[List[int], List[List[int]]]] = None,
514
+ text_target: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
515
+ text_pair_target: Optional[
516
+ Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]
517
+ ] = None,
518
+ **kwargs,
519
+ ) -> BatchEncoding:
520
+ if text is None and text_target is None:
521
+ raise ValueError("You need to specify either `text` or `text_target`.")
522
+ if text is not None:
523
+ # The context manager will send the inputs as normal texts and not text_target, but we shouldn't change the
524
+ # input mode in this case.
525
+ if not self._in_target_context_manager:
526
+ self._switch_to_input_mode()
527
+ encodings = self.call_boxes(text=text, text_pair=text_pair, boxes=boxes, word_labels=word_labels, **kwargs)
528
+ if text_target is not None:
529
+ self._switch_to_target_mode()
530
+ target_encodings = self._call_one(text=text_target, text_pair=text_pair_target, **kwargs)
531
+ # Leave back tokenizer in input mode
532
+ self._switch_to_input_mode()
533
+
534
+ if text_target is None:
535
+ return encodings
536
+ elif text is None:
537
+ return target_encodings
538
+ else:
539
+ encodings["labels"] = target_encodings["input_ids"]
540
+ return encodings
541
+
542
+ def call_boxes(
543
+ self,
544
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
545
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
546
+ boxes: Union[List[List[int]], List[List[List[int]]]] = None,
547
+ word_labels: Optional[Union[List[int], List[List[int]]]] = None,
548
+ add_special_tokens: bool = True,
549
+ padding: Union[bool, str, PaddingStrategy] = False,
550
+ truncation: Union[bool, str, TruncationStrategy] = None,
551
+ max_length: Optional[int] = None,
552
+ stride: int = 0,
553
+ pad_to_multiple_of: Optional[int] = None,
554
+ padding_side: Optional[str] = None,
555
+ return_tensors: Optional[Union[str, TensorType]] = None,
556
+ return_token_type_ids: Optional[bool] = None,
557
+ return_attention_mask: Optional[bool] = None,
558
+ return_overflowing_tokens: bool = False,
559
+ return_special_tokens_mask: bool = False,
560
+ return_offsets_mapping: bool = False,
561
+ return_length: bool = False,
562
+ verbose: bool = True,
563
+ **kwargs,
564
+ ) -> BatchEncoding:
565
+ """
566
+ Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
567
+ sequences with word-level normalized bounding boxes and optional labels.
568
+
569
+ Args:
570
+ text (`str`, `List[str]`, `List[List[str]]`):
571
+ The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
572
+ (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
573
+ words).
574
+ text_pair (`List[str]`, `List[List[str]]`):
575
+ The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
576
+ (pretokenized string).
577
+ boxes (`List[List[int]]`, `List[List[List[int]]]`):
578
+ Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
579
+ word_labels (`List[int]`, `List[List[int]]`, *optional*):
580
+ Word-level integer labels (for token classification tasks such as FUNSD, CORD).
581
+ """
582
+
583
+ # Input type checking for clearer error
584
+ def _is_valid_text_input(t):
585
+ if isinstance(t, str):
586
+ # Strings are fine
587
+ return True
588
+ elif isinstance(t, (list, tuple)):
589
+ # List are fine as long as they are...
590
+ if len(t) == 0:
591
+ # ... empty
592
+ return True
593
+ elif isinstance(t[0], str):
594
+ # ... list of strings
595
+ return True
596
+ elif isinstance(t[0], (list, tuple)):
597
+ # ... list with an empty list or with a list of strings
598
+ return len(t[0]) == 0 or isinstance(t[0][0], str)
599
+ else:
600
+ return False
601
+ else:
602
+ return False
603
+
604
+ if text_pair is not None:
605
+ # in case text + text_pair are provided, text = questions, text_pair = words
606
+ if not _is_valid_text_input(text):
607
+ raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
608
+ if not isinstance(text_pair, (list, tuple)):
609
+ raise ValueError(
610
+ "words must of type `List[str]` (single pretokenized example), "
611
+ "or `List[List[str]]` (batch of pretokenized examples)."
612
+ )
613
+ else:
614
+ # in case only text is provided => must be words
615
+ if not isinstance(text, (list, tuple)):
616
+ raise ValueError(
617
+ "Words must of type `List[str]` (single pretokenized example), "
618
+ "or `List[List[str]]` (batch of pretokenized examples)."
619
+ )
620
+
621
+ if text_pair is not None:
622
+ is_batched = isinstance(text, (list, tuple))
623
+ else:
624
+ is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
625
+
626
+ words = text if text_pair is None else text_pair
627
+ if boxes is None:
628
+ raise ValueError("You must provide corresponding bounding boxes")
629
+ if is_batched:
630
+ if len(words) != len(boxes):
631
+ raise ValueError("You must provide words and boxes for an equal amount of examples")
632
+ for words_example, boxes_example in zip(words, boxes):
633
+ if len(words_example) != len(boxes_example):
634
+ raise ValueError("You must provide as many words as there are bounding boxes")
635
+ else:
636
+ if len(words) != len(boxes):
637
+ raise ValueError("You must provide as many words as there are bounding boxes")
638
+
639
+ if is_batched:
640
+ if text_pair is not None and len(text) != len(text_pair):
641
+ raise ValueError(
642
+ f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
643
+ f" {len(text_pair)}."
644
+ )
645
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
646
+ is_pair = bool(text_pair is not None)
647
+ return self.batch_encode_plus_boxes(
648
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
649
+ is_pair=is_pair,
650
+ boxes=boxes,
651
+ word_labels=word_labels,
652
+ add_special_tokens=add_special_tokens,
653
+ padding=padding,
654
+ truncation=truncation,
655
+ max_length=max_length,
656
+ stride=stride,
657
+ pad_to_multiple_of=pad_to_multiple_of,
658
+ padding_side=padding_side,
659
+ return_tensors=return_tensors,
660
+ return_token_type_ids=return_token_type_ids,
661
+ return_attention_mask=return_attention_mask,
662
+ return_overflowing_tokens=return_overflowing_tokens,
663
+ return_special_tokens_mask=return_special_tokens_mask,
664
+ return_offsets_mapping=return_offsets_mapping,
665
+ return_length=return_length,
666
+ verbose=verbose,
667
+ **kwargs,
668
+ )
669
+ else:
670
+ return self.encode_plus_boxes(
671
+ text=text,
672
+ text_pair=text_pair,
673
+ boxes=boxes,
674
+ word_labels=word_labels,
675
+ add_special_tokens=add_special_tokens,
676
+ padding=padding,
677
+ truncation=truncation,
678
+ max_length=max_length,
679
+ stride=stride,
680
+ pad_to_multiple_of=pad_to_multiple_of,
681
+ padding_side=padding_side,
682
+ return_tensors=return_tensors,
683
+ return_token_type_ids=return_token_type_ids,
684
+ return_attention_mask=return_attention_mask,
685
+ return_overflowing_tokens=return_overflowing_tokens,
686
+ return_special_tokens_mask=return_special_tokens_mask,
687
+ return_offsets_mapping=return_offsets_mapping,
688
+ return_length=return_length,
689
+ verbose=verbose,
690
+ **kwargs,
691
+ )
692
+
693
+ def batch_encode_plus_boxes(
694
+ self,
695
+ batch_text_or_text_pairs: Union[
696
+ List[TextInput],
697
+ List[TextInputPair],
698
+ List[PreTokenizedInput],
699
+ ],
700
+ is_pair: bool = None,
701
+ boxes: Optional[List[List[List[int]]]] = None,
702
+ word_labels: Optional[List[List[int]]] = None,
703
+ add_special_tokens: bool = True,
704
+ padding: Union[bool, str, PaddingStrategy] = False,
705
+ truncation: Union[bool, str, TruncationStrategy] = None,
706
+ max_length: Optional[int] = None,
707
+ stride: int = 0,
708
+ is_split_into_words: bool = False,
709
+ pad_to_multiple_of: Optional[int] = None,
710
+ padding_side: Optional[str] = None,
711
+ return_tensors: Optional[Union[str, TensorType]] = None,
712
+ return_token_type_ids: Optional[bool] = None,
713
+ return_attention_mask: Optional[bool] = None,
714
+ return_overflowing_tokens: bool = False,
715
+ return_special_tokens_mask: bool = False,
716
+ return_offsets_mapping: bool = False,
717
+ return_length: bool = False,
718
+ verbose: bool = True,
719
+ **kwargs,
720
+ ) -> BatchEncoding:
721
+ """
722
+ Tokenize and prepare for the model a list of sequences or a list of pairs of sequences.
723
+
724
+ Args:
725
+ batch_text_or_text_pairs (`List[str]`, `List[Tuple[str, str]]`, `List[List[str]]`, `List[Tuple[List[str], List[str]]]`, and for not-fast tokenizers, also `List[List[int]]`, `List[Tuple[List[int], List[int]]]`):
726
+ Batch of sequences or pair of sequences to be encoded. This can be a list of
727
+ string/string-sequences/int-sequences or a list of pair of string/string-sequences/int-sequence (see
728
+ details in `encode_plus`).
729
+ """
730
+
731
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
732
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
733
+ padding=padding,
734
+ truncation=truncation,
735
+ max_length=max_length,
736
+ pad_to_multiple_of=pad_to_multiple_of,
737
+ verbose=verbose,
738
+ **kwargs,
739
+ )
740
+
741
+ return self._batch_encode_plus_boxes(
742
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
743
+ is_pair=is_pair,
744
+ boxes=boxes,
745
+ word_labels=word_labels,
746
+ add_special_tokens=add_special_tokens,
747
+ padding_strategy=padding_strategy,
748
+ truncation_strategy=truncation_strategy,
749
+ max_length=max_length,
750
+ stride=stride,
751
+ is_split_into_words=is_split_into_words,
752
+ pad_to_multiple_of=pad_to_multiple_of,
753
+ padding_side=padding_side,
754
+ return_tensors=return_tensors,
755
+ return_token_type_ids=return_token_type_ids,
756
+ return_attention_mask=return_attention_mask,
757
+ return_overflowing_tokens=return_overflowing_tokens,
758
+ return_special_tokens_mask=return_special_tokens_mask,
759
+ return_offsets_mapping=return_offsets_mapping,
760
+ return_length=return_length,
761
+ verbose=verbose,
762
+ **kwargs,
763
+ )
764
+
765
+ def encode_boxes(
766
+ self,
767
+ text: Union[TextInput, PreTokenizedInput, EncodedInput],
768
+ text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
769
+ boxes: Optional[List[List[int]]] = None,
770
+ word_labels: Optional[List[List[int]]] = None,
771
+ add_special_tokens: bool = True,
772
+ padding: Union[bool, str, PaddingStrategy] = False,
773
+ truncation: Union[bool, str, TruncationStrategy] = None,
774
+ max_length: Optional[int] = None,
775
+ stride: int = 0,
776
+ return_tensors: Optional[Union[str, TensorType]] = None,
777
+ **kwargs,
778
+ ) -> List[int]:
779
+ """
780
+ Args:
781
+ Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. Same as doing
782
+ `self.convert_tokens_to_ids(self.tokenize(text))`.
783
+ text (`str`, `List[str]` or `List[int]`):
784
+ The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
785
+ `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
786
+ method).
787
+ text_pair (`str`, `List[str]` or `List[int]`, *optional*):
788
+ Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
789
+ the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
790
+ method).
791
+ """
792
+ encoded_inputs = self.encode_plus_boxes(
793
+ text,
794
+ text_pair=text_pair,
795
+ boxes=boxes,
796
+ word_labels=word_labels,
797
+ add_special_tokens=add_special_tokens,
798
+ padding=padding,
799
+ truncation=truncation,
800
+ max_length=max_length,
801
+ stride=stride,
802
+ return_tensors=return_tensors,
803
+ **kwargs,
804
+ )
805
+
806
+ return encoded_inputs["input_ids"]
807
+
808
+ def encode_plus_boxes(
809
+ self,
810
+ text: Union[TextInput, PreTokenizedInput],
811
+ text_pair: Optional[PreTokenizedInput] = None,
812
+ boxes: Optional[List[List[int]]] = None,
813
+ word_labels: Optional[List[List[int]]] = None,
814
+ add_special_tokens: bool = True,
815
+ padding: Union[bool, str, PaddingStrategy] = False,
816
+ truncation: Union[bool, str, TruncationStrategy] = None,
817
+ max_length: Optional[int] = None,
818
+ stride: int = 0,
819
+ is_split_into_words: bool = False,
820
+ pad_to_multiple_of: Optional[int] = None,
821
+ padding_side: Optional[str] = None,
822
+ return_tensors: Optional[Union[str, TensorType]] = None,
823
+ return_token_type_ids: Optional[bool] = None,
824
+ return_attention_mask: Optional[bool] = None,
825
+ return_overflowing_tokens: bool = False,
826
+ return_special_tokens_mask: bool = False,
827
+ return_offsets_mapping: bool = False,
828
+ return_length: bool = False,
829
+ verbose: bool = True,
830
+ **kwargs,
831
+ ) -> BatchEncoding:
832
+ """
833
+ Tokenize and prepare for the model a sequence or a pair of sequences.
834
+
835
+ <Tip warning={true}>
836
+
837
+ This method is deprecated, `__call__` should be used instead.
838
+
839
+ </Tip>
840
+
841
+ Args:
842
+ text (`str`, `List[str]` or (for non-fast tokenizers) `List[int]`):
843
+ The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
844
+ `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
845
+ method).
846
+ text_pair (`str`, `List[str]` or `List[int]`, *optional*):
847
+ Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
848
+ the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
849
+ method).
850
+ """
851
+
852
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
853
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
854
+ padding=padding,
855
+ truncation=truncation,
856
+ max_length=max_length,
857
+ pad_to_multiple_of=pad_to_multiple_of,
858
+ verbose=verbose,
859
+ **kwargs,
860
+ )
861
+
862
+ return self._encode_plus_boxes(
863
+ text=text,
864
+ text_pair=text_pair,
865
+ boxes=boxes,
866
+ word_labels=word_labels,
867
+ add_special_tokens=add_special_tokens,
868
+ padding_strategy=padding_strategy,
869
+ truncation_strategy=truncation_strategy,
870
+ max_length=max_length,
871
+ stride=stride,
872
+ is_split_into_words=is_split_into_words,
873
+ pad_to_multiple_of=pad_to_multiple_of,
874
+ padding_side=padding_side,
875
+ return_tensors=return_tensors,
876
+ return_token_type_ids=return_token_type_ids,
877
+ return_attention_mask=return_attention_mask,
878
+ return_overflowing_tokens=return_overflowing_tokens,
879
+ return_special_tokens_mask=return_special_tokens_mask,
880
+ return_offsets_mapping=return_offsets_mapping,
881
+ return_length=return_length,
882
+ verbose=verbose,
883
+ **kwargs,
884
+ )
885
+
886
+ def _batch_encode_plus_boxes(
887
+ self,
888
+ batch_text_or_text_pairs: Union[
889
+ List[TextInput],
890
+ List[TextInputPair],
891
+ List[PreTokenizedInput],
892
+ ],
893
+ is_pair: bool = None,
894
+ boxes: Optional[List[List[List[int]]]] = None,
895
+ word_labels: Optional[List[List[int]]] = None,
896
+ add_special_tokens: bool = True,
897
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
898
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
899
+ max_length: Optional[int] = None,
900
+ stride: int = 0,
901
+ pad_to_multiple_of: Optional[int] = None,
902
+ padding_side: Optional[str] = None,
903
+ return_tensors: Optional[Union[str, TensorType]] = None,
904
+ return_token_type_ids: Optional[bool] = None,
905
+ return_attention_mask: Optional[bool] = None,
906
+ return_overflowing_tokens: bool = False,
907
+ return_special_tokens_mask: bool = False,
908
+ return_offsets_mapping: bool = False,
909
+ return_length: bool = False,
910
+ verbose: bool = True,
911
+ **kwargs,
912
+ ) -> BatchEncoding:
913
+ if return_offsets_mapping:
914
+ raise NotImplementedError(
915
+ "return_offset_mapping is not available when using Python tokenizers. "
916
+ "To use this feature, change your tokenizer to one deriving from "
917
+ "transformers.PreTrainedTokenizerFast."
918
+ )
919
+
920
+ batch_outputs = self._batch_prepare_for_model_boxes(
921
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
922
+ is_pair=is_pair,
923
+ boxes=boxes,
924
+ word_labels=word_labels,
925
+ add_special_tokens=add_special_tokens,
926
+ padding_strategy=padding_strategy,
927
+ truncation_strategy=truncation_strategy,
928
+ max_length=max_length,
929
+ stride=stride,
930
+ pad_to_multiple_of=pad_to_multiple_of,
931
+ padding_side=padding_side,
932
+ return_attention_mask=return_attention_mask,
933
+ return_token_type_ids=return_token_type_ids,
934
+ return_overflowing_tokens=return_overflowing_tokens,
935
+ return_special_tokens_mask=return_special_tokens_mask,
936
+ return_length=return_length,
937
+ return_tensors=return_tensors,
938
+ verbose=verbose,
939
+ )
940
+
941
+ return BatchEncoding(batch_outputs)
942
+
943
+ @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
944
+ def _batch_prepare_for_model_boxes(
945
+ self,
946
+ batch_text_or_text_pairs,
947
+ is_pair: bool = None,
948
+ boxes: Optional[List[List[int]]] = None,
949
+ word_labels: Optional[List[List[int]]] = None,
950
+ add_special_tokens: bool = True,
951
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
952
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
953
+ max_length: Optional[int] = None,
954
+ stride: int = 0,
955
+ pad_to_multiple_of: Optional[int] = None,
956
+ padding_side: Optional[str] = None,
957
+ return_tensors: Optional[str] = None,
958
+ return_token_type_ids: Optional[bool] = None,
959
+ return_attention_mask: Optional[bool] = None,
960
+ return_overflowing_tokens: bool = False,
961
+ return_special_tokens_mask: bool = False,
962
+ return_length: bool = False,
963
+ verbose: bool = True,
964
+ ) -> BatchEncoding:
965
+ """
966
+ Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
967
+ adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
968
+ manages a moving window (with user defined stride) for overflowing tokens
969
+
970
+ Args:
971
+ batch_ids_pairs: list of tokenized input ids or input ids pairs
972
+ """
973
+
974
+ batch_outputs = {}
975
+ for idx, example in enumerate(zip(batch_text_or_text_pairs, boxes)):
976
+ batch_text_or_text_pair, boxes_example = example
977
+ outputs = self.prepare_for_model_boxes(
978
+ batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair,
979
+ batch_text_or_text_pair[1] if is_pair else None,
980
+ boxes_example,
981
+ word_labels=word_labels[idx] if word_labels is not None else None,
982
+ add_special_tokens=add_special_tokens,
983
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
984
+ truncation=truncation_strategy.value,
985
+ max_length=max_length,
986
+ stride=stride,
987
+ pad_to_multiple_of=None, # we pad in batch afterward
988
+ padding_side=None, # we pad in batch afterward
989
+ return_attention_mask=False, # we pad in batch afterward
990
+ return_token_type_ids=return_token_type_ids,
991
+ return_overflowing_tokens=return_overflowing_tokens,
992
+ return_special_tokens_mask=return_special_tokens_mask,
993
+ return_length=return_length,
994
+ return_tensors=None, # We convert the whole batch to tensors at the end
995
+ prepend_batch_axis=False,
996
+ verbose=verbose,
997
+ )
998
+
999
+ for key, value in outputs.items():
1000
+ if key not in batch_outputs:
1001
+ batch_outputs[key] = []
1002
+ batch_outputs[key].append(value)
1003
+
1004
+ batch_outputs = self.pad(
1005
+ batch_outputs,
1006
+ padding=padding_strategy.value,
1007
+ max_length=max_length,
1008
+ pad_to_multiple_of=pad_to_multiple_of,
1009
+ padding_side=padding_side,
1010
+ return_attention_mask=return_attention_mask,
1011
+ )
1012
+
1013
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
1014
+
1015
+ return batch_outputs
1016
+
1017
+ def _encode_plus_boxes(
1018
+ self,
1019
+ text: Union[TextInput, PreTokenizedInput],
1020
+ text_pair: Optional[PreTokenizedInput] = None,
1021
+ boxes: Optional[List[List[int]]] = None,
1022
+ word_labels: Optional[List[int]] = None,
1023
+ add_special_tokens: bool = True,
1024
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1025
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
1026
+ max_length: Optional[int] = None,
1027
+ stride: int = 0,
1028
+ pad_to_multiple_of: Optional[int] = None,
1029
+ padding_side: Optional[str] = None,
1030
+ return_tensors: Optional[Union[str, TensorType]] = None,
1031
+ return_token_type_ids: Optional[bool] = None,
1032
+ return_attention_mask: Optional[bool] = None,
1033
+ return_overflowing_tokens: bool = False,
1034
+ return_special_tokens_mask: bool = False,
1035
+ return_offsets_mapping: bool = False,
1036
+ return_length: bool = False,
1037
+ verbose: bool = True,
1038
+ **kwargs,
1039
+ ) -> BatchEncoding:
1040
+ if return_offsets_mapping:
1041
+ raise NotImplementedError(
1042
+ "return_offset_mapping is not available when using Python tokenizers. "
1043
+ "To use this feature, change your tokenizer to one deriving from "
1044
+ "transformers.PreTrainedTokenizerFast. "
1045
+ "More information on available tokenizers at "
1046
+ "https://github.com/huggingface/transformers/pull/2674"
1047
+ )
1048
+
1049
+ return self.prepare_for_model_boxes(
1050
+ text=text,
1051
+ text_pair=text_pair,
1052
+ boxes=boxes,
1053
+ word_labels=word_labels,
1054
+ add_special_tokens=add_special_tokens,
1055
+ padding=padding_strategy.value,
1056
+ truncation=truncation_strategy.value,
1057
+ max_length=max_length,
1058
+ stride=stride,
1059
+ pad_to_multiple_of=pad_to_multiple_of,
1060
+ padding_side=padding_side,
1061
+ return_tensors=return_tensors,
1062
+ prepend_batch_axis=True,
1063
+ return_attention_mask=return_attention_mask,
1064
+ return_token_type_ids=return_token_type_ids,
1065
+ return_overflowing_tokens=return_overflowing_tokens,
1066
+ return_special_tokens_mask=return_special_tokens_mask,
1067
+ return_length=return_length,
1068
+ verbose=verbose,
1069
+ )
1070
+
1071
+ @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
1072
+ def prepare_for_model_boxes(
1073
+ self,
1074
+ text: Union[TextInput, PreTokenizedInput],
1075
+ text_pair: Optional[PreTokenizedInput] = None,
1076
+ boxes: Optional[List[List[int]]] = None,
1077
+ word_labels: Optional[List[int]] = None,
1078
+ add_special_tokens: bool = True,
1079
+ padding: Union[bool, str, PaddingStrategy] = False,
1080
+ truncation: Union[bool, str, TruncationStrategy] = None,
1081
+ max_length: Optional[int] = None,
1082
+ stride: int = 0,
1083
+ pad_to_multiple_of: Optional[int] = None,
1084
+ padding_side: Optional[str] = None,
1085
+ return_tensors: Optional[Union[str, TensorType]] = None,
1086
+ return_token_type_ids: Optional[bool] = None,
1087
+ return_attention_mask: Optional[bool] = None,
1088
+ return_overflowing_tokens: bool = False,
1089
+ return_special_tokens_mask: bool = False,
1090
+ return_offsets_mapping: bool = False,
1091
+ return_length: bool = False,
1092
+ verbose: bool = True,
1093
+ prepend_batch_axis: bool = False,
1094
+ **kwargs,
1095
+ ) -> BatchEncoding:
1096
+ """
1097
+ Prepares a sequence or a pair of sequences so that it can be used by the model. It adds special tokens,
1098
+ truncates sequences if overflowing while taking into account the special tokens and manages a moving window
1099
+ (with user defined stride) for overflowing tokens.
1100
+
1101
+ Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into
1102
+ token-level `labels`. The word label is used for the first token of the word, while remaining tokens are
1103
+ labeled with -100, such that they will be ignored by the loss function.
1104
+
1105
+ Args:
1106
+ text (`str`, `List[str]`, `List[List[str]]`):
1107
+ The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
1108
+ text_pair (`List[str]` or `List[int]`, *optional*):
1109
+ Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
1110
+ list of list of strings (words of a batch of examples).
1111
+ """
1112
+
1113
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
1114
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
1115
+ padding=padding,
1116
+ truncation=truncation,
1117
+ max_length=max_length,
1118
+ pad_to_multiple_of=pad_to_multiple_of,
1119
+ verbose=verbose,
1120
+ **kwargs,
1121
+ )
1122
+
1123
+ tokens = []
1124
+ pair_tokens = []
1125
+ token_boxes = []
1126
+ pair_token_boxes = []
1127
+ labels = []
1128
+
1129
+ if text_pair is None:
1130
+ if word_labels is None:
1131
+ # CASE 1: document image classification (training + inference) + CASE 2: token classification (inference)
1132
+ for word, box in zip(text, boxes):
1133
+ if len(word) < 1: # skip empty words
1134
+ continue
1135
+ word_tokens = self.tokenize(word)
1136
+ tokens.extend(word_tokens)
1137
+ token_boxes.extend([box] * len(word_tokens))
1138
+ else:
1139
+ # CASE 2: token classification (training)
1140
+ for word, box, label in zip(text, boxes, word_labels):
1141
+ if len(word) < 1: # skip empty words
1142
+ continue
1143
+ word_tokens = self.tokenize(word)
1144
+ tokens.extend(word_tokens)
1145
+ token_boxes.extend([box] * len(word_tokens))
1146
+ if self.only_label_first_subword:
1147
+ # Use the real label id for the first token of the word, and padding ids for the remaining tokens
1148
+ labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
1149
+ else:
1150
+ labels.extend([label] * len(word_tokens))
1151
+ else:
1152
+ # CASE 3: document visual question answering (inference)
1153
+ # text = question
1154
+ # text_pair = words
1155
+ tokens = self.tokenize(text)
1156
+ token_boxes = [self.pad_token_box for _ in range(len(tokens))]
1157
+
1158
+ for word, box in zip(text_pair, boxes):
1159
+ if len(word) < 1: # skip empty words
1160
+ continue
1161
+ word_tokens = self.tokenize(word)
1162
+ pair_tokens.extend(word_tokens)
1163
+ pair_token_boxes.extend([box] * len(word_tokens))
1164
+
1165
+ # Create ids + pair_ids
1166
+ ids = self.convert_tokens_to_ids(tokens)
1167
+ pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else None
1168
+
1169
+ # Compute the total size of the returned encodings
1170
+ pair = bool(pair_ids is not None)
1171
+ len_ids = len(ids)
1172
+ len_pair_ids = len(pair_ids) if pair else 0
1173
+ total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
1174
+
1175
+ # Truncation: Handle max sequence length
1176
+ overflowing_tokens = []
1177
+ overflowing_token_boxes = []
1178
+ overflowing_labels = []
1179
+ if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
1180
+ (
1181
+ ids,
1182
+ token_boxes,
1183
+ pair_ids,
1184
+ pair_token_boxes,
1185
+ labels,
1186
+ overflowing_tokens,
1187
+ overflowing_token_boxes,
1188
+ overflowing_labels,
1189
+ ) = self.truncate_sequences(
1190
+ ids,
1191
+ token_boxes,
1192
+ pair_ids=pair_ids,
1193
+ pair_token_boxes=pair_token_boxes,
1194
+ labels=labels,
1195
+ num_tokens_to_remove=total_len - max_length,
1196
+ truncation_strategy=truncation_strategy,
1197
+ stride=stride,
1198
+ )
1199
+
1200
+ if return_token_type_ids and not add_special_tokens:
1201
+ raise ValueError(
1202
+ "Asking to return token_type_ids while setting add_special_tokens to False "
1203
+ "results in an undefined behavior. Please set add_special_tokens to True or "
1204
+ "set return_token_type_ids to None."
1205
+ )
1206
+
1207
+ # Load from model defaults
1208
+ if return_token_type_ids is None:
1209
+ return_token_type_ids = "token_type_ids" in self.model_input_names
1210
+ if return_attention_mask is None:
1211
+ return_attention_mask = "attention_mask" in self.model_input_names
1212
+
1213
+ encoded_inputs = {}
1214
+
1215
+ if return_overflowing_tokens:
1216
+ encoded_inputs["overflowing_tokens"] = overflowing_tokens
1217
+ encoded_inputs["overflowing_token_boxes"] = overflowing_token_boxes
1218
+ encoded_inputs["overflowing_labels"] = overflowing_labels
1219
+ encoded_inputs["num_truncated_tokens"] = total_len - max_length
1220
+
1221
+ # Add special tokens
1222
+ if add_special_tokens:
1223
+ sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
1224
+ token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
1225
+ token_boxes = token_boxes + [self.sep_token_box]
1226
+ if pair_token_boxes:
1227
+ pair_token_boxes = pair_token_boxes + [self.sep_token_box]
1228
+ if labels:
1229
+ labels = labels + [self.pad_token_label]
1230
+ else:
1231
+ sequence = ids + pair_ids if pair else ids
1232
+ token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
1233
+
1234
+ # Build output dictionary
1235
+ encoded_inputs["input_ids"] = sequence
1236
+ encoded_inputs["bbox"] = token_boxes + pair_token_boxes
1237
+ if return_token_type_ids:
1238
+ encoded_inputs["token_type_ids"] = token_type_ids
1239
+ if return_special_tokens_mask:
1240
+ if add_special_tokens:
1241
+ encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
1242
+ else:
1243
+ encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
1244
+
1245
+ if labels:
1246
+ encoded_inputs["labels"] = labels
1247
+
1248
+ # Check lengths
1249
+ self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
1250
+
1251
+ # Padding
1252
+ if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
1253
+ encoded_inputs = self.pad(
1254
+ encoded_inputs,
1255
+ max_length=max_length,
1256
+ padding=padding_strategy.value,
1257
+ pad_to_multiple_of=pad_to_multiple_of,
1258
+ padding_side=padding_side,
1259
+ return_attention_mask=return_attention_mask,
1260
+ )
1261
+
1262
+ if return_length:
1263
+ encoded_inputs["length"] = len(encoded_inputs["input_ids"])
1264
+
1265
+ batch_outputs = BatchEncoding(
1266
+ encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
1267
+ )
1268
+
1269
+ return batch_outputs
1270
+
1271
+ # Copied from transformers.models.layoutxlm.tokenization_layoutxlm.LayoutXLMTokenizer.truncate_sequences
1272
+ def truncate_sequences(
1273
+ self,
1274
+ ids: List[int],
1275
+ token_boxes: List[List[int]],
1276
+ pair_ids: Optional[List[int]] = None,
1277
+ pair_token_boxes: Optional[List[List[int]]] = None,
1278
+ labels: Optional[List[int]] = None,
1279
+ num_tokens_to_remove: int = 0,
1280
+ truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
1281
+ stride: int = 0,
1282
+ ) -> Tuple[List[int], List[int], List[int]]:
1283
+ """
1284
+ Truncates a sequence pair in-place following the strategy.
1285
+
1286
+ Args:
1287
+ ids (`List[int]`):
1288
+ Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
1289
+ `convert_tokens_to_ids` methods.
1290
+ token_boxes (`List[List[int]]`):
1291
+ Bounding boxes of the first sequence.
1292
+ pair_ids (`List[int]`, *optional*):
1293
+ Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
1294
+ and `convert_tokens_to_ids` methods.
1295
+ pair_token_boxes (`List[List[int]]`, *optional*):
1296
+ Bounding boxes of the second sequence.
1297
+ labels (`List[int]`, *optional*):
1298
+ Labels of the first sequence (for token classification tasks).
1299
+ num_tokens_to_remove (`int`, *optional*, defaults to 0):
1300
+ Number of tokens to remove using the truncation strategy.
1301
+ truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
1302
+ The strategy to follow for truncation. Can be:
1303
+
1304
+ - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
1305
+ maximum acceptable input length for the model if that argument is not provided. This will truncate
1306
+ token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
1307
+ batch of pairs) is provided.
1308
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
1309
+ maximum acceptable input length for the model if that argument is not provided. This will only
1310
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
1311
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
1312
+ maximum acceptable input length for the model if that argument is not provided. This will only
1313
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
1314
+ - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
1315
+ than the model maximum admissible input size).
1316
+ stride (`int`, *optional*, defaults to 0):
1317
+ If set to a positive number, the overflowing tokens returned will contain some tokens from the main
1318
+ sequence returned. The value of this argument defines the number of additional tokens.
1319
+
1320
+ Returns:
1321
+ `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
1322
+ overflowing tokens.
1323
+ """
1324
+ if num_tokens_to_remove <= 0:
1325
+ return ids, token_boxes, pair_ids, pair_token_boxes, labels, [], [], []
1326
+
1327
+ if not isinstance(truncation_strategy, TruncationStrategy):
1328
+ truncation_strategy = TruncationStrategy(truncation_strategy)
1329
+
1330
+ overflowing_tokens = []
1331
+ overflowing_token_boxes = []
1332
+ overflowing_labels = []
1333
+ if truncation_strategy == TruncationStrategy.LONGEST_FIRST:
1334
+ for _ in range(num_tokens_to_remove):
1335
+ if pair_ids is None or len(ids) > len(pair_ids):
1336
+ if not overflowing_tokens:
1337
+ window_len = min(len(ids), stride + 1)
1338
+ else:
1339
+ window_len = 1
1340
+ overflowing_tokens.extend(ids[-window_len:])
1341
+ overflowing_token_boxes.extend(token_boxes[-window_len:])
1342
+ overflowing_labels.extend(labels[-window_len:])
1343
+ ids = ids[:-1]
1344
+ token_boxes = token_boxes[:-1]
1345
+ labels = labels[:-1]
1346
+ else:
1347
+ if not overflowing_tokens:
1348
+ window_len = min(len(pair_ids), stride + 1)
1349
+ else:
1350
+ window_len = 1
1351
+ overflowing_tokens.extend(pair_ids[-window_len:])
1352
+ overflowing_token_boxes.extend(pair_token_boxes[-window_len:])
1353
+ pair_ids = pair_ids[:-1]
1354
+ pair_token_boxes = pair_token_boxes[:-1]
1355
+ elif truncation_strategy == TruncationStrategy.ONLY_FIRST:
1356
+ if len(ids) > num_tokens_to_remove:
1357
+ window_len = min(len(ids), stride + num_tokens_to_remove)
1358
+ overflowing_tokens = ids[-window_len:]
1359
+ overflowing_token_boxes = token_boxes[-window_len:]
1360
+ overflowing_labels = labels[-window_len:]
1361
+ ids = ids[:-num_tokens_to_remove]
1362
+ token_boxes = token_boxes[:-num_tokens_to_remove]
1363
+ labels = labels[:-num_tokens_to_remove]
1364
+ else:
1365
+ logger.error(
1366
+ f"We need to remove {num_tokens_to_remove} to truncate the input "
1367
+ f"but the first sequence has a length {len(ids)}. "
1368
+ f"Please select another truncation strategy than {truncation_strategy}, "
1369
+ "for instance 'longest_first' or 'only_second'."
1370
+ )
1371
+ elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
1372
+ if len(pair_ids) > num_tokens_to_remove:
1373
+ window_len = min(len(pair_ids), stride + num_tokens_to_remove)
1374
+ overflowing_tokens = pair_ids[-window_len:]
1375
+ overflowing_token_boxes = pair_token_boxes[-window_len:]
1376
+ pair_ids = pair_ids[:-num_tokens_to_remove]
1377
+ pair_token_boxes = pair_token_boxes[:-num_tokens_to_remove]
1378
+ else:
1379
+ logger.error(
1380
+ f"We need to remove {num_tokens_to_remove} to truncate the input "
1381
+ f"but the second sequence has a length {len(pair_ids)}. "
1382
+ f"Please select another truncation strategy than {truncation_strategy}, "
1383
+ "for instance 'longest_first' or 'only_first'."
1384
+ )
1385
+
1386
+ return (
1387
+ ids,
1388
+ token_boxes,
1389
+ pair_ids,
1390
+ pair_token_boxes,
1391
+ labels,
1392
+ overflowing_tokens,
1393
+ overflowing_token_boxes,
1394
+ overflowing_labels,
1395
+ )
1396
+
1397
+ # Copied from transformers.models.layoutxlm.tokenization_layoutxlm.LayoutXLMTokenizer._pad
1398
+ def _pad(
1399
+ self,
1400
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
1401
+ max_length: Optional[int] = None,
1402
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1403
+ pad_to_multiple_of: Optional[int] = None,
1404
+ padding_side: Optional[str] = None,
1405
+ return_attention_mask: Optional[bool] = None,
1406
+ ) -> dict:
1407
+ """
1408
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
1409
+
1410
+ Args:
1411
+ encoded_inputs:
1412
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
1413
+ max_length: maximum length of the returned list and optionally padding length (see below).
1414
+ Will truncate by taking into account the special tokens.
1415
+ padding_strategy: PaddingStrategy to use for padding.
1416
+
1417
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
1418
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
1419
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
1420
+ The tokenizer padding sides are defined in self.padding_side:
1421
+
1422
+ - 'left': pads on the left of the sequences
1423
+ - 'right': pads on the right of the sequences
1424
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
1425
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
1426
+ `>= 7.5` (Volta).
1427
+ padding_side (`str`, *optional*):
1428
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
1429
+ Default value is picked from the class attribute of the same name.
1430
+ return_attention_mask:
1431
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
1432
+ """
1433
+ # Load from model defaults
1434
+ if return_attention_mask is None:
1435
+ return_attention_mask = "attention_mask" in self.model_input_names
1436
+
1437
+ required_input = encoded_inputs[self.model_input_names[0]]
1438
+
1439
+ if padding_strategy == PaddingStrategy.LONGEST:
1440
+ max_length = len(required_input)
1441
+
1442
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
1443
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
1444
+
1445
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
1446
+
1447
+ # Initialize attention mask if not present.
1448
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
1449
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
1450
+
1451
+ if needs_to_be_padded:
1452
+ difference = max_length - len(required_input)
1453
+ padding_side = padding_side if padding_side is not None else self.padding_side
1454
+ if padding_side == "right":
1455
+ if return_attention_mask:
1456
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
1457
+ if "token_type_ids" in encoded_inputs:
1458
+ encoded_inputs["token_type_ids"] = (
1459
+ encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
1460
+ )
1461
+ if "bbox" in encoded_inputs:
1462
+ encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
1463
+ if "labels" in encoded_inputs:
1464
+ encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
1465
+ if "special_tokens_mask" in encoded_inputs:
1466
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
1467
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
1468
+ elif padding_side == "left":
1469
+ if return_attention_mask:
1470
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
1471
+ if "token_type_ids" in encoded_inputs:
1472
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
1473
+ "token_type_ids"
1474
+ ]
1475
+ if "bbox" in encoded_inputs:
1476
+ encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
1477
+ if "labels" in encoded_inputs:
1478
+ encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
1479
+ if "special_tokens_mask" in encoded_inputs:
1480
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
1481
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
1482
+ else:
1483
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
1484
+
1485
+ return encoded_inputs
1486
+
1487
+
1488
+ __all__ = ["UdopTokenizer"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/udop/tokenization_udop_fast.py ADDED
@@ -0,0 +1,1031 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License
15
+ """Tokenization classes for UDOP model."""
16
+
17
+ import os
18
+ from shutil import copyfile
19
+ from typing import Dict, List, Optional, Tuple, Union
20
+
21
+ from ...tokenization_utils_base import (
22
+ BatchEncoding,
23
+ EncodedInput,
24
+ PreTokenizedInput,
25
+ TextInput,
26
+ TextInputPair,
27
+ TruncationStrategy,
28
+ )
29
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
30
+ from ...utils import PaddingStrategy, TensorType, add_end_docstrings, is_sentencepiece_available, logging
31
+
32
+
33
+ if is_sentencepiece_available():
34
+ from .tokenization_udop import UdopTokenizer
35
+ else:
36
+ UdopTokenizer = None
37
+
38
+
39
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ UDOP_ENCODE_KWARGS_DOCSTRING = r"""
45
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
46
+ Whether or not to encode the sequences with the special tokens relative to their model.
47
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
48
+ Activates and controls padding. Accepts the following values:
49
+
50
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
51
+ sequence if provided).
52
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
53
+ acceptable input length for the model if that argument is not provided.
54
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
55
+ lengths).
56
+ truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
57
+ Activates and controls truncation. Accepts the following values:
58
+
59
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
60
+ to the maximum acceptable input length for the model if that argument is not provided. This will
61
+ truncate token by token, removing a token from the longest sequence in the pair if a pair of
62
+ sequences (or a batch of pairs) is provided.
63
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
64
+ maximum acceptable input length for the model if that argument is not provided. This will only
65
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
66
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
67
+ maximum acceptable input length for the model if that argument is not provided. This will only
68
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
69
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
70
+ greater than the model maximum admissible input size).
71
+ max_length (`int`, *optional*):
72
+ Controls the maximum length to use by one of the truncation/padding parameters.
73
+
74
+ If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
75
+ is required by one of the truncation/padding parameters. If the model has no specific maximum input
76
+ length (like XLNet) truncation/padding to a maximum length will be deactivated.
77
+ stride (`int`, *optional*, defaults to 0):
78
+ If set to a number along with `max_length`, the overflowing tokens returned when
79
+ `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
80
+ returned to provide some overlap between truncated and overflowing sequences. The value of this
81
+ argument defines the number of overlapping tokens.
82
+ pad_to_multiple_of (`int`, *optional*):
83
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
84
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
85
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
86
+ If set, will return tensors instead of list of python integers. Acceptable values are:
87
+
88
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
89
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
90
+ - `'np'`: Return Numpy `np.ndarray` objects.
91
+ return_token_type_ids (`bool`, *optional*):
92
+ Whether to return token type IDs. If left to the default, will return the token type IDs according to
93
+ the specific tokenizer's default, defined by the `return_outputs` attribute.
94
+
95
+ [What are token type IDs?](../glossary#token-type-ids)
96
+ return_attention_mask (`bool`, *optional*):
97
+ Whether to return the attention mask. If left to the default, will return the attention mask according
98
+ to the specific tokenizer's default, defined by the `return_outputs` attribute.
99
+
100
+ [What are attention masks?](../glossary#attention-mask)
101
+ return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
102
+ Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
103
+ of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
104
+ of returning overflowing tokens.
105
+ return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
106
+ Whether or not to return special tokens mask information.
107
+ return_offsets_mapping (`bool`, *optional*, defaults to `False`):
108
+ Whether or not to return `(char_start, char_end)` for each token.
109
+
110
+ This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
111
+ Python's tokenizer, this method will raise `NotImplementedError`.
112
+ return_length (`bool`, *optional*, defaults to `False`):
113
+ Whether or not to return the lengths of the encoded inputs.
114
+ verbose (`bool`, *optional*, defaults to `True`):
115
+ Whether or not to print more information and warnings.
116
+ **kwargs: passed to the `self.tokenize()` method
117
+
118
+ Return:
119
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
120
+
121
+ - **input_ids** -- List of token ids to be fed to a model.
122
+
123
+ [What are input IDs?](../glossary#input-ids)
124
+
125
+ - **bbox** -- List of bounding boxes to be fed to a model.
126
+
127
+ - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
128
+ if *"token_type_ids"* is in `self.model_input_names`).
129
+
130
+ [What are token type IDs?](../glossary#token-type-ids)
131
+
132
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
133
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
134
+
135
+ [What are attention masks?](../glossary#attention-mask)
136
+
137
+ - **labels** -- List of labels to be fed to a model. (when `word_labels` is specified).
138
+ - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
139
+ `return_overflowing_tokens=True`).
140
+ - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
141
+ `return_overflowing_tokens=True`).
142
+ - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
143
+ regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
144
+ - **length** -- The length of the inputs (when `return_length=True`).
145
+ """
146
+
147
+
148
+ class UdopTokenizerFast(PreTrainedTokenizerFast):
149
+ """
150
+ Construct a "fast" UDOP tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
151
+ [`LayoutXLMTokenizer`] and [`T5Tokenizer`]. Based on
152
+ [BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
153
+
154
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
155
+ refer to this superclass for more information regarding those methods.
156
+
157
+ Args:
158
+ vocab_file (`str`, *optional*):
159
+ Path to the vocabulary file.
160
+
161
+ tokenizer_file (`str`, *optional*):
162
+ Path to the tokenizer file.
163
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
164
+ The end of sequence token.
165
+
166
+ <Tip>
167
+
168
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
169
+ The token used is the `sep_token`.
170
+
171
+ </Tip>
172
+
173
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
174
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
175
+ sequence classification or for a text and a question for question answering. It is also used as the last
176
+ token of a sequence built with special tokens.
177
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
178
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
179
+ token instead.
180
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
181
+ The token used for padding, for example when batching sequences of different lengths.
182
+ sep_token_box (`List[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
183
+ The bounding box to use for the special [SEP] token.
184
+ pad_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
185
+ The bounding box to use for the special [PAD] token.
186
+ pad_token_label (`int`, *optional*, defaults to -100):
187
+ The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
188
+ CrossEntropyLoss.
189
+ only_label_first_subword (`bool`, *optional*, defaults to `True`):
190
+ Whether or not to only label the first subword, in case word labels are provided.
191
+ additional_special_tokens (`List[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
192
+ Additional special tokens used by the tokenizer.
193
+ """
194
+
195
+ vocab_files_names = VOCAB_FILES_NAMES
196
+ model_input_names = ["input_ids", "attention_mask"]
197
+ slow_tokenizer_class = UdopTokenizer
198
+
199
+ def __init__(
200
+ self,
201
+ vocab_file=None,
202
+ tokenizer_file=None,
203
+ eos_token="</s>",
204
+ sep_token="</s>",
205
+ unk_token="<unk>",
206
+ pad_token="<pad>",
207
+ sep_token_box=[1000, 1000, 1000, 1000],
208
+ pad_token_box=[0, 0, 0, 0],
209
+ pad_token_label=-100,
210
+ only_label_first_subword=True,
211
+ additional_special_tokens=None,
212
+ **kwargs,
213
+ ):
214
+ super().__init__(
215
+ vocab_file,
216
+ tokenizer_file=tokenizer_file,
217
+ eos_token=eos_token,
218
+ sep_token=sep_token,
219
+ unk_token=unk_token,
220
+ pad_token=pad_token,
221
+ sep_token_box=sep_token_box,
222
+ pad_token_box=pad_token_box,
223
+ pad_token_label=pad_token_label,
224
+ only_label_first_subword=only_label_first_subword,
225
+ additional_special_tokens=additional_special_tokens,
226
+ **kwargs,
227
+ )
228
+
229
+ self.vocab_file = vocab_file
230
+
231
+ # additional properties
232
+ self.sep_token_box = sep_token_box
233
+ self.pad_token_box = pad_token_box
234
+ self.pad_token_label = pad_token_label
235
+ self.only_label_first_subword = only_label_first_subword
236
+
237
+ @property
238
+ def can_save_slow_tokenizer(self) -> bool:
239
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
240
+
241
+ @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
242
+ def __call__(
243
+ self,
244
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
245
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
246
+ boxes: Union[List[List[int]], List[List[List[int]]]] = None,
247
+ word_labels: Optional[Union[List[int], List[List[int]]]] = None,
248
+ text_target: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
249
+ text_pair_target: Optional[
250
+ Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]
251
+ ] = None,
252
+ **kwargs,
253
+ ) -> BatchEncoding:
254
+ if text is None and text_target is None:
255
+ raise ValueError("You need to specify either `text` or `text_target`.")
256
+ if text is not None:
257
+ # The context manager will send the inputs as normal texts and not text_target, but we shouldn't change the
258
+ # input mode in this case.
259
+ if not self._in_target_context_manager:
260
+ self._switch_to_input_mode()
261
+ encodings = self.call_boxes(text=text, text_pair=text_pair, boxes=boxes, word_labels=word_labels, **kwargs)
262
+ if text_target is not None:
263
+ self._switch_to_target_mode()
264
+ target_encodings = self._call_one(text=text_target, text_pair=text_pair_target, **kwargs)
265
+ # Leave back tokenizer in input mode
266
+ self._switch_to_input_mode()
267
+
268
+ if text_target is None:
269
+ return encodings
270
+ elif text is None:
271
+ return target_encodings
272
+ else:
273
+ encodings["labels"] = target_encodings["input_ids"]
274
+ return encodings
275
+
276
+ @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
277
+ def call_boxes(
278
+ self,
279
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
280
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
281
+ boxes: Union[List[List[int]], List[List[List[int]]]] = None,
282
+ word_labels: Optional[Union[List[int], List[List[int]]]] = None,
283
+ add_special_tokens: bool = True,
284
+ padding: Union[bool, str, PaddingStrategy] = False,
285
+ truncation: Union[bool, str, TruncationStrategy] = None,
286
+ max_length: Optional[int] = None,
287
+ stride: int = 0,
288
+ pad_to_multiple_of: Optional[int] = None,
289
+ padding_side: Optional[str] = None,
290
+ return_tensors: Optional[Union[str, TensorType]] = None,
291
+ return_token_type_ids: Optional[bool] = None,
292
+ return_attention_mask: Optional[bool] = None,
293
+ return_overflowing_tokens: bool = False,
294
+ return_special_tokens_mask: bool = False,
295
+ return_offsets_mapping: bool = False,
296
+ return_length: bool = False,
297
+ verbose: bool = True,
298
+ **kwargs,
299
+ ) -> BatchEncoding:
300
+ """
301
+ Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
302
+ sequences with word-level normalized bounding boxes and optional labels.
303
+
304
+ Args:
305
+ text (`str`, `List[str]`, `List[List[str]]`):
306
+ The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
307
+ (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
308
+ words).
309
+ text_pair (`List[str]`, `List[List[str]]`):
310
+ The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
311
+ (pretokenized string).
312
+ boxes (`List[List[int]]`, `List[List[List[int]]]`):
313
+ Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
314
+ word_labels (`List[int]`, `List[List[int]]`, *optional*):
315
+ Word-level integer labels (for token classification tasks such as FUNSD, CORD).
316
+ """
317
+
318
+ # Input type checking for clearer error
319
+ def _is_valid_text_input(t):
320
+ if isinstance(t, str):
321
+ # Strings are fine
322
+ return True
323
+ elif isinstance(t, (list, tuple)):
324
+ # List are fine as long as they are...
325
+ if len(t) == 0:
326
+ # ... empty
327
+ return True
328
+ elif isinstance(t[0], str):
329
+ # ... list of strings
330
+ return True
331
+ elif isinstance(t[0], (list, tuple)):
332
+ # ... list with an empty list or with a list of strings
333
+ return len(t[0]) == 0 or isinstance(t[0][0], str)
334
+ else:
335
+ return False
336
+ else:
337
+ return False
338
+
339
+ if text_pair is not None:
340
+ # in case text + text_pair are provided, text = questions, text_pair = words
341
+ if not _is_valid_text_input(text):
342
+ raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
343
+ if not isinstance(text_pair, (list, tuple)):
344
+ raise ValueError(
345
+ "words must of type `List[str]` (single pretokenized example), "
346
+ "or `List[List[str]]` (batch of pretokenized examples)."
347
+ )
348
+ else:
349
+ # in case only text is provided => must be words
350
+ if not isinstance(text, (list, tuple)):
351
+ raise ValueError(
352
+ "Words must of type `List[str]` (single pretokenized example), "
353
+ "or `List[List[str]]` (batch of pretokenized examples)."
354
+ )
355
+
356
+ if text_pair is not None:
357
+ is_batched = isinstance(text, (list, tuple))
358
+ else:
359
+ is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
360
+
361
+ words = text if text_pair is None else text_pair
362
+ if boxes is None:
363
+ raise ValueError("You must provide corresponding bounding boxes")
364
+ if is_batched:
365
+ if len(words) != len(boxes):
366
+ raise ValueError("You must provide words and boxes for an equal amount of examples")
367
+ for words_example, boxes_example in zip(words, boxes):
368
+ if len(words_example) != len(boxes_example):
369
+ raise ValueError("You must provide as many words as there are bounding boxes")
370
+ else:
371
+ if len(words) != len(boxes):
372
+ raise ValueError("You must provide as many words as there are bounding boxes")
373
+
374
+ if is_batched:
375
+ if text_pair is not None and len(text) != len(text_pair):
376
+ raise ValueError(
377
+ f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
378
+ f" {len(text_pair)}."
379
+ )
380
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
381
+ is_pair = bool(text_pair is not None)
382
+ return self.batch_encode_plus_boxes(
383
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
384
+ is_pair=is_pair,
385
+ boxes=boxes,
386
+ word_labels=word_labels,
387
+ add_special_tokens=add_special_tokens,
388
+ padding=padding,
389
+ truncation=truncation,
390
+ max_length=max_length,
391
+ stride=stride,
392
+ pad_to_multiple_of=pad_to_multiple_of,
393
+ padding_side=padding_side,
394
+ return_tensors=return_tensors,
395
+ return_token_type_ids=return_token_type_ids,
396
+ return_attention_mask=return_attention_mask,
397
+ return_overflowing_tokens=return_overflowing_tokens,
398
+ return_special_tokens_mask=return_special_tokens_mask,
399
+ return_offsets_mapping=return_offsets_mapping,
400
+ return_length=return_length,
401
+ verbose=verbose,
402
+ **kwargs,
403
+ )
404
+ else:
405
+ return self.encode_plus_boxes(
406
+ text=text,
407
+ text_pair=text_pair,
408
+ boxes=boxes,
409
+ word_labels=word_labels,
410
+ add_special_tokens=add_special_tokens,
411
+ padding=padding,
412
+ truncation=truncation,
413
+ max_length=max_length,
414
+ stride=stride,
415
+ pad_to_multiple_of=pad_to_multiple_of,
416
+ padding_side=padding_side,
417
+ return_tensors=return_tensors,
418
+ return_token_type_ids=return_token_type_ids,
419
+ return_attention_mask=return_attention_mask,
420
+ return_overflowing_tokens=return_overflowing_tokens,
421
+ return_special_tokens_mask=return_special_tokens_mask,
422
+ return_offsets_mapping=return_offsets_mapping,
423
+ return_length=return_length,
424
+ verbose=verbose,
425
+ **kwargs,
426
+ )
427
+
428
+ # Copied from transformers.models.layoutxlm.tokenization_layoutxlm_fast.LayoutXLMTokenizerFast.tokenize
429
+ def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
430
+ batched_input = [(text, pair)] if pair else [text]
431
+
432
+ self._tokenizer.encode_special_tokens = kwargs.pop(
433
+ "split_special_tokens", self._tokenizer.encode_special_tokens
434
+ )
435
+
436
+ encodings = self._tokenizer.encode_batch(
437
+ batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
438
+ )
439
+
440
+ return encodings[0].tokens
441
+
442
+ def batch_encode_plus_boxes(
443
+ self,
444
+ batch_text_or_text_pairs: Union[
445
+ List[TextInput],
446
+ List[TextInputPair],
447
+ List[PreTokenizedInput],
448
+ ],
449
+ is_pair: bool = None,
450
+ boxes: Optional[List[List[List[int]]]] = None,
451
+ word_labels: Optional[List[List[int]]] = None,
452
+ add_special_tokens: bool = True,
453
+ padding: Union[bool, str, PaddingStrategy] = False,
454
+ truncation: Union[bool, str, TruncationStrategy] = None,
455
+ max_length: Optional[int] = None,
456
+ stride: int = 0,
457
+ is_split_into_words: bool = False,
458
+ pad_to_multiple_of: Optional[int] = None,
459
+ padding_side: Optional[str] = None,
460
+ return_tensors: Optional[Union[str, TensorType]] = None,
461
+ return_token_type_ids: Optional[bool] = None,
462
+ return_attention_mask: Optional[bool] = None,
463
+ return_overflowing_tokens: bool = False,
464
+ return_special_tokens_mask: bool = False,
465
+ return_offsets_mapping: bool = False,
466
+ return_length: bool = False,
467
+ verbose: bool = True,
468
+ **kwargs,
469
+ ) -> BatchEncoding:
470
+ """
471
+ Tokenize and prepare for the model a list of sequences or a list of pairs of sequences.
472
+
473
+ <Tip warning={true}>
474
+
475
+ This method is deprecated, `__call__` should be used instead.
476
+
477
+ </Tip>
478
+
479
+ Args:
480
+ batch_text_or_text_pairs (`List[str]`, `List[Tuple[str, str]]`, `List[List[str]]`, `List[Tuple[List[str], List[str]]]`, and for not-fast tokenizers, also `List[List[int]]`, `List[Tuple[List[int], List[int]]]`):
481
+ Batch of sequences or pair of sequences to be encoded. This can be a list of
482
+ string/string-sequences/int-sequences or a list of pair of string/string-sequences/int-sequence (see
483
+ details in `encode_plus`).
484
+ """
485
+
486
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
487
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
488
+ padding=padding,
489
+ truncation=truncation,
490
+ max_length=max_length,
491
+ pad_to_multiple_of=pad_to_multiple_of,
492
+ verbose=verbose,
493
+ **kwargs,
494
+ )
495
+
496
+ return self._batch_encode_plus_boxes(
497
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
498
+ is_pair=is_pair,
499
+ boxes=boxes,
500
+ word_labels=word_labels,
501
+ add_special_tokens=add_special_tokens,
502
+ padding_strategy=padding_strategy,
503
+ truncation_strategy=truncation_strategy,
504
+ max_length=max_length,
505
+ stride=stride,
506
+ is_split_into_words=is_split_into_words,
507
+ pad_to_multiple_of=pad_to_multiple_of,
508
+ padding_side=padding_side,
509
+ return_tensors=return_tensors,
510
+ return_token_type_ids=return_token_type_ids,
511
+ return_attention_mask=return_attention_mask,
512
+ return_overflowing_tokens=return_overflowing_tokens,
513
+ return_special_tokens_mask=return_special_tokens_mask,
514
+ return_offsets_mapping=return_offsets_mapping,
515
+ return_length=return_length,
516
+ verbose=verbose,
517
+ **kwargs,
518
+ )
519
+
520
+ def _batch_encode_plus_boxes(
521
+ self,
522
+ batch_text_or_text_pairs: Union[
523
+ List[TextInput],
524
+ List[TextInputPair],
525
+ List[PreTokenizedInput],
526
+ ],
527
+ is_pair: bool = None,
528
+ boxes: Optional[List[List[List[int]]]] = None,
529
+ word_labels: Optional[List[List[int]]] = None,
530
+ add_special_tokens: bool = True,
531
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
532
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
533
+ max_length: Optional[int] = None,
534
+ stride: int = 0,
535
+ pad_to_multiple_of: Optional[int] = None,
536
+ padding_side: Optional[str] = None,
537
+ return_tensors: Optional[str] = None,
538
+ return_token_type_ids: Optional[bool] = None,
539
+ return_attention_mask: Optional[bool] = None,
540
+ return_overflowing_tokens: bool = False,
541
+ return_special_tokens_mask: bool = False,
542
+ return_offsets_mapping: bool = False,
543
+ return_length: bool = False,
544
+ verbose: bool = True,
545
+ **kwargs,
546
+ ) -> BatchEncoding:
547
+ if not isinstance(batch_text_or_text_pairs, list):
548
+ raise TypeError(f"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})")
549
+
550
+ # Set the truncation and padding strategy and restore the initial configuration
551
+ self.set_truncation_and_padding(
552
+ padding_strategy=padding_strategy,
553
+ truncation_strategy=truncation_strategy,
554
+ max_length=max_length,
555
+ stride=stride,
556
+ pad_to_multiple_of=pad_to_multiple_of,
557
+ padding_side=padding_side,
558
+ )
559
+
560
+ if is_pair:
561
+ batch_text_or_text_pairs = [(text.split(), text_pair) for text, text_pair in batch_text_or_text_pairs]
562
+
563
+ encodings = self._tokenizer.encode_batch(
564
+ batch_text_or_text_pairs,
565
+ add_special_tokens=add_special_tokens,
566
+ is_pretokenized=True, # we set this to True as LayoutLMv2 always expects pretokenized inputs
567
+ )
568
+
569
+ # Convert encoding to dict
570
+ # `Tokens` has type: Tuple[
571
+ # List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
572
+ # List[EncodingFast]
573
+ # ]
574
+ # with nested dimensions corresponding to batch, overflows, sequence length
575
+ tokens_and_encodings = [
576
+ self._convert_encoding(
577
+ encoding=encoding,
578
+ return_token_type_ids=return_token_type_ids,
579
+ return_attention_mask=return_attention_mask,
580
+ return_overflowing_tokens=return_overflowing_tokens,
581
+ return_special_tokens_mask=return_special_tokens_mask,
582
+ return_offsets_mapping=True
583
+ if word_labels is not None
584
+ else return_offsets_mapping, # we use offsets to create the labels
585
+ return_length=return_length,
586
+ verbose=verbose,
587
+ )
588
+ for encoding in encodings
589
+ ]
590
+
591
+ # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
592
+ # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
593
+ # (we say ~ because the number of overflow varies with the example in the batch)
594
+ #
595
+ # To match each overflowing sample with the original sample in the batch
596
+ # we add an overflow_to_sample_mapping array (see below)
597
+ sanitized_tokens = {}
598
+ for key in tokens_and_encodings[0][0].keys():
599
+ stack = [e for item, _ in tokens_and_encodings for e in item[key]]
600
+ sanitized_tokens[key] = stack
601
+ sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
602
+
603
+ # If returning overflowing tokens, we need to return a mapping
604
+ # from the batch idx to the original sample
605
+ if return_overflowing_tokens:
606
+ overflow_to_sample_mapping = []
607
+ for i, (toks, _) in enumerate(tokens_and_encodings):
608
+ overflow_to_sample_mapping += [i] * len(toks["input_ids"])
609
+ sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
610
+
611
+ for input_ids in sanitized_tokens["input_ids"]:
612
+ self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
613
+
614
+ # create the token boxes
615
+ token_boxes = []
616
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
617
+ if return_overflowing_tokens:
618
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
619
+ else:
620
+ original_index = batch_index
621
+ token_boxes_example = []
622
+ for id, sequence_id, word_id in zip(
623
+ sanitized_tokens["input_ids"][batch_index],
624
+ sanitized_encodings[batch_index].sequence_ids,
625
+ sanitized_encodings[batch_index].word_ids,
626
+ ):
627
+ if word_id is not None:
628
+ if is_pair and sequence_id == 0:
629
+ token_boxes_example.append(self.pad_token_box)
630
+ else:
631
+ token_boxes_example.append(boxes[original_index][word_id])
632
+ else:
633
+ if id == self.sep_token_id:
634
+ token_boxes_example.append(self.sep_token_box)
635
+ elif id == self.pad_token_id:
636
+ token_boxes_example.append(self.pad_token_box)
637
+ else:
638
+ raise ValueError("Id not recognized")
639
+ token_boxes.append(token_boxes_example)
640
+
641
+ sanitized_tokens["bbox"] = token_boxes
642
+
643
+ # optionally, create the labels
644
+ if word_labels is not None:
645
+ labels = []
646
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
647
+ if return_overflowing_tokens:
648
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
649
+ else:
650
+ original_index = batch_index
651
+ labels_example = []
652
+ previous_token_empty = False
653
+ for id, offset, word_id in zip(
654
+ sanitized_tokens["input_ids"][batch_index],
655
+ sanitized_tokens["offset_mapping"][batch_index],
656
+ sanitized_encodings[batch_index].word_ids,
657
+ ):
658
+ if word_id is not None:
659
+ if self.only_label_first_subword:
660
+ if offset[0] == 0 and not previous_token_empty:
661
+ # Use the real label id for the first token of the word, and padding ids for the remaining tokens
662
+ labels_example.append(word_labels[original_index][word_id])
663
+ else:
664
+ labels_example.append(self.pad_token_label)
665
+ else:
666
+ labels_example.append(word_labels[original_index][word_id])
667
+ if self.decode(id) == "":
668
+ previous_token_empty = True
669
+ else:
670
+ previous_token_empty = False
671
+ else:
672
+ labels_example.append(self.pad_token_label)
673
+ labels.append(labels_example)
674
+
675
+ sanitized_tokens["labels"] = labels
676
+ # finally, remove offsets if the user didn't want them
677
+ if not return_offsets_mapping:
678
+ del sanitized_tokens["offset_mapping"]
679
+
680
+ return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
681
+
682
+ def _encode_plus_boxes(
683
+ self,
684
+ text: Union[TextInput, PreTokenizedInput],
685
+ text_pair: Optional[PreTokenizedInput] = None,
686
+ boxes: Optional[List[List[int]]] = None,
687
+ word_labels: Optional[List[int]] = None,
688
+ add_special_tokens: bool = True,
689
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
690
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
691
+ max_length: Optional[int] = None,
692
+ stride: int = 0,
693
+ pad_to_multiple_of: Optional[int] = None,
694
+ padding_side: Optional[str] = None,
695
+ return_tensors: Optional[bool] = None,
696
+ return_token_type_ids: Optional[bool] = None,
697
+ return_attention_mask: Optional[bool] = None,
698
+ return_overflowing_tokens: bool = False,
699
+ return_special_tokens_mask: bool = False,
700
+ return_offsets_mapping: bool = False,
701
+ return_length: bool = False,
702
+ verbose: bool = True,
703
+ **kwargs,
704
+ ) -> BatchEncoding:
705
+ # make it a batched input
706
+ # 2 options:
707
+ # 1) only text, in case text must be a list of str
708
+ # 2) text + text_pair, in which case text = str and text_pair a list of str
709
+ batched_input = [(text, text_pair)] if text_pair else [text]
710
+ batched_boxes = [boxes]
711
+ batched_word_labels = [word_labels] if word_labels is not None else None
712
+ batched_output = self._batch_encode_plus_boxes(
713
+ batched_input,
714
+ is_pair=bool(text_pair is not None),
715
+ boxes=batched_boxes,
716
+ word_labels=batched_word_labels,
717
+ add_special_tokens=add_special_tokens,
718
+ padding_strategy=padding_strategy,
719
+ truncation_strategy=truncation_strategy,
720
+ max_length=max_length,
721
+ stride=stride,
722
+ pad_to_multiple_of=pad_to_multiple_of,
723
+ padding_side=padding_side,
724
+ return_tensors=return_tensors,
725
+ return_token_type_ids=return_token_type_ids,
726
+ return_attention_mask=return_attention_mask,
727
+ return_overflowing_tokens=return_overflowing_tokens,
728
+ return_special_tokens_mask=return_special_tokens_mask,
729
+ return_offsets_mapping=return_offsets_mapping,
730
+ return_length=return_length,
731
+ verbose=verbose,
732
+ **kwargs,
733
+ )
734
+
735
+ # Return tensor is None, then we can remove the leading batch axis
736
+ # Overflowing tokens are returned as a batch of output so we keep them in this case
737
+ if return_tensors is None and not return_overflowing_tokens:
738
+ batched_output = BatchEncoding(
739
+ {
740
+ key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
741
+ for key, value in batched_output.items()
742
+ },
743
+ batched_output.encodings,
744
+ )
745
+
746
+ self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
747
+
748
+ return batched_output
749
+
750
+ def encode_boxes(
751
+ self,
752
+ text: Union[TextInput, PreTokenizedInput, EncodedInput],
753
+ text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
754
+ boxes: Optional[List[List[int]]] = None,
755
+ word_labels: Optional[List[List[int]]] = None,
756
+ add_special_tokens: bool = True,
757
+ padding: Union[bool, str, PaddingStrategy] = False,
758
+ truncation: Union[bool, str, TruncationStrategy] = None,
759
+ max_length: Optional[int] = None,
760
+ stride: int = 0,
761
+ return_tensors: Optional[Union[str, TensorType]] = None,
762
+ **kwargs,
763
+ ) -> List[int]:
764
+ """
765
+ Args:
766
+ Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. Same as doing
767
+ `self.convert_tokens_to_ids(self.tokenize(text))`.
768
+ text (`str`, `List[str]` or `List[int]`):
769
+ The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
770
+ `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
771
+ method).
772
+ text_pair (`str`, `List[str]` or `List[int]`, *optional*):
773
+ Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
774
+ the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
775
+ method).
776
+ """
777
+ encoded_inputs = self.encode_plus_boxes(
778
+ text,
779
+ text_pair=text_pair,
780
+ boxes=boxes,
781
+ word_labels=word_labels,
782
+ add_special_tokens=add_special_tokens,
783
+ padding=padding,
784
+ truncation=truncation,
785
+ max_length=max_length,
786
+ stride=stride,
787
+ return_tensors=return_tensors,
788
+ **kwargs,
789
+ )
790
+
791
+ return encoded_inputs["input_ids"]
792
+
793
+ def encode_plus_boxes(
794
+ self,
795
+ text: Union[TextInput, PreTokenizedInput],
796
+ text_pair: Optional[PreTokenizedInput] = None,
797
+ boxes: Optional[List[List[int]]] = None,
798
+ word_labels: Optional[List[List[int]]] = None,
799
+ add_special_tokens: bool = True,
800
+ padding: Union[bool, str, PaddingStrategy] = False,
801
+ truncation: Union[bool, str, TruncationStrategy] = None,
802
+ max_length: Optional[int] = None,
803
+ stride: int = 0,
804
+ is_split_into_words: bool = False,
805
+ pad_to_multiple_of: Optional[int] = None,
806
+ padding_side: Optional[str] = None,
807
+ return_tensors: Optional[Union[str, TensorType]] = None,
808
+ return_token_type_ids: Optional[bool] = None,
809
+ return_attention_mask: Optional[bool] = None,
810
+ return_overflowing_tokens: bool = False,
811
+ return_special_tokens_mask: bool = False,
812
+ return_offsets_mapping: bool = False,
813
+ return_length: bool = False,
814
+ verbose: bool = True,
815
+ **kwargs,
816
+ ) -> BatchEncoding:
817
+ """
818
+ Tokenize and prepare for the model a sequence or a pair of sequences.
819
+
820
+ <Tip warning={true}>
821
+
822
+ This method is deprecated, `__call__` should be used instead.
823
+
824
+ </Tip>
825
+
826
+ Args:
827
+ text (`str`, `List[str]` or (for non-fast tokenizers) `List[int]`):
828
+ The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
829
+ `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
830
+ method).
831
+ text_pair (`str`, `List[str]` or `List[int]`, *optional*):
832
+ Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
833
+ the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
834
+ method).
835
+ """
836
+
837
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
838
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
839
+ padding=padding,
840
+ truncation=truncation,
841
+ max_length=max_length,
842
+ pad_to_multiple_of=pad_to_multiple_of,
843
+ verbose=verbose,
844
+ **kwargs,
845
+ )
846
+
847
+ return self._encode_plus_boxes(
848
+ text=text,
849
+ text_pair=text_pair,
850
+ boxes=boxes,
851
+ word_labels=word_labels,
852
+ add_special_tokens=add_special_tokens,
853
+ padding_strategy=padding_strategy,
854
+ truncation_strategy=truncation_strategy,
855
+ max_length=max_length,
856
+ stride=stride,
857
+ is_split_into_words=is_split_into_words,
858
+ pad_to_multiple_of=pad_to_multiple_of,
859
+ padding_side=padding_side,
860
+ return_tensors=return_tensors,
861
+ return_token_type_ids=return_token_type_ids,
862
+ return_attention_mask=return_attention_mask,
863
+ return_overflowing_tokens=return_overflowing_tokens,
864
+ return_special_tokens_mask=return_special_tokens_mask,
865
+ return_offsets_mapping=return_offsets_mapping,
866
+ return_length=return_length,
867
+ verbose=verbose,
868
+ **kwargs,
869
+ )
870
+
871
+ # Copied from transformers.models.layoutxlm.tokenization_layoutxlm_fast.LayoutXLMTokenizerFast._pad
872
+ def _pad(
873
+ self,
874
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
875
+ max_length: Optional[int] = None,
876
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
877
+ pad_to_multiple_of: Optional[int] = None,
878
+ padding_side: Optional[str] = None,
879
+ return_attention_mask: Optional[bool] = None,
880
+ ) -> dict:
881
+ """
882
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
883
+
884
+ Args:
885
+ encoded_inputs:
886
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
887
+ max_length: maximum length of the returned list and optionally padding length (see below).
888
+ Will truncate by taking into account the special tokens.
889
+ padding_strategy: PaddingStrategy to use for padding.
890
+
891
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
892
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
893
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
894
+ The tokenizer padding sides are defined in self.padding_side:
895
+
896
+ - 'left': pads on the left of the sequences
897
+ - 'right': pads on the right of the sequences
898
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
899
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
900
+ `>= 7.5` (Volta).
901
+ padding_side (`str`, *optional*):
902
+ The side on which the model should have padding applied. Should be selected between ['right', 'left'].
903
+ Default value is picked from the class attribute of the same name.
904
+ return_attention_mask:
905
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
906
+ """
907
+ # Load from model defaults
908
+ if return_attention_mask is None:
909
+ return_attention_mask = "attention_mask" in self.model_input_names
910
+
911
+ required_input = encoded_inputs[self.model_input_names[0]]
912
+
913
+ if padding_strategy == PaddingStrategy.LONGEST:
914
+ max_length = len(required_input)
915
+
916
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
917
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
918
+
919
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
920
+
921
+ # Initialize attention mask if not present.
922
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
923
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
924
+
925
+ if needs_to_be_padded:
926
+ difference = max_length - len(required_input)
927
+ padding_side = padding_side if padding_side is not None else self.padding_side
928
+ if padding_side == "right":
929
+ if return_attention_mask:
930
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
931
+ if "token_type_ids" in encoded_inputs:
932
+ encoded_inputs["token_type_ids"] = (
933
+ encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
934
+ )
935
+ if "bbox" in encoded_inputs:
936
+ encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
937
+ if "labels" in encoded_inputs:
938
+ encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
939
+ if "special_tokens_mask" in encoded_inputs:
940
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
941
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
942
+ elif padding_side == "left":
943
+ if return_attention_mask:
944
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
945
+ if "token_type_ids" in encoded_inputs:
946
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
947
+ "token_type_ids"
948
+ ]
949
+ if "bbox" in encoded_inputs:
950
+ encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
951
+ if "labels" in encoded_inputs:
952
+ encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
953
+ if "special_tokens_mask" in encoded_inputs:
954
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
955
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
956
+ else:
957
+ raise ValueError("Invalid padding strategy:" + str(padding_side))
958
+
959
+ return encoded_inputs
960
+
961
+ def build_inputs_with_special_tokens(
962
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
963
+ ) -> List[int]:
964
+ """
965
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
966
+ adding special tokens. An XLM-RoBERTa sequence has the following format:
967
+
968
+ - single sequence: `<s> X </s>`
969
+ - pair of sequences: `<s> A </s></s> B </s>`
970
+
971
+ Args:
972
+ token_ids_0 (`List[int]`):
973
+ List of IDs to which the special tokens will be added.
974
+ token_ids_1 (`List[int]`, *optional*):
975
+ Optional second list of IDs for sequence pairs.
976
+
977
+ Returns:
978
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
979
+ """
980
+
981
+ if token_ids_1 is None:
982
+ return token_ids_0 + [self.sep_token_id]
983
+ sep = [self.sep_token_id]
984
+ return token_ids_0 + sep + token_ids_1 + sep
985
+
986
+ def create_token_type_ids_from_sequences(
987
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
988
+ ) -> List[int]:
989
+ """
990
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
991
+ not make use of token type ids, therefore a list of zeros is returned.
992
+
993
+ Args:
994
+ token_ids_0 (`List[int]`):
995
+ List of IDs.
996
+ token_ids_1 (`List[int]`, *optional*):
997
+ Optional second list of IDs for sequence pairs.
998
+
999
+ Returns:
1000
+ `List[int]`: List of zeros.
1001
+
1002
+ """
1003
+
1004
+ sep = [self.sep_token_id]
1005
+
1006
+ if token_ids_1 is None:
1007
+ return len(token_ids_0 + sep) * [0]
1008
+ return len(token_ids_0 + sep + token_ids_1 + sep) * [0]
1009
+
1010
+ # Copied from transformers.models.layoutxlm.tokenization_layoutxlm_fast.LayoutXLMTokenizerFast.save_vocabulary
1011
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
1012
+ if not self.can_save_slow_tokenizer:
1013
+ raise ValueError(
1014
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
1015
+ "tokenizer."
1016
+ )
1017
+
1018
+ if not os.path.isdir(save_directory):
1019
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory.")
1020
+ return
1021
+ out_vocab_file = os.path.join(
1022
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
1023
+ )
1024
+
1025
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
1026
+ copyfile(self.vocab_file, out_vocab_file)
1027
+
1028
+ return (out_vocab_file,)
1029
+
1030
+
1031
+ __all__ = ["UdopTokenizerFast"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_umt5 import *
22
+ from .modeling_umt5 import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/configuration_umt5.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023, The T5 Authors and HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """UMT5 model configuration"""
16
+
17
+ from typing import Mapping
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...onnx import OnnxSeq2SeqConfigWithPast
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class UMT5Config(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`UMT5Model`]. It is used to instantiate a UMT5
30
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
+ defaults will yield a similar configuration to that of the UMT5
32
+ [google/umt5-small](https://huggingface.co/google/umt5-small) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+ Arguments:
38
+ vocab_size (`int`, *optional*, defaults to 250112):
39
+ Vocabulary size of the UMT5 model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`UMT5Model`] or [`TFUMT5Model`].
41
+ d_model (`int`, *optional*, defaults to 512):
42
+ Size of the encoder layers and the pooler layer.
43
+ d_kv (`int`, *optional*, defaults to 64):
44
+ Size of the key, query, value projections per attention head. `d_kv` has to be equal to `d_model //
45
+ num_heads`.
46
+ d_ff (`int`, *optional*, defaults to 1024):
47
+ Size of the intermediate feed forward layer in each `UMT5Block`.
48
+ num_layers (`int`, *optional*, defaults to 8):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_decoder_layers (`int`, *optional*):
51
+ Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
52
+ num_heads (`int`, *optional*, defaults to 6):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
55
+ The number of buckets to use for each attention layer.
56
+ relative_attention_max_distance (`int`, *optional*, defaults to 128):
57
+ The maximum distance of the longer sequences for the bucket separation.
58
+ dropout_rate (`float`, *optional*, defaults to 0.1):
59
+ The ratio for all dropout layers.
60
+ classifier_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for classifier.
62
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
63
+ The epsilon used by the layer normalization layers.
64
+ initializer_factor (`float`, *optional*, defaults to 1):
65
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
66
+ testing).
67
+ feed_forward_proj (`string`, *optional*, defaults to `"gated-gelu"`):
68
+ Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models).
71
+ """
72
+
73
+ model_type = "umt5"
74
+ keys_to_ignore_at_inference = ["past_key_values"]
75
+ attribute_map = {
76
+ "hidden_size": "d_model",
77
+ "num_attention_heads": "num_heads",
78
+ "num_hidden_layers": "num_layers",
79
+ "head_dim": "d_kv",
80
+ }
81
+
82
+ def __init__(
83
+ self,
84
+ vocab_size=250112,
85
+ d_model=512,
86
+ d_kv=64,
87
+ d_ff=1024,
88
+ num_layers=8,
89
+ num_decoder_layers=None,
90
+ num_heads=6,
91
+ relative_attention_num_buckets=32,
92
+ relative_attention_max_distance=128,
93
+ dropout_rate=0.1,
94
+ layer_norm_epsilon=1e-6,
95
+ initializer_factor=1.0,
96
+ feed_forward_proj="gated-gelu",
97
+ is_encoder_decoder=True,
98
+ use_cache=True,
99
+ tokenizer_class="T5Tokenizer",
100
+ tie_word_embeddings=True,
101
+ pad_token_id=0,
102
+ eos_token_id=1,
103
+ decoder_start_token_id=0,
104
+ classifier_dropout=0.0,
105
+ **kwargs,
106
+ ):
107
+ self.vocab_size = vocab_size
108
+ self.d_model = d_model
109
+ self.d_kv = d_kv
110
+ self.d_ff = d_ff
111
+ self.num_layers = num_layers
112
+ self.num_decoder_layers = (
113
+ num_decoder_layers if num_decoder_layers is not None else self.num_layers
114
+ ) # default = symmetry
115
+ self.num_heads = num_heads
116
+ self.relative_attention_num_buckets = relative_attention_num_buckets
117
+ self.relative_attention_max_distance = relative_attention_max_distance
118
+ self.dropout_rate = dropout_rate
119
+ self.classifier_dropout = classifier_dropout
120
+ self.layer_norm_epsilon = layer_norm_epsilon
121
+ self.initializer_factor = initializer_factor
122
+ self.feed_forward_proj = feed_forward_proj
123
+ self.use_cache = use_cache
124
+
125
+ act_info = self.feed_forward_proj.split("-")
126
+ self.dense_act_fn = act_info[-1]
127
+ self.is_gated_act = act_info[0] == "gated"
128
+
129
+ if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
130
+ raise ValueError(
131
+ f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer. "
132
+ "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
133
+ "'gated-gelu' or 'relu'"
134
+ )
135
+
136
+ if feed_forward_proj == "gated-gelu":
137
+ self.dense_act_fn = "gelu_new"
138
+
139
+ super().__init__(
140
+ is_encoder_decoder=is_encoder_decoder,
141
+ tokenizer_class=tokenizer_class,
142
+ tie_word_embeddings=tie_word_embeddings,
143
+ pad_token_id=pad_token_id,
144
+ eos_token_id=eos_token_id,
145
+ decoder_start_token_id=decoder_start_token_id,
146
+ **kwargs,
147
+ )
148
+
149
+
150
+ class UMT5OnnxConfig(OnnxSeq2SeqConfigWithPast):
151
+ @property
152
+ # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
153
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
154
+ common_inputs = {
155
+ "input_ids": {0: "batch", 1: "encoder_sequence"},
156
+ "attention_mask": {0: "batch", 1: "encoder_sequence"},
157
+ }
158
+ if self.use_past:
159
+ common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence"
160
+ common_inputs["decoder_input_ids"] = {0: "batch"}
161
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
162
+ else:
163
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
164
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
165
+
166
+ if self.use_past:
167
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
168
+
169
+ return common_inputs
170
+
171
+ @property
172
+ # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
173
+ def default_onnx_opset(self) -> int:
174
+ return 13
175
+
176
+ @property
177
+ def atol_for_validation(self) -> float:
178
+ return 5e-4
179
+
180
+
181
+ __all__ = ["UMT5Config", "UMT5OnnxConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Google LLC and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Convert T5X checkpoint to PyTorch
17
+
18
+ Steps:
19
+ - Install gsutil according to https://cloud.google.com/storage/docs/gsutil_install
20
+ - Get a T5X checkpoint at https://github.com/google-research/t5x/blob/main/docs/models.md#t5-11-checkpoints Example:
21
+ `gsutil -m cp -r gs://t5-data/pretrained_models/t5x/t5_1_1_small $HOME/`
22
+ - Create or download a corresponding config for the downloaded model. E.g. for T5 v1.1 small, you can use
23
+ https://huggingface.co/google/t5-v1_1-small/blob/main/config.json
24
+ - Convert:
25
+ ```
26
+ python3 convert_t5x_checkpoint_to_pytorch.py --t5x_checkpoint_path=$HOME/t5_1_1_small --config_file=config.json\
27
+ --pytorch_dump_path=$HOME/t5_1_1_small_pt
28
+ ```
29
+ """
30
+
31
+ import argparse
32
+ import collections
33
+
34
+ import numpy as np
35
+ import torch
36
+ from flax import traverse_util
37
+ from t5x import checkpoints
38
+
39
+ from transformers import MT5Config, UMT5EncoderModel, UMT5ForConditionalGeneration
40
+ from transformers.utils import logging
41
+
42
+
43
+ logging.set_verbosity_info()
44
+
45
+
46
+ def t5x_relpos_bias_lookup(params, i, prefix):
47
+ """Returns the Relative Position Bias parameters of a layer. Does not transpose."""
48
+ return params[f"{prefix}/{prefix}/relpos_bias/rel_embedding"][:, i, :]
49
+
50
+
51
+ def t5x_attention_lookup(params, i, prefix, layer_name="attention"):
52
+ """Returns the KOQV parameters of (self-)attention. Does not transpose."""
53
+ k_tmp = k_tmp = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/key/kernel"][:, i, :, :])
54
+ k = k_tmp.reshape(k_tmp.shape[0], k_tmp.shape[1] * k_tmp.shape[2])
55
+ o_tmp = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/out/kernel"][:, i, :, :])
56
+ o = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1], o_tmp.shape[2])
57
+ q_tmp = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/query/kernel"][:, i, :, :])
58
+ q = q_tmp.reshape(q_tmp.shape[0], q_tmp.shape[1] * q_tmp.shape[2])
59
+ v_tmp = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/value/kernel"][:, i, :, :])
60
+ v = v_tmp.reshape(v_tmp.shape[0], v_tmp.shape[1] * v_tmp.shape[2])
61
+ return k, o, q, v
62
+
63
+
64
+ def t5x_mlp_lookup(params, i, prefix, split_mlp_wi=False):
65
+ """Returns the MLP parameters of a layer. Does not transpose."""
66
+ if split_mlp_wi:
67
+ wi_0 = params[f"{prefix}/{prefix}/mlp/wi_0/kernel"][:, i, :]
68
+ wi_1 = params[f"{prefix}/{prefix}/mlp/wi_1/kernel"][:, i, :]
69
+ wi = (wi_0, wi_1)
70
+ else:
71
+ wi = params[f"{prefix}/{prefix}/mlp/wi/kernel"][:, i, :]
72
+
73
+ wo = params[f"{prefix}/{prefix}/mlp/wo/kernel"][:, i, :]
74
+ return wi, wo
75
+
76
+
77
+ def t5x_layer_norm_lookup(params, i, prefix, layer_name):
78
+ """Returns the layer norm param of a layer."""
79
+ return params[f"{prefix}/{prefix}/{layer_name}/scale"][:, i]
80
+
81
+
82
+ def convert_t5x_to_pytorch(
83
+ variables: dict, *, num_layers: int, is_encoder_only: bool, scalable_attention: bool = False
84
+ ):
85
+ """Converts the parameters from T5X-Flax to Transformers-PyTorch."""
86
+ old = traverse_util.flatten_dict(variables["target"])
87
+ old = {"/".join(k): v for k, v in old.items()}
88
+
89
+ # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
90
+ split_mlp_wi = "encoder/encoder/mlp/wi_0/kernel" in old
91
+ print("Split MLP:", split_mlp_wi)
92
+
93
+ new = collections.OrderedDict()
94
+
95
+ # Shared embeddings.
96
+ new["shared.weight"] = old["token_embedder/embedding"]
97
+
98
+ # Encoder.
99
+ for i in range(num_layers):
100
+ # Block i, layer 0 (Self Attention).
101
+ layer_norm = t5x_layer_norm_lookup(old, i, "encoder", "pre_attention_layer_norm")
102
+ k, o, q, v = t5x_attention_lookup(old, i, "encoder", "attention")
103
+ new[f"encoder.block.{i}.layer.0.layer_norm.weight"] = layer_norm
104
+ new[f"encoder.block.{i}.layer.0.SelfAttention.k.weight"] = k.T
105
+ new[f"encoder.block.{i}.layer.0.SelfAttention.o.weight"] = o.T
106
+ new[f"encoder.block.{i}.layer.0.SelfAttention.q.weight"] = q.T
107
+ new[f"encoder.block.{i}.layer.0.SelfAttention.v.weight"] = v.T
108
+
109
+ # Block i, layer 1 (MLP).
110
+ layer_norm = t5x_layer_norm_lookup(old, i, "encoder", "pre_mlp_layer_norm")
111
+ wi, wo = t5x_mlp_lookup(old, i, "encoder", split_mlp_wi)
112
+ new[f"encoder.block.{i}.layer.1.layer_norm.weight"] = layer_norm
113
+ if split_mlp_wi:
114
+ new[f"encoder.block.{i}.layer.1.DenseReluDense.wi_0.weight"] = wi[0].T
115
+ new[f"encoder.block.{i}.layer.1.DenseReluDense.wi_1.weight"] = wi[1].T
116
+ else:
117
+ new[f"encoder.block.{i}.layer.1.DenseReluDense.wi.weight"] = wi.T
118
+ new[f"encoder.block.{i}.layer.1.DenseReluDense.wo.weight"] = wo.T
119
+ if scalable_attention:
120
+ # convert the rel_embedding of each layer
121
+ new[f"encoder.block.{i}.layer.0.SelfAttention.relative_attention_bias.weight"] = t5x_relpos_bias_lookup(
122
+ old, i, "encoder"
123
+ ).T
124
+
125
+ new["encoder.final_layer_norm.weight"] = old["encoder/encoder_norm/scale"]
126
+
127
+ if not scalable_attention:
128
+ new["encoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight"] = t5x_relpos_bias_lookup(
129
+ old, 0, "encoder"
130
+ ).T
131
+ new["decoder.block.0.layer.0.SelfAttention.relative_attention_bias.weight"] = t5x_relpos_bias_lookup(
132
+ old, 0, "decoder"
133
+ ).T
134
+
135
+ if not is_encoder_only:
136
+ # Decoder.
137
+ for i in range(num_layers):
138
+ # Block i, layer 0 (Self Attention).
139
+ layer_norm = t5x_layer_norm_lookup(old, i, "decoder", "pre_self_attention_layer_norm")
140
+ k, o, q, v = t5x_attention_lookup(old, i, "decoder", "self_attention")
141
+ new[f"decoder.block.{i}.layer.0.layer_norm.weight"] = layer_norm
142
+ new[f"decoder.block.{i}.layer.0.SelfAttention.k.weight"] = k.T
143
+ new[f"decoder.block.{i}.layer.0.SelfAttention.o.weight"] = o.T
144
+ new[f"decoder.block.{i}.layer.0.SelfAttention.q.weight"] = q.T
145
+ new[f"decoder.block.{i}.layer.0.SelfAttention.v.weight"] = v.T
146
+
147
+ # Block i, layer 1 (Cross Attention).
148
+ layer_norm = t5x_layer_norm_lookup(old, i, "decoder", "pre_cross_attention_layer_norm")
149
+ k, o, q, v = t5x_attention_lookup(old, i, "decoder", "encoder_decoder_attention")
150
+ new[f"decoder.block.{i}.layer.1.layer_norm.weight"] = layer_norm
151
+ new[f"decoder.block.{i}.layer.1.EncDecAttention.k.weight"] = k.T
152
+ new[f"decoder.block.{i}.layer.1.EncDecAttention.o.weight"] = o.T
153
+ new[f"decoder.block.{i}.layer.1.EncDecAttention.q.weight"] = q.T
154
+ new[f"decoder.block.{i}.layer.1.EncDecAttention.v.weight"] = v.T
155
+
156
+ # Block i, layer 2 (MLP).
157
+ layer_norm = t5x_layer_norm_lookup(old, i, "decoder", "pre_mlp_layer_norm")
158
+ wi, wo = t5x_mlp_lookup(old, i, "decoder", split_mlp_wi)
159
+ new[f"decoder.block.{i}.layer.2.layer_norm.weight"] = layer_norm
160
+ if split_mlp_wi:
161
+ new[f"decoder.block.{i}.layer.2.DenseReluDense.wi_0.weight"] = wi[0].T
162
+ new[f"decoder.block.{i}.layer.2.DenseReluDense.wi_1.weight"] = wi[1].T
163
+ else:
164
+ new[f"encoder.block.{i}.layer.2.DenseReluDense.wi.weight"] = wi.T
165
+ new[f"decoder.block.{i}.layer.2.DenseReluDense.wo.weight"] = wo.T
166
+
167
+ if scalable_attention:
168
+ # convert the rel_embedding of each layer
169
+ new[f"decoder.block.{i}.layer.0.SelfAttention.relative_attention_bias.weight"] = (
170
+ t5x_relpos_bias_lookup(old, i, "decoder").T
171
+ )
172
+
173
+ new["decoder.final_layer_norm.weight"] = old["decoder/decoder_norm/scale"]
174
+
175
+ # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
176
+ if "decoder/logits_dense/kernel" in old:
177
+ new["lm_head.weight"] = old["decoder/logits_dense/kernel"].T
178
+
179
+ return new
180
+
181
+
182
+ def make_state_dict(converted_params, is_encoder_only: bool):
183
+ """Prepares a state dict for the PyTorch model."""
184
+ # Make a state dict with torch tensors.
185
+ state_dict = collections.OrderedDict([(k, torch.from_numpy(v.copy())) for (k, v) in converted_params.items()])
186
+
187
+ # Add what is missing.
188
+ if "encoder.embed_tokens.weight" not in state_dict:
189
+ state_dict["encoder.embed_tokens.weight"] = state_dict["shared.weight"]
190
+
191
+ if not is_encoder_only:
192
+ if "decoder.embed_tokens.weight" not in state_dict:
193
+ state_dict["decoder.embed_tokens.weight"] = state_dict["shared.weight"]
194
+
195
+ if "lm_head.weight" not in state_dict: # For old 1.0 models.
196
+ print("Using shared word embeddings as lm_head.")
197
+ state_dict["lm_head.weight"] = state_dict["shared.weight"]
198
+
199
+ return state_dict
200
+
201
+
202
+ def load_t5x_weights_in_t5(model, config, t5x_checkpoint_path, is_encoder_only, scalable_attention):
203
+ """Replaces the params in model witht the T5X converted params."""
204
+ variables = checkpoints.load_t5x_checkpoint(t5x_checkpoint_path)
205
+ converted = convert_t5x_to_pytorch(
206
+ variables, num_layers=config.num_layers, is_encoder_only=is_encoder_only, scalable_attention=scalable_attention
207
+ )
208
+ state_dict = make_state_dict(converted, is_encoder_only)
209
+ model.load_state_dict(state_dict, strict=True)
210
+
211
+
212
+ def convert_t5x_checkpoint_to_pytorch(
213
+ t5x_checkpoint_path,
214
+ config_file,
215
+ pytorch_dump_path,
216
+ is_encoder_only: bool = False,
217
+ scalable_attention: bool = False,
218
+ ):
219
+ """Loads the config and model, converts the T5X checkpoint, and saves a PyTorch checkpoint."""
220
+ # Initialise PyTorch model
221
+ config = MT5Config.from_json_file(config_file)
222
+ print(f"Building PyTorch model from configuration: {config}")
223
+ # Non-v1.1 checkpoints could also use T5Model, but this works for all.
224
+ # The v1.0 checkpoints will simply have an LM head that is the word embeddings.
225
+ if is_encoder_only:
226
+ model = UMT5EncoderModel(config)
227
+ else:
228
+ model = UMT5ForConditionalGeneration(config)
229
+
230
+ # Load weights from tf checkpoint
231
+ load_t5x_weights_in_t5(model, config, t5x_checkpoint_path, is_encoder_only, scalable_attention)
232
+
233
+ # Save pytorch-model
234
+ print(f"Save PyTorch model to {pytorch_dump_path}")
235
+ model.save_pretrained(pytorch_dump_path)
236
+
237
+ # Verify that we can load the checkpoint.
238
+ model.from_pretrained(pytorch_dump_path)
239
+ print("Done")
240
+
241
+
242
+ if __name__ == "__main__":
243
+ parser = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.")
244
+ # Required parameters
245
+ parser.add_argument(
246
+ "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint."
247
+ )
248
+ parser.add_argument(
249
+ "--config_file",
250
+ default=None,
251
+ type=str,
252
+ required=True,
253
+ help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.",
254
+ )
255
+ parser.add_argument(
256
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
257
+ )
258
+ parser.add_argument(
259
+ "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False
260
+ )
261
+ parser.add_argument(
262
+ "--scalable_attention",
263
+ action="store_true",
264
+ help="Whether the model uses scaled attention (umt5 model)",
265
+ default=False,
266
+ )
267
+ args = parser.parse_args()
268
+ convert_t5x_checkpoint_to_pytorch(
269
+ args.t5x_checkpoint_path,
270
+ args.config_file,
271
+ args.pytorch_dump_path,
272
+ args.is_encoder_only,
273
+ args.scalable_attention,
274
+ )
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/umt5/modeling_umt5.py ADDED
@@ -0,0 +1,2029 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch UMT5 model."""
16
+
17
+ import copy
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache, StaticCache
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
29
+ from ...modeling_outputs import (
30
+ BaseModelOutput,
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ Seq2SeqLMOutput,
33
+ Seq2SeqModelOutput,
34
+ Seq2SeqQuestionAnsweringModelOutput,
35
+ Seq2SeqSequenceClassifierOutput,
36
+ TokenClassifierOutput,
37
+ )
38
+ from ...modeling_utils import PreTrainedModel
39
+ from ...utils import (
40
+ DUMMY_INPUTS,
41
+ DUMMY_MASK,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_torch_fx_proxy,
45
+ is_torchdynamo_compiling,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ from .configuration_umt5 import UMT5Config
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CONFIG_FOR_DOC = "UMT5Config"
55
+ _CHECKPOINT_FOR_DOC = "google/umt5-small"
56
+
57
+
58
+ # Copied from transformers.models.t5.modeling_t5.T5LayerNorm with T5->UMT5
59
+ class UMT5LayerNorm(nn.Module):
60
+ def __init__(self, hidden_size, eps=1e-6):
61
+ """
62
+ Construct a layernorm module in the UMT5 style. No bias and no subtraction of mean.
63
+ """
64
+ super().__init__()
65
+ self.weight = nn.Parameter(torch.ones(hidden_size))
66
+ self.variance_epsilon = eps
67
+
68
+ def forward(self, hidden_states):
69
+ # UMT5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
70
+ # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus varience is calculated
71
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
72
+ # half-precision inputs is done in fp32
73
+
74
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
75
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
76
+
77
+ # convert into half-precision if necessary
78
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
79
+ hidden_states = hidden_states.to(self.weight.dtype)
80
+
81
+ return self.weight * hidden_states
82
+
83
+
84
+ # Copied from transformers.models.t5.modeling_t5.T5DenseActDense with T5->UMT5
85
+ class UMT5DenseActDense(nn.Module):
86
+ def __init__(self, config: UMT5Config):
87
+ super().__init__()
88
+ self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
89
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
90
+ self.dropout = nn.Dropout(config.dropout_rate)
91
+ self.act = ACT2FN[config.dense_act_fn]
92
+
93
+ def forward(self, hidden_states):
94
+ hidden_states = self.wi(hidden_states)
95
+ hidden_states = self.act(hidden_states)
96
+ hidden_states = self.dropout(hidden_states)
97
+ if (
98
+ isinstance(self.wo.weight, torch.Tensor)
99
+ and hidden_states.dtype != self.wo.weight.dtype
100
+ and self.wo.weight.dtype != torch.int8
101
+ ):
102
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
103
+ hidden_states = self.wo(hidden_states)
104
+ return hidden_states
105
+
106
+
107
+ # Copied from transformers.models.t5.modeling_t5.T5DenseGatedActDense with T5->UMT5
108
+ class UMT5DenseGatedActDense(nn.Module):
109
+ def __init__(self, config: UMT5Config):
110
+ super().__init__()
111
+ self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
112
+ self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
113
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
114
+ self.dropout = nn.Dropout(config.dropout_rate)
115
+ self.act = ACT2FN[config.dense_act_fn]
116
+
117
+ def forward(self, hidden_states):
118
+ hidden_gelu = self.act(self.wi_0(hidden_states))
119
+ hidden_linear = self.wi_1(hidden_states)
120
+ hidden_states = hidden_gelu * hidden_linear
121
+ hidden_states = self.dropout(hidden_states)
122
+
123
+ # To make 8bit quantization work for google/flan-t5-xxl, self.wo is kept in float32.
124
+ # See https://github.com/huggingface/transformers/issues/20287
125
+ # we also make sure the weights are not in `int8` in case users will force `_keep_in_fp32_modules` to be `None``
126
+ if (
127
+ isinstance(self.wo.weight, torch.Tensor)
128
+ and hidden_states.dtype != self.wo.weight.dtype
129
+ and self.wo.weight.dtype != torch.int8
130
+ ):
131
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
132
+
133
+ hidden_states = self.wo(hidden_states)
134
+ return hidden_states
135
+
136
+
137
+ # Copied from transformers.models.t5.modeling_t5.T5LayerFF with T5->UMT5
138
+ class UMT5LayerFF(nn.Module):
139
+ def __init__(self, config: UMT5Config):
140
+ super().__init__()
141
+ if config.is_gated_act:
142
+ self.DenseReluDense = UMT5DenseGatedActDense(config)
143
+ else:
144
+ self.DenseReluDense = UMT5DenseActDense(config)
145
+
146
+ self.layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
147
+ self.dropout = nn.Dropout(config.dropout_rate)
148
+
149
+ def forward(self, hidden_states):
150
+ forwarded_states = self.layer_norm(hidden_states)
151
+ forwarded_states = self.DenseReluDense(forwarded_states)
152
+ hidden_states = hidden_states + self.dropout(forwarded_states)
153
+ return hidden_states
154
+
155
+
156
+ class UMT5Attention(nn.Module):
157
+ """
158
+ T5's attention using relative_attention_bias.
159
+ """
160
+
161
+ def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
162
+ super().__init__()
163
+ self.is_decoder = config.is_decoder
164
+ self.has_relative_attention_bias = has_relative_attention_bias
165
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
166
+ self.relative_attention_max_distance = config.relative_attention_max_distance
167
+ self.d_model = config.d_model
168
+ self.key_value_proj_dim = config.d_kv
169
+ self.n_heads = config.num_heads
170
+ self.dropout = config.dropout_rate
171
+ self.inner_dim = self.n_heads * self.key_value_proj_dim
172
+ self.layer_idx = layer_idx
173
+ if layer_idx is None and self.is_decoder:
174
+ logger.warning_once(
175
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
176
+ "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
177
+ "when creating this class."
178
+ )
179
+
180
+ # Mesh TensorFlow initialization to avoid scaling before softmax
181
+ self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)
182
+ self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)
183
+ self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)
184
+ self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)
185
+
186
+ if self.has_relative_attention_bias:
187
+ self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
188
+ self.pruned_heads = set()
189
+
190
+ def _shape(self, projection: torch.Tensor) -> torch.Tensor:
191
+ new_projection_shape = projection.size()[:-1] + (self.n_heads, self.key_value_proj_dim)
192
+ # move heads to 2nd position (B, T, H * D) -> (B, T, H, D) -> (B, H, T, D)
193
+ new_projection = projection.view(new_projection_shape).permute(0, 2, 1, 3)
194
+ return new_projection
195
+
196
+ def _relative_position_bucket(self, relative_position):
197
+ """
198
+ Adapted from Mesh Tensorflow:
199
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
200
+
201
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
202
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
203
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
204
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
205
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
206
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
207
+
208
+ Args:
209
+ relative_position: an int32 Tensor
210
+ bidirectional: a boolean - whether the attention is bidirectional
211
+ num_buckets: an integer
212
+ max_distance: an integer
213
+
214
+ Returns:
215
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
216
+ """
217
+ relative_buckets = 0
218
+ num_buckets = self.relative_attention_num_buckets
219
+ max_distance = self.relative_attention_max_distance
220
+ if not self.is_decoder:
221
+ num_buckets //= 2
222
+ relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
223
+ relative_position = torch.abs(relative_position)
224
+ else:
225
+ relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
226
+ # now relative_position is in the range [0, inf)
227
+
228
+ # half of the buckets are for exact increments in positions
229
+ max_exact = num_buckets // 2
230
+ is_small = relative_position < max_exact
231
+
232
+ # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
233
+ log_ratio = torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact)
234
+ log_ratio = log_ratio * (num_buckets - max_exact)
235
+ relative_position_if_large = max_exact + log_ratio.to(torch.long)
236
+ relative_position_if_large = torch.min(
237
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
238
+ )
239
+
240
+ relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
241
+ return relative_buckets
242
+
243
+ def compute_bias(self, query_length, key_length, device=None, cache_position=None):
244
+ """Compute binned relative position bias"""
245
+ if device is None:
246
+ device = self.relative_attention_bias.weight.device
247
+ if cache_position is None:
248
+ context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
249
+ else:
250
+ context_position = cache_position[:, None]
251
+ memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
252
+ relative_position = memory_position - context_position # shape (query_length, key_length)
253
+ relative_position_bucket = self._relative_position_bucket(relative_position)
254
+ values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
255
+ values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
256
+ return values
257
+
258
+ def forward(
259
+ self,
260
+ hidden_states: torch.Tensor,
261
+ encoder_hidden_states: Optional[torch.Tensor] = None,
262
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
263
+ attention_mask: Optional[torch.Tensor] = None,
264
+ layer_head_mask: Optional[torch.Tensor] = None,
265
+ cache_position: Optional[torch.Tensor] = None,
266
+ ):
267
+ batch_size, seq_length = hidden_states.shape[:2]
268
+
269
+ # if encoder_hidden_states are provided this layer is used as a cross-attention layer for the decoder
270
+ is_cross_attention = encoder_hidden_states is not None
271
+
272
+ query_states = self.q(hidden_states)
273
+ query_states = query_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
274
+
275
+ if past_key_value is not None:
276
+ is_updated = past_key_value.is_updated.get(self.layer_idx)
277
+ if is_cross_attention:
278
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
279
+ curr_past_key_value = past_key_value.cross_attention_cache
280
+ else:
281
+ curr_past_key_value = past_key_value.self_attention_cache
282
+
283
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
284
+ if is_cross_attention and past_key_value is not None and is_updated:
285
+ # reuse k,v, cross_attentions
286
+ key_states = curr_past_key_value.key_cache[self.layer_idx]
287
+ value_states = curr_past_key_value.value_cache[self.layer_idx]
288
+ else:
289
+ key_states = self.k(current_states)
290
+ value_states = self.v(current_states)
291
+ key_states = key_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
292
+ value_states = value_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
293
+
294
+ if past_key_value is not None:
295
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
296
+ cache_position = cache_position if not is_cross_attention else None
297
+ key_states, value_states = curr_past_key_value.update(
298
+ key_states, value_states, self.layer_idx, {"cache_position": cache_position}
299
+ )
300
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
301
+ if is_cross_attention:
302
+ past_key_value.is_updated[self.layer_idx] = True
303
+
304
+ # compute scores, equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
305
+ scores = torch.matmul(query_states, key_states.transpose(3, 2))
306
+
307
+ # cache position is 0-indexed so we add 1 to get the real length of queries (aka with past)
308
+ real_seq_length = seq_length + past_key_value.get_seq_length() if past_key_value is not None else seq_length
309
+ key_length = key_states.shape[-2]
310
+ if not self.has_relative_attention_bias:
311
+ position_bias = torch.zeros(
312
+ (1, self.n_heads, seq_length, key_length), device=scores.device, dtype=scores.dtype
313
+ )
314
+ else:
315
+ position_bias = self.compute_bias(
316
+ real_seq_length, key_length, device=scores.device, cache_position=cache_position
317
+ )
318
+ position_bias = position_bias[:, :, -seq_length:, :]
319
+
320
+ if attention_mask is not None:
321
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
322
+ position_bias = position_bias + causal_mask
323
+
324
+ if self.pruned_heads:
325
+ mask = torch.ones(position_bias.shape[1])
326
+ mask[list(self.pruned_heads)] = 0
327
+ position_bias_masked = position_bias[:, mask.bool()]
328
+ else:
329
+ position_bias_masked = position_bias
330
+
331
+ scores += position_bias_masked
332
+
333
+ # (batch_size, n_heads, seq_length, key_length)
334
+ attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores)
335
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
336
+
337
+ # Mask heads if we want to
338
+ if layer_head_mask is not None:
339
+ attn_weights = attn_weights * layer_head_mask
340
+
341
+ attn_output = torch.matmul(attn_weights, value_states)
342
+
343
+ attn_output = attn_output.transpose(1, 2).contiguous()
344
+ attn_output = attn_output.view(batch_size, seq_length, -1)
345
+
346
+ attn_output = self.o(attn_output)
347
+ return attn_output, attn_weights, past_key_value
348
+
349
+
350
+ class UMT5LayerSelfAttention(nn.Module):
351
+ def __init__(self, config, layer_idx: Optional[int] = None):
352
+ super().__init__()
353
+ self.SelfAttention = UMT5Attention(config, has_relative_attention_bias=True, layer_idx=layer_idx)
354
+ self.layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
355
+ self.dropout = nn.Dropout(config.dropout_rate)
356
+
357
+ def forward(
358
+ self,
359
+ hidden_states,
360
+ attention_mask=None,
361
+ layer_head_mask=None,
362
+ past_key_value=None,
363
+ cache_position=None,
364
+ ):
365
+ normed_hidden_states = self.layer_norm(hidden_states)
366
+ attention_output = self.SelfAttention(
367
+ normed_hidden_states,
368
+ attention_mask=attention_mask,
369
+ layer_head_mask=layer_head_mask,
370
+ past_key_value=past_key_value,
371
+ cache_position=cache_position,
372
+ )
373
+ hidden_states = hidden_states + self.dropout(attention_output[0])
374
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
375
+ return outputs
376
+
377
+
378
+ class UMT5LayerCrossAttention(nn.Module):
379
+ def __init__(self, config, layer_idx: Optional[int] = None):
380
+ super().__init__()
381
+ self.EncDecAttention = UMT5Attention(config, has_relative_attention_bias=False, layer_idx=layer_idx)
382
+ self.layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
383
+ self.dropout = nn.Dropout(config.dropout_rate)
384
+
385
+ def forward(
386
+ self,
387
+ hidden_states,
388
+ encoder_hidden_states=None,
389
+ attention_mask=None,
390
+ layer_head_mask=None,
391
+ past_key_value=None,
392
+ cache_position=None,
393
+ ):
394
+ normed_hidden_states = self.layer_norm(hidden_states)
395
+ attention_output = self.EncDecAttention(
396
+ normed_hidden_states,
397
+ encoder_hidden_states=encoder_hidden_states,
398
+ attention_mask=attention_mask,
399
+ layer_head_mask=layer_head_mask,
400
+ past_key_value=past_key_value,
401
+ cache_position=cache_position,
402
+ )
403
+ layer_output = hidden_states + self.dropout(attention_output[0])
404
+ outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
405
+ return outputs
406
+
407
+
408
+ class UMT5Block(nn.Module):
409
+ def __init__(self, config, layer_idx: Optional[int] = None):
410
+ super().__init__()
411
+ self.is_decoder = config.is_decoder
412
+ self.layer = nn.ModuleList()
413
+ self.layer.append(UMT5LayerSelfAttention(config, layer_idx=layer_idx))
414
+ if self.is_decoder:
415
+ self.layer.append(UMT5LayerCrossAttention(config, layer_idx=layer_idx))
416
+
417
+ self.layer.append(UMT5LayerFF(config))
418
+
419
+ def forward(
420
+ self,
421
+ hidden_states,
422
+ attention_mask=None,
423
+ encoder_hidden_states=None,
424
+ encoder_attention_mask=None,
425
+ layer_head_mask=None,
426
+ cross_attn_layer_head_mask=None,
427
+ past_key_value=None,
428
+ use_cache=False,
429
+ output_attentions=False,
430
+ cache_position=None,
431
+ ):
432
+ hidden_states, self_attn_weights, past_key_value = self.layer[0](
433
+ hidden_states,
434
+ attention_mask=attention_mask,
435
+ layer_head_mask=layer_head_mask,
436
+ past_key_value=past_key_value,
437
+ cache_position=cache_position,
438
+ )
439
+
440
+ # clamp inf values to enable fp16 training
441
+ if hidden_states.dtype == torch.float16:
442
+ max_dtype = torch.finfo(hidden_states.dtype).max
443
+ clamp_value = torch.where(torch.isinf(hidden_states).any(), max_dtype - 1000, max_dtype)
444
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
445
+
446
+ # Cross-Attention Block
447
+ cross_attn_weights = None
448
+ do_cross_attention = self.is_decoder and encoder_hidden_states is not None
449
+ if do_cross_attention:
450
+ hidden_states, cross_attn_weights, past_key_value = self.layer[1](
451
+ hidden_states,
452
+ encoder_hidden_states=encoder_hidden_states,
453
+ attention_mask=encoder_attention_mask,
454
+ layer_head_mask=cross_attn_layer_head_mask,
455
+ past_key_value=past_key_value,
456
+ cache_position=cache_position,
457
+ )
458
+ # clamp inf values to enable fp16 training
459
+ if hidden_states.dtype == torch.float16:
460
+ max_dtype = torch.finfo(hidden_states.dtype).max
461
+ clamp_value = torch.where(torch.isinf(hidden_states).any(), max_dtype - 1000, max_dtype)
462
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
463
+
464
+ # Apply Feed Forward layer
465
+ hidden_states = self.layer[-1](hidden_states)
466
+
467
+ # clamp inf values to enable fp16 training
468
+ if hidden_states.dtype == torch.float16:
469
+ max_dtype = torch.finfo(hidden_states.dtype).max
470
+ clamp_value = torch.where(torch.isinf(hidden_states).any(), max_dtype - 1000, max_dtype)
471
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
472
+
473
+ outputs = (
474
+ hidden_states,
475
+ past_key_value,
476
+ )
477
+
478
+ if output_attentions:
479
+ outputs += (self_attn_weights, cross_attn_weights)
480
+
481
+ return outputs
482
+
483
+
484
+ # Copied from transformers.models.t5.modeling_t5.T5ClassificationHead with T5->UMT5
485
+ class UMT5ClassificationHead(nn.Module):
486
+ """Head for sentence-level classification tasks."""
487
+
488
+ def __init__(self, config: UMT5Config):
489
+ super().__init__()
490
+ self.dense = nn.Linear(config.d_model, config.d_model)
491
+ self.dropout = nn.Dropout(p=config.classifier_dropout)
492
+ self.out_proj = nn.Linear(config.d_model, config.num_labels)
493
+
494
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
495
+ hidden_states = self.dropout(hidden_states)
496
+ hidden_states = self.dense(hidden_states)
497
+ hidden_states = torch.tanh(hidden_states)
498
+ hidden_states = self.dropout(hidden_states)
499
+ hidden_states = self.out_proj(hidden_states)
500
+ return hidden_states
501
+
502
+
503
+ class UMT5PreTrainedModel(PreTrainedModel):
504
+ """
505
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
506
+ models.
507
+ """
508
+
509
+ config_class = UMT5Config
510
+ base_model_prefix = "transformer"
511
+ supports_gradient_checkpointing = True
512
+ _supports_cache_class = True
513
+ _supports_static_cache = True
514
+ _no_split_modules = ["UMT5Block"]
515
+ _keep_in_fp32_modules = ["wo"]
516
+
517
+ @property
518
+ def dummy_inputs(self):
519
+ input_ids = torch.tensor(DUMMY_INPUTS)
520
+ input_mask = torch.tensor(DUMMY_MASK)
521
+ dummy_inputs = {
522
+ "decoder_input_ids": input_ids,
523
+ "input_ids": input_ids,
524
+ "decoder_attention_mask": input_mask,
525
+ }
526
+ return dummy_inputs
527
+
528
+ def _init_weights(self, module):
529
+ """Initialize the weights"""
530
+ factor = self.config.initializer_factor # Used for testing weights initialization
531
+ if isinstance(module, UMT5LayerNorm):
532
+ module.weight.data.fill_(factor * 1.0)
533
+ elif isinstance(
534
+ module,
535
+ (
536
+ UMT5Model,
537
+ UMT5ForConditionalGeneration,
538
+ UMT5EncoderModel,
539
+ UMT5ForQuestionAnswering,
540
+ ),
541
+ ):
542
+ # Mesh TensorFlow embeddings initialization
543
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
544
+ module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
545
+ if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
546
+ module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
547
+ if hasattr(module, "qa_outputs"):
548
+ module.qa_outputs.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
549
+ module.qa_outputs.bias.data.zero_()
550
+ elif isinstance(module, UMT5ForTokenClassification):
551
+ if hasattr(module, "classifier"):
552
+ module.classifier.weight.data.normal_(mean=0.0, std=factor * 1.0)
553
+ module.classifier.bias.data.zero_()
554
+ elif isinstance(module, UMT5ClassificationHead):
555
+ module.dense.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
556
+ if hasattr(module.dense, "bias") and module.dense.bias is not None:
557
+ module.dense.bias.data.zero_()
558
+ module.out_proj.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
559
+ if hasattr(module.out_proj, "bias") and module.out_proj.bias is not None:
560
+ module.out_proj.bias.data.zero_()
561
+ elif isinstance(module, UMT5DenseActDense):
562
+ # Mesh TensorFlow FF initialization
563
+ # See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
564
+ # and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
565
+ module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
566
+ if hasattr(module.wi, "bias") and module.wi.bias is not None:
567
+ module.wi.bias.data.zero_()
568
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
569
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
570
+ module.wo.bias.data.zero_()
571
+ elif isinstance(module, UMT5DenseGatedActDense):
572
+ module.wi_0.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
573
+ if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
574
+ module.wi_0.bias.data.zero_()
575
+ module.wi_1.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
576
+ if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
577
+ module.wi_1.bias.data.zero_()
578
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
579
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
580
+ module.wo.bias.data.zero_()
581
+ elif isinstance(module, UMT5Attention):
582
+ # Mesh TensorFlow attention initialization to avoid scaling before softmax
583
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
584
+ d_model = self.config.d_model
585
+ key_value_proj_dim = self.config.d_kv
586
+ n_heads = self.config.num_heads
587
+ module.q.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
588
+ module.k.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
589
+ module.v.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
590
+ module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
591
+ if module.has_relative_attention_bias:
592
+ module.relative_attention_bias.weight.data.normal_(mean=0.0, std=factor * ((d_model) ** -0.5))
593
+
594
+ def _shift_right(self, input_ids):
595
+ decoder_start_token_id = self.config.decoder_start_token_id
596
+ pad_token_id = self.config.pad_token_id
597
+
598
+ if decoder_start_token_id is None:
599
+ raise ValueError(
600
+ "self.model.config.decoder_start_token_id has to be defined. In UMT5 it is usually set to the pad_token_id. "
601
+ "See UMT5 docs for more information."
602
+ )
603
+
604
+ # shift inputs to the right
605
+ if is_torch_fx_proxy(input_ids):
606
+ # Item assignment is not supported natively for proxies.
607
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), decoder_start_token_id)
608
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
609
+ else:
610
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
611
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
612
+ shifted_input_ids[..., 0] = decoder_start_token_id
613
+
614
+ if pad_token_id is None:
615
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
616
+ # replace possible -100 values in labels by `pad_token_id`
617
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
618
+
619
+ return shifted_input_ids
620
+
621
+
622
+ class UMT5Stack(UMT5PreTrainedModel):
623
+ def __init__(self, config, embed_tokens=None):
624
+ super().__init__(config)
625
+ self.embed_tokens = embed_tokens
626
+ self.is_decoder = config.is_decoder
627
+ self.block = nn.ModuleList([UMT5Block(config, layer_idx=i) for i in range(config.num_layers)])
628
+ self.final_layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
629
+ self.dropout = nn.Dropout(config.dropout_rate)
630
+
631
+ # Initialize weights and apply final processing
632
+ self.gradient_checkpointing = False
633
+ self.post_init()
634
+
635
+ def get_input_embeddings(self):
636
+ return self.embed_tokens
637
+
638
+ def set_input_embeddings(self, new_embeddings):
639
+ self.embed_tokens = new_embeddings
640
+
641
+ def forward(
642
+ self,
643
+ input_ids=None,
644
+ attention_mask=None,
645
+ encoder_hidden_states=None,
646
+ encoder_attention_mask=None,
647
+ inputs_embeds=None,
648
+ head_mask=None,
649
+ cross_attn_head_mask=None,
650
+ past_key_values=None,
651
+ use_cache=None,
652
+ output_attentions=None,
653
+ output_hidden_states=None,
654
+ return_dict=None,
655
+ cache_position=None,
656
+ ):
657
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
658
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
659
+ output_hidden_states = (
660
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
661
+ )
662
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
663
+
664
+ if input_ids is not None and inputs_embeds is not None:
665
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
666
+ raise ValueError(
667
+ f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
668
+ )
669
+ elif input_ids is not None:
670
+ input_shape = input_ids.size()
671
+ input_ids = input_ids.view(-1, input_shape[-1])
672
+ elif inputs_embeds is not None:
673
+ input_shape = inputs_embeds.size()[:-1]
674
+ else:
675
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
676
+ raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
677
+
678
+ if self.gradient_checkpointing and self.training:
679
+ if use_cache:
680
+ logger.warning_once(
681
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
682
+ )
683
+ use_cache = False
684
+
685
+ if inputs_embeds is None:
686
+ if self.embed_tokens is None:
687
+ raise ValueError("You have to initialize the model with valid token embeddings")
688
+ inputs_embeds = self.embed_tokens(input_ids)
689
+
690
+ batch_size, seq_length = input_shape
691
+
692
+ if use_cache is True:
693
+ if not self.is_decoder:
694
+ raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
695
+
696
+ # initialize past_key_values
697
+ return_legacy_cache = False
698
+ return_self_attention_cache = False
699
+ if self.is_decoder and (use_cache or past_key_values is not None):
700
+ if isinstance(past_key_values, Cache) and not isinstance(past_key_values, EncoderDecoderCache):
701
+ return_self_attention_cache = True
702
+ past_key_values = EncoderDecoderCache(past_key_values, DynamicCache())
703
+ elif not isinstance(past_key_values, EncoderDecoderCache):
704
+ return_legacy_cache = True
705
+ logger.warning_once(
706
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.48.0. "
707
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
708
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
709
+ )
710
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
711
+ elif past_key_values is None:
712
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
713
+ elif not self.is_decoder:
714
+ # do not pass cache object down the line for encoder stack
715
+ # it messes indexing later in decoder-stack because cache object is modified in-place
716
+ past_key_values = None
717
+
718
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
719
+ if cache_position is None:
720
+ cache_position = torch.arange(
721
+ past_key_values_length, past_key_values_length + seq_length, device=inputs_embeds.device
722
+ )
723
+
724
+ if attention_mask is None and not is_torchdynamo_compiling():
725
+ # required mask seq length can be calculated via length of past cache
726
+ mask_seq_length = past_key_values_length + seq_length
727
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
728
+
729
+ if self.is_decoder:
730
+ causal_mask = self._update_causal_mask(
731
+ attention_mask,
732
+ inputs_embeds,
733
+ cache_position,
734
+ past_key_values.self_attention_cache if past_key_values is not None else None,
735
+ output_attentions,
736
+ )
737
+ elif attention_mask is not None:
738
+ causal_mask = attention_mask[:, None, None, :]
739
+ causal_mask = causal_mask.to(dtype=inputs_embeds.dtype)
740
+ causal_mask = (1.0 - causal_mask) * torch.finfo(inputs_embeds.dtype).min
741
+ else:
742
+ causal_mask = None
743
+
744
+ # If a 2D or 3D attention mask is provided for the cross-attention
745
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
746
+ if self.is_decoder and encoder_hidden_states is not None:
747
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
748
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
749
+ if encoder_attention_mask is None:
750
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=inputs_embeds.device)
751
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
752
+ else:
753
+ encoder_extended_attention_mask = None
754
+
755
+ # Prepare head mask if needed
756
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
757
+ cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)
758
+ all_hidden_states = () if output_hidden_states else None
759
+ all_attentions = () if output_attentions else None
760
+ all_cross_attentions = () if output_attentions and self.is_decoder else None
761
+
762
+ hidden_states = self.dropout(inputs_embeds)
763
+
764
+ for i, layer_module in enumerate(self.block):
765
+ layer_head_mask = head_mask[i]
766
+ cross_attn_layer_head_mask = cross_attn_head_mask[i]
767
+
768
+ if output_hidden_states:
769
+ all_hidden_states = all_hidden_states + (hidden_states,)
770
+
771
+ if self.gradient_checkpointing and self.training:
772
+ layer_outputs = self._gradient_checkpointing_func(
773
+ layer_module.forward,
774
+ hidden_states,
775
+ causal_mask,
776
+ encoder_hidden_states,
777
+ encoder_extended_attention_mask,
778
+ layer_head_mask,
779
+ cross_attn_layer_head_mask,
780
+ None, # past_key_value is always None with gradient checkpointing
781
+ use_cache,
782
+ output_attentions,
783
+ cache_position,
784
+ )
785
+ else:
786
+ layer_outputs = layer_module(
787
+ hidden_states,
788
+ attention_mask=causal_mask,
789
+ encoder_hidden_states=encoder_hidden_states,
790
+ encoder_attention_mask=encoder_extended_attention_mask,
791
+ layer_head_mask=layer_head_mask,
792
+ cross_attn_layer_head_mask=cross_attn_layer_head_mask,
793
+ past_key_value=past_key_values,
794
+ use_cache=use_cache,
795
+ output_attentions=output_attentions,
796
+ cache_position=cache_position,
797
+ )
798
+
799
+ hidden_states = layer_outputs[0]
800
+
801
+ if use_cache:
802
+ next_decoder_cache = layer_outputs[1]
803
+
804
+ if output_attentions:
805
+ all_attentions += (layer_outputs[2],)
806
+ if self.is_decoder:
807
+ all_cross_attentions += (layer_outputs[3],)
808
+
809
+ hidden_states = self.final_layer_norm(hidden_states)
810
+ hidden_states = self.dropout(hidden_states)
811
+
812
+ # Add last layer
813
+ if output_hidden_states:
814
+ all_hidden_states = all_hidden_states + (hidden_states,)
815
+
816
+ next_cache = next_decoder_cache if use_cache else None
817
+ if return_self_attention_cache:
818
+ next_cache = past_key_values.self_attention_cache
819
+ if return_legacy_cache:
820
+ next_cache = past_key_values.to_legacy_cache()
821
+
822
+ if not return_dict:
823
+ return tuple(
824
+ v
825
+ for v in [
826
+ hidden_states,
827
+ next_cache,
828
+ all_hidden_states,
829
+ all_attentions,
830
+ all_cross_attentions,
831
+ ]
832
+ if v is not None
833
+ )
834
+ return BaseModelOutputWithPastAndCrossAttentions(
835
+ last_hidden_state=hidden_states,
836
+ past_key_values=next_cache,
837
+ hidden_states=all_hidden_states,
838
+ attentions=all_attentions,
839
+ cross_attentions=all_cross_attentions,
840
+ )
841
+
842
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
843
+ def _update_causal_mask(
844
+ self,
845
+ attention_mask: torch.Tensor,
846
+ input_tensor: torch.Tensor,
847
+ cache_position: torch.Tensor,
848
+ past_key_values: Cache,
849
+ output_attentions: bool,
850
+ ):
851
+ if self.config._attn_implementation == "flash_attention_2":
852
+ if attention_mask is not None and (attention_mask == 0.0).any():
853
+ return attention_mask
854
+ return None
855
+
856
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
857
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
858
+ # to infer the attention mask.
859
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
860
+ using_static_cache = isinstance(past_key_values, StaticCache)
861
+
862
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
863
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
864
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
865
+ attention_mask,
866
+ inputs_embeds=input_tensor,
867
+ past_key_values_length=past_seen_tokens,
868
+ is_training=self.training,
869
+ ):
870
+ return None
871
+
872
+ dtype, device = input_tensor.dtype, input_tensor.device
873
+ sequence_length = input_tensor.shape[1]
874
+ if using_static_cache:
875
+ target_length = past_key_values.get_max_cache_shape()
876
+ else:
877
+ target_length = (
878
+ attention_mask.shape[-1]
879
+ if isinstance(attention_mask, torch.Tensor)
880
+ else past_seen_tokens + sequence_length + 1
881
+ )
882
+
883
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
884
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
885
+ attention_mask,
886
+ sequence_length=sequence_length,
887
+ target_length=target_length,
888
+ dtype=dtype,
889
+ device=device,
890
+ cache_position=cache_position,
891
+ batch_size=input_tensor.shape[0],
892
+ )
893
+
894
+ if (
895
+ self.config._attn_implementation == "sdpa"
896
+ and attention_mask is not None
897
+ and attention_mask.device.type in ["cuda", "xpu"]
898
+ and not output_attentions
899
+ ):
900
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
901
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
902
+ # Details: https://github.com/pytorch/pytorch/issues/110213
903
+ min_dtype = torch.finfo(dtype).min
904
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
905
+
906
+ return causal_mask
907
+
908
+ @staticmethod
909
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_position
910
+ def _prepare_4d_causal_attention_mask_with_cache_position(
911
+ attention_mask: torch.Tensor,
912
+ sequence_length: int,
913
+ target_length: int,
914
+ dtype: torch.dtype,
915
+ device: torch.device,
916
+ cache_position: torch.Tensor,
917
+ batch_size: int,
918
+ **kwargs,
919
+ ):
920
+ """
921
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
922
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
923
+
924
+ Args:
925
+ attention_mask (`torch.Tensor`):
926
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
927
+ `(batch_size, 1, query_length, key_value_length)`.
928
+ sequence_length (`int`):
929
+ The sequence length being processed.
930
+ target_length (`int`):
931
+ The target length: when generating with static cache, the mask should be as long as the static cache,
932
+ to account for the 0 padding, the part of the cache that is not filled yet.
933
+ dtype (`torch.dtype`):
934
+ The dtype to use for the 4D attention mask.
935
+ device (`torch.device`):
936
+ The device to plcae the 4D attention mask on.
937
+ cache_position (`torch.Tensor`):
938
+ Indices depicting the position of the input sequence tokens in the sequence.
939
+ batch_size (`torch.Tensor`):
940
+ Batch size.
941
+ """
942
+ if attention_mask is not None and attention_mask.dim() == 4:
943
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
944
+ causal_mask = attention_mask
945
+ else:
946
+ min_dtype = torch.finfo(dtype).min
947
+ causal_mask = torch.full(
948
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
949
+ )
950
+ if sequence_length != 1:
951
+ causal_mask = torch.triu(causal_mask, diagonal=1)
952
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
953
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
954
+ if attention_mask is not None:
955
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
956
+ mask_length = attention_mask.shape[-1]
957
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
958
+ causal_mask.device
959
+ )
960
+ padding_mask = padding_mask == 0
961
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
962
+ padding_mask, min_dtype
963
+ )
964
+
965
+ return causal_mask
966
+
967
+
968
+ UMT5_START_DOCSTRING = r"""
969
+
970
+ The UMT5 model was proposed in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text
971
+ Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan
972
+ Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu. It's an encoder decoder transformer pre-trained in a
973
+ text-to-text denoising generative setting.
974
+
975
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
976
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
977
+ etc.)
978
+
979
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
980
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
981
+ and behavior.
982
+
983
+ Parameters:
984
+ config ([`UMT5Config`]): Model configuration class with all the parameters of the model.
985
+ Initializing with a config file does not load the weights associated with the model, only the
986
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
987
+ """
988
+
989
+ UMT5_INPUTS_DOCSTRING = r"""
990
+ Args:
991
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
992
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so
993
+ you should be able to pad the inputs on both the right and the left.
994
+
995
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
996
+ [`PreTrainedTokenizer.__call__`] for detail.
997
+
998
+ [What are input IDs?](../glossary#input-ids)
999
+
1000
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1001
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1002
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1003
+
1004
+ - 1 for tokens that are **not masked**,
1005
+ - 0 for tokens that are **masked**.
1006
+
1007
+ [What are attention masks?](../glossary#attention-mask)
1008
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1009
+ Indices of decoder input sequence tokens in the vocabulary.
1010
+
1011
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1012
+ [`PreTrainedTokenizer.__call__`] for details.
1013
+
1014
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1015
+
1016
+ UMT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1017
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1018
+
1019
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [UMT5
1020
+ Training](./umt5#training).
1021
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1022
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1023
+ be used by default.
1024
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1025
+ Mask to nullify selected heads of the self-attention modules in the encoder. Mask values selected in `[0,
1026
+ 1]`:
1027
+
1028
+ - 1 indicates the head is **not masked**,
1029
+ - 0 indicates the head is **masked**.
1030
+
1031
+ decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1032
+ Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
1033
+ 1]`:
1034
+
1035
+ - 1 indicates the head is **not masked**,
1036
+ - 0 indicates the head is **masked**.
1037
+
1038
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1039
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
1040
+ `[0, 1]`:
1041
+
1042
+ - 1 indicates the head is **not masked**,
1043
+ - 0 indicates the head is **masked**.
1044
+
1045
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
1046
+ Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
1047
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
1048
+ the output of the last layer of the encoder. Used in the cross-attention of the decoder.
1049
+ 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)`):
1050
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1051
+
1052
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1053
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1054
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1055
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1056
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1057
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1058
+ model's internal embedding lookup matrix.
1059
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
1060
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
1061
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
1062
+ input (see `past_key_values`). This is useful if you want more control over how to convert
1063
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
1064
+
1065
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
1066
+ of `inputs_embeds`.
1067
+
1068
+ use_cache (`bool`, *optional*):
1069
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1070
+ `past_key_values`).
1071
+
1072
+ output_attentions (`bool`, *optional*):
1073
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1074
+ tensors for more detail.
1075
+ output_hidden_states (`bool`, *optional*):
1076
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1077
+ more detail.
1078
+ return_dict (`bool`, *optional*):
1079
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1080
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1081
+ Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
1082
+ cache in the correct position and to infer the complete sequence length.
1083
+ """
1084
+
1085
+ UMT5_ENCODER_INPUTS_DOCSTRING = r"""
1086
+ Args:
1087
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1088
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so
1089
+ you should be able to pad the inputs on both the right and the left.
1090
+
1091
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1092
+ [`PreTrainedTokenizer.__call__`] for detail.
1093
+
1094
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1095
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1096
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1097
+
1098
+ - 1 for tokens that are **not masked**,
1099
+ - 0 for tokens that are **masked**.
1100
+
1101
+ [What are attention masks?](../glossary#attention-mask)
1102
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1103
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1104
+
1105
+ - 1 indicates the head is **not masked**,
1106
+ - 0 indicates the head is **masked**.
1107
+
1108
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1109
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1110
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1111
+ model's internal embedding lookup matrix.
1112
+ output_attentions (`bool`, *optional*):
1113
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1114
+ tensors for more detail.
1115
+ output_hidden_states (`bool`, *optional*):
1116
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1117
+ more detail.
1118
+ return_dict (`bool`, *optional*):
1119
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1120
+ """
1121
+
1122
+
1123
+ @add_start_docstrings(
1124
+ "The bare UMT5 Model transformer outputting raw hidden-states without any specific head on top.",
1125
+ UMT5_START_DOCSTRING,
1126
+ )
1127
+ class UMT5Model(UMT5PreTrainedModel):
1128
+ r"""
1129
+ Examples:
1130
+
1131
+ ```python
1132
+ >>> from transformers import UMT5Model, AutoTokenizer
1133
+
1134
+ >>> model = UMT5Model.from_pretrained("google/umt5-small")
1135
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1136
+ >>> noisy_text = "UN Offizier sagt, dass weiter <extra_id_0> werden muss in Syrien."
1137
+ >>> label = "<extra_id_0> verhandelt"
1138
+ >>> inputs = tokenizer(inputs, return_tensors="pt")
1139
+ >>> labels = tokenizer(label=label, return_tensors="pt")
1140
+
1141
+ >>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=labels["input_ids"])
1142
+ >>> hidden_states = outputs.last_hidden_state
1143
+ ```"""
1144
+
1145
+ model_type = "umt5"
1146
+ config_class = UMT5Config
1147
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1148
+
1149
+ def __init__(self, config):
1150
+ super().__init__(config)
1151
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1152
+
1153
+ encoder_config = copy.deepcopy(config)
1154
+ encoder_config.is_decoder = False
1155
+ encoder_config.use_cache = False
1156
+ encoder_config.is_encoder_decoder = False
1157
+ self.encoder = UMT5Stack(encoder_config, self.shared)
1158
+
1159
+ decoder_config = copy.deepcopy(config)
1160
+ decoder_config.is_decoder = True
1161
+ decoder_config.is_encoder_decoder = False
1162
+ decoder_config.num_layers = config.num_decoder_layers
1163
+ self.decoder = UMT5Stack(decoder_config, self.shared)
1164
+
1165
+ # Initialize weights and apply final processing
1166
+ self.post_init()
1167
+
1168
+ # Copied from transformers.models.t5.modeling_t5.T5Model.get_input_embeddings
1169
+ def get_input_embeddings(self):
1170
+ return self.shared
1171
+
1172
+ # Copied from transformers.models.t5.modeling_t5.T5Model.set_input_embeddings
1173
+ def set_input_embeddings(self, new_embeddings):
1174
+ self.shared = new_embeddings
1175
+ self.encoder.set_input_embeddings(new_embeddings)
1176
+ self.decoder.set_input_embeddings(new_embeddings)
1177
+
1178
+ # Copied from transformers.models.t5.modeling_t5.T5Model._tie_weights
1179
+ def _tie_weights(self):
1180
+ if self.config.tie_word_embeddings:
1181
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1182
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1183
+
1184
+ # Copied from transformers.models.t5.modeling_t5.T5Model.get_encoder
1185
+ def get_encoder(self):
1186
+ return self.encoder
1187
+
1188
+ # Copied from transformers.models.t5.modeling_t5.T5Model.get_decoder
1189
+ def get_decoder(self):
1190
+ return self.decoder
1191
+
1192
+ # Copied from transformers.models.t5.modeling_t5.T5Model._prune_heads
1193
+ def _prune_heads(self, heads_to_prune):
1194
+ """
1195
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1196
+ class PreTrainedModel
1197
+ """
1198
+ for layer, heads in heads_to_prune.items():
1199
+ self.encoder.layer[layer].attention.prune_heads(heads)
1200
+
1201
+ @add_start_docstrings_to_model_forward(UMT5_INPUTS_DOCSTRING)
1202
+ @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
1203
+ def forward(
1204
+ self,
1205
+ input_ids: Optional[torch.LongTensor] = None,
1206
+ attention_mask: Optional[torch.FloatTensor] = None,
1207
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1208
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1209
+ head_mask: Optional[torch.FloatTensor] = None,
1210
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
1211
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1212
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1213
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1214
+ inputs_embeds: Optional[torch.Tensor] = None,
1215
+ decoder_inputs_embeds: Optional[torch.Tensor] = None,
1216
+ use_cache: Optional[bool] = None,
1217
+ output_attentions: Optional[bool] = None,
1218
+ output_hidden_states: Optional[bool] = None,
1219
+ return_dict: Optional[bool] = None,
1220
+ cache_position: Optional[torch.LongTensor] = None,
1221
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:
1222
+ r"""
1223
+ Returns:
1224
+
1225
+ Example:
1226
+
1227
+ ```python
1228
+ >>> from transformers import AutoTokenizer, UMT5Model
1229
+
1230
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1231
+ >>> model = UMT5Model.from_pretrained("google/umt5-small")
1232
+
1233
+ >>> input_ids = tokenizer(
1234
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1235
+ ... ).input_ids # Batch size 1
1236
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
1237
+
1238
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for UMT5Model.
1239
+ >>> # This is not needed for torch's UMT5ForConditionalGeneration as it does this internally using labels arg.
1240
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
1241
+
1242
+ >>> # forward pass
1243
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
1244
+ >>> last_hidden_states = outputs.last_hidden_state
1245
+ ```"""
1246
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1247
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1248
+
1249
+ # Encode if needed (training, first prediction pass)
1250
+ if encoder_outputs is None:
1251
+ encoder_outputs = self.encoder(
1252
+ input_ids=input_ids,
1253
+ attention_mask=attention_mask,
1254
+ inputs_embeds=inputs_embeds,
1255
+ head_mask=head_mask,
1256
+ output_attentions=output_attentions,
1257
+ output_hidden_states=output_hidden_states,
1258
+ return_dict=return_dict,
1259
+ )
1260
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1261
+ encoder_outputs = BaseModelOutput(
1262
+ last_hidden_state=encoder_outputs[0],
1263
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1264
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1265
+ )
1266
+
1267
+ hidden_states = encoder_outputs[0]
1268
+
1269
+ # Decode
1270
+ decoder_outputs = self.decoder(
1271
+ input_ids=decoder_input_ids,
1272
+ attention_mask=decoder_attention_mask,
1273
+ inputs_embeds=decoder_inputs_embeds,
1274
+ past_key_values=past_key_values,
1275
+ encoder_hidden_states=hidden_states,
1276
+ encoder_attention_mask=attention_mask,
1277
+ head_mask=decoder_head_mask,
1278
+ cross_attn_head_mask=cross_attn_head_mask,
1279
+ use_cache=use_cache,
1280
+ output_attentions=output_attentions,
1281
+ output_hidden_states=output_hidden_states,
1282
+ return_dict=return_dict,
1283
+ cache_position=cache_position,
1284
+ )
1285
+
1286
+ if not return_dict:
1287
+ return decoder_outputs + encoder_outputs
1288
+
1289
+ return Seq2SeqModelOutput(
1290
+ last_hidden_state=decoder_outputs.last_hidden_state,
1291
+ past_key_values=decoder_outputs.past_key_values,
1292
+ decoder_hidden_states=decoder_outputs.hidden_states,
1293
+ decoder_attentions=decoder_outputs.attentions,
1294
+ cross_attentions=decoder_outputs.cross_attentions,
1295
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1296
+ encoder_hidden_states=encoder_outputs.hidden_states,
1297
+ encoder_attentions=encoder_outputs.attentions,
1298
+ )
1299
+
1300
+
1301
+ @add_start_docstrings("""UMT5 Model with a `language modeling` head on top.""", UMT5_START_DOCSTRING)
1302
+ class UMT5ForConditionalGeneration(UMT5PreTrainedModel, GenerationMixin):
1303
+ r"""
1304
+ Examples:
1305
+
1306
+ ```python
1307
+ >>> from transformers import UMT5ForConditionalGeneration, AutoTokenizer
1308
+
1309
+ >>> model = UMT5ForConditionalGeneration.from_pretrained("google/umt5-small")
1310
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1311
+ >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
1312
+ >>> summary = "Weiter Verhandlung in Syrien."
1313
+ >>> inputs = tokenizer(article, text_target=summary, return_tensors="pt")
1314
+
1315
+ >>> outputs = model(**inputs)
1316
+ >>> loss = outputs.loss
1317
+ ```"""
1318
+
1319
+ model_type = "umt5"
1320
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
1321
+
1322
+ def __init__(self, config):
1323
+ super().__init__(config)
1324
+ self.model_dim = config.d_model
1325
+
1326
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1327
+
1328
+ encoder_config = copy.deepcopy(config)
1329
+ encoder_config.is_decoder = False
1330
+ encoder_config.use_cache = False
1331
+ encoder_config.is_encoder_decoder = False
1332
+ self.encoder = UMT5Stack(encoder_config, self.shared)
1333
+
1334
+ decoder_config = copy.deepcopy(config)
1335
+ decoder_config.is_decoder = True
1336
+ decoder_config.is_encoder_decoder = False
1337
+ decoder_config.num_layers = config.num_decoder_layers
1338
+ self.decoder = UMT5Stack(decoder_config, self.shared)
1339
+
1340
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
1341
+
1342
+ # Initialize weights and apply final processing
1343
+ self.post_init()
1344
+
1345
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.get_input_embeddings
1346
+ def get_input_embeddings(self):
1347
+ return self.shared
1348
+
1349
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.set_input_embeddings
1350
+ def set_input_embeddings(self, new_embeddings):
1351
+ self.shared = new_embeddings
1352
+ self.encoder.set_input_embeddings(new_embeddings)
1353
+ self.decoder.set_input_embeddings(new_embeddings)
1354
+
1355
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration._tie_weights
1356
+ def _tie_weights(self):
1357
+ if self.config.tie_word_embeddings:
1358
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1359
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1360
+
1361
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.set_output_embeddings
1362
+ def set_output_embeddings(self, new_embeddings):
1363
+ self.lm_head = new_embeddings
1364
+
1365
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.get_output_embeddings
1366
+ def get_output_embeddings(self):
1367
+ return self.lm_head
1368
+
1369
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.get_encoder
1370
+ def get_encoder(self):
1371
+ return self.encoder
1372
+
1373
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.get_decoder
1374
+ def get_decoder(self):
1375
+ return self.decoder
1376
+
1377
+ @add_start_docstrings_to_model_forward(UMT5_INPUTS_DOCSTRING)
1378
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1379
+ def forward(
1380
+ self,
1381
+ input_ids: Optional[torch.LongTensor] = None,
1382
+ attention_mask: Optional[torch.FloatTensor] = None,
1383
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1384
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1385
+ head_mask: Optional[torch.FloatTensor] = None,
1386
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
1387
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1388
+ encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1389
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1390
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1391
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1392
+ labels: Optional[torch.LongTensor] = None,
1393
+ use_cache: Optional[bool] = None,
1394
+ output_attentions: Optional[bool] = None,
1395
+ output_hidden_states: Optional[bool] = None,
1396
+ return_dict: Optional[bool] = None,
1397
+ cache_position: Optional[torch.LongTensor] = None,
1398
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
1399
+ r"""
1400
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1401
+ Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
1402
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
1403
+ labels in `[0, ..., config.vocab_size]`
1404
+
1405
+ Returns:
1406
+
1407
+ Examples:
1408
+
1409
+ ```python
1410
+ >>> from transformers import AutoTokenizer, UMT5ForConditionalGeneration
1411
+
1412
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1413
+ >>> model = UMT5ForConditionalGeneration.from_pretrained("google/umt5-small")
1414
+
1415
+ >>> # training
1416
+ >>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
1417
+ >>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
1418
+ >>> outputs = model(input_ids=input_ids, labels=labels)
1419
+ >>> loss = outputs.loss
1420
+ >>> logits = outputs.logits
1421
+
1422
+ >>> # inference
1423
+ >>> input_ids = tokenizer("Studies have shown that <extra_id_0> good for you", return_tensors="pt").input_ids
1424
+ >>> outputs = model.generate(input_ids)
1425
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
1426
+ ```"""
1427
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1428
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1429
+
1430
+ # Encode if needed (training, first prediction pass)
1431
+ if encoder_outputs is None:
1432
+ # Convert encoder inputs in embeddings if needed
1433
+ encoder_outputs = self.encoder(
1434
+ input_ids=input_ids,
1435
+ attention_mask=attention_mask,
1436
+ inputs_embeds=inputs_embeds,
1437
+ head_mask=head_mask,
1438
+ output_attentions=output_attentions,
1439
+ output_hidden_states=output_hidden_states,
1440
+ return_dict=return_dict,
1441
+ )
1442
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1443
+ encoder_outputs = BaseModelOutput(
1444
+ last_hidden_state=encoder_outputs[0],
1445
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1446
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1447
+ )
1448
+
1449
+ hidden_states = encoder_outputs[0]
1450
+
1451
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
1452
+ # get decoder inputs from shifting lm labels to the right
1453
+ decoder_input_ids = self._shift_right(labels)
1454
+
1455
+ # Decode
1456
+ decoder_outputs = self.decoder(
1457
+ input_ids=decoder_input_ids,
1458
+ attention_mask=decoder_attention_mask,
1459
+ inputs_embeds=decoder_inputs_embeds,
1460
+ past_key_values=past_key_values,
1461
+ encoder_hidden_states=hidden_states,
1462
+ encoder_attention_mask=attention_mask,
1463
+ head_mask=decoder_head_mask,
1464
+ cross_attn_head_mask=cross_attn_head_mask,
1465
+ use_cache=use_cache,
1466
+ output_attentions=output_attentions,
1467
+ output_hidden_states=output_hidden_states,
1468
+ return_dict=return_dict,
1469
+ cache_position=cache_position,
1470
+ )
1471
+
1472
+ sequence_output = decoder_outputs[0]
1473
+
1474
+ if self.config.tie_word_embeddings:
1475
+ # Rescale output before projecting on vocab
1476
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
1477
+ sequence_output = sequence_output * (self.model_dim**-0.5)
1478
+
1479
+ lm_logits = self.lm_head(sequence_output)
1480
+
1481
+ loss = None
1482
+ if labels is not None:
1483
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1484
+ # move labels to correct device to enable PP
1485
+ labels = labels.to(lm_logits.device)
1486
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
1487
+
1488
+ if not return_dict:
1489
+ output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
1490
+ return ((loss,) + output) if loss is not None else output
1491
+
1492
+ return Seq2SeqLMOutput(
1493
+ loss=loss,
1494
+ logits=lm_logits,
1495
+ past_key_values=decoder_outputs.past_key_values,
1496
+ decoder_hidden_states=decoder_outputs.hidden_states,
1497
+ decoder_attentions=decoder_outputs.attentions,
1498
+ cross_attentions=decoder_outputs.cross_attentions,
1499
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1500
+ encoder_hidden_states=encoder_outputs.hidden_states,
1501
+ encoder_attentions=encoder_outputs.attentions,
1502
+ )
1503
+
1504
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.prepare_decoder_input_ids_from_labels
1505
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1506
+ return self._shift_right(labels)
1507
+
1508
+ @staticmethod
1509
+ def _reorder_cache(past_key_values, beam_idx):
1510
+ reordered_past = ()
1511
+ for layer_past in past_key_values:
1512
+ reordered_past += (
1513
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1514
+ )
1515
+ return reordered_past
1516
+
1517
+
1518
+ @add_start_docstrings(
1519
+ "The bare UMT5 Model transformer outputting encoder's raw hidden-states without any specific head on top.",
1520
+ UMT5_START_DOCSTRING,
1521
+ )
1522
+ class UMT5EncoderModel(UMT5PreTrainedModel):
1523
+ r"""
1524
+ Examples:
1525
+
1526
+ ```python
1527
+ >>> from transformers import UMT5EncoderModel, AutoTokenizer
1528
+
1529
+ >>> model = UMT5EncoderModel.from_pretrained("google/umt5-small")
1530
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1531
+ >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
1532
+ >>> input_ids = tokenizer(article, return_tensors="pt").input_ids
1533
+ >>> outputs = model(input_ids)
1534
+ >>> hidden_state = outputs.last_hidden_state
1535
+ ```"""
1536
+
1537
+ model_type = "umt5"
1538
+ # config_class = UMT5Config
1539
+ _tied_weights_keys = ["encoder.embed_tokens.weight"]
1540
+
1541
+ def __init__(self, config):
1542
+ super().__init__(config)
1543
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1544
+
1545
+ encoder_config = copy.deepcopy(config)
1546
+ encoder_config.use_cache = False
1547
+ encoder_config.is_encoder_decoder = False
1548
+ self.encoder = UMT5Stack(encoder_config, self.shared)
1549
+
1550
+ # Initialize weights and apply final processing
1551
+ self.post_init()
1552
+
1553
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.get_input_embeddings
1554
+ def get_input_embeddings(self):
1555
+ return self.shared
1556
+
1557
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.set_input_embeddings
1558
+ def set_input_embeddings(self, new_embeddings):
1559
+ self.shared = new_embeddings
1560
+ self.encoder.set_input_embeddings(new_embeddings)
1561
+
1562
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel._tie_weights
1563
+ def _tie_weights(self):
1564
+ if self.config.tie_word_embeddings:
1565
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1566
+
1567
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.get_encoder
1568
+ def get_encoder(self):
1569
+ return self.encoder
1570
+
1571
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel._prune_heads
1572
+ def _prune_heads(self, heads_to_prune):
1573
+ """
1574
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1575
+ class PreTrainedModel
1576
+ """
1577
+ for layer, heads in heads_to_prune.items():
1578
+ self.encoder.block[layer].layer[0].SelfAttention.prune_heads(heads)
1579
+
1580
+ @add_start_docstrings_to_model_forward(UMT5_ENCODER_INPUTS_DOCSTRING)
1581
+ @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
1582
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.forward with T5->UMT5, google-t5/t5-small->google/umt5-small
1583
+ def forward(
1584
+ self,
1585
+ input_ids: Optional[torch.LongTensor] = None,
1586
+ attention_mask: Optional[torch.FloatTensor] = None,
1587
+ head_mask: Optional[torch.FloatTensor] = None,
1588
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1589
+ output_attentions: Optional[bool] = None,
1590
+ output_hidden_states: Optional[bool] = None,
1591
+ return_dict: Optional[bool] = None,
1592
+ ) -> Union[Tuple[torch.FloatTensor], BaseModelOutput]:
1593
+ r"""
1594
+ Returns:
1595
+
1596
+ Example:
1597
+
1598
+ ```python
1599
+ >>> from transformers import AutoTokenizer, UMT5EncoderModel
1600
+
1601
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1602
+ >>> model = UMT5EncoderModel.from_pretrained("google/umt5-small")
1603
+ >>> input_ids = tokenizer(
1604
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1605
+ ... ).input_ids # Batch size 1
1606
+ >>> outputs = model(input_ids=input_ids)
1607
+ >>> last_hidden_states = outputs.last_hidden_state
1608
+ ```"""
1609
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1610
+
1611
+ encoder_outputs = self.encoder(
1612
+ input_ids=input_ids,
1613
+ attention_mask=attention_mask,
1614
+ inputs_embeds=inputs_embeds,
1615
+ head_mask=head_mask,
1616
+ output_attentions=output_attentions,
1617
+ output_hidden_states=output_hidden_states,
1618
+ return_dict=return_dict,
1619
+ )
1620
+
1621
+ return encoder_outputs
1622
+
1623
+
1624
+ @add_start_docstrings(
1625
+ """
1626
+ UMT5 model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
1627
+ tasks.
1628
+ """,
1629
+ UMT5_START_DOCSTRING,
1630
+ )
1631
+ class UMT5ForSequenceClassification(UMT5PreTrainedModel):
1632
+ _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
1633
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1634
+
1635
+ # Copied from transformers.models.t5.modeling_t5.T5ForSequenceClassification.__init__ with T5->UMT5
1636
+ def __init__(self, config: UMT5Config):
1637
+ super().__init__(config)
1638
+ self.transformer = UMT5Model(config)
1639
+ self.classification_head = UMT5ClassificationHead(config)
1640
+
1641
+ # Initialize weights and apply final processing
1642
+ self.post_init()
1643
+
1644
+ self.model_parallel = False
1645
+
1646
+ @add_start_docstrings_to_model_forward(UMT5_INPUTS_DOCSTRING)
1647
+ @replace_return_docstrings(output_type=Seq2SeqSequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
1648
+ def forward(
1649
+ self,
1650
+ input_ids: torch.LongTensor = None,
1651
+ attention_mask: Optional[torch.Tensor] = None,
1652
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1653
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1654
+ head_mask: Optional[torch.Tensor] = None,
1655
+ decoder_head_mask: Optional[torch.Tensor] = None,
1656
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1657
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1658
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1659
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1660
+ labels: Optional[torch.LongTensor] = None,
1661
+ use_cache: Optional[bool] = None,
1662
+ output_attentions: Optional[bool] = None,
1663
+ output_hidden_states: Optional[bool] = None,
1664
+ return_dict: Optional[bool] = None,
1665
+ ) -> Union[Tuple, Seq2SeqSequenceClassifierOutput]:
1666
+ r"""
1667
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1668
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1669
+ config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1670
+ Returns:
1671
+ """
1672
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1673
+ if labels is not None:
1674
+ use_cache = False
1675
+
1676
+ if input_ids is None and inputs_embeds is not None:
1677
+ raise NotImplementedError(
1678
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
1679
+ )
1680
+
1681
+ # Copied from models.bart.modeling_bart.BartModel.forward different to other models, T5 automatically creates
1682
+ # decoder_input_ids from input_ids if no decoder_input_ids are provided
1683
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1684
+ if input_ids is None:
1685
+ raise ValueError(
1686
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
1687
+ "passed, `input_ids` cannot be `None`. Please pass either "
1688
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
1689
+ )
1690
+ decoder_input_ids = self._shift_right(input_ids)
1691
+
1692
+ outputs = self.transformer(
1693
+ input_ids,
1694
+ attention_mask=attention_mask,
1695
+ decoder_input_ids=decoder_input_ids,
1696
+ decoder_attention_mask=decoder_attention_mask,
1697
+ head_mask=head_mask,
1698
+ decoder_head_mask=decoder_head_mask,
1699
+ cross_attn_head_mask=cross_attn_head_mask,
1700
+ encoder_outputs=encoder_outputs,
1701
+ inputs_embeds=inputs_embeds,
1702
+ decoder_inputs_embeds=decoder_inputs_embeds,
1703
+ use_cache=use_cache,
1704
+ output_attentions=output_attentions,
1705
+ output_hidden_states=output_hidden_states,
1706
+ return_dict=return_dict,
1707
+ )
1708
+ sequence_output = outputs[0]
1709
+
1710
+ eos_mask = input_ids.eq(self.config.eos_token_id).to(sequence_output.device)
1711
+
1712
+ if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
1713
+ raise ValueError("All examples must have the same number of <eos> tokens.")
1714
+ batch_size, _, hidden_size = sequence_output.shape
1715
+ sentence_representation = sequence_output[eos_mask, :].view(batch_size, -1, hidden_size)[:, -1, :]
1716
+ logits = self.classification_head(sentence_representation)
1717
+
1718
+ loss = None
1719
+ if labels is not None:
1720
+ labels = labels.to(logits.device)
1721
+ if self.config.problem_type is None:
1722
+ if self.config.num_labels == 1:
1723
+ self.config.problem_type = "regression"
1724
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1725
+ self.config.problem_type = "single_label_classification"
1726
+ else:
1727
+ self.config.problem_type = "multi_label_classification"
1728
+
1729
+ if self.config.problem_type == "regression":
1730
+ loss_fct = MSELoss()
1731
+ if self.config.num_labels == 1:
1732
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1733
+ else:
1734
+ loss = loss_fct(logits, labels)
1735
+ elif self.config.problem_type == "single_label_classification":
1736
+ loss_fct = CrossEntropyLoss()
1737
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1738
+ elif self.config.problem_type == "multi_label_classification":
1739
+ loss_fct = BCEWithLogitsLoss()
1740
+ loss = loss_fct(logits, labels)
1741
+ if not return_dict:
1742
+ output = (logits,) + outputs[1:]
1743
+ return ((loss,) + output) if loss is not None else output
1744
+
1745
+ return Seq2SeqSequenceClassifierOutput(
1746
+ loss=loss,
1747
+ logits=logits,
1748
+ past_key_values=outputs.past_key_values,
1749
+ decoder_hidden_states=outputs.decoder_hidden_states,
1750
+ decoder_attentions=outputs.decoder_attentions,
1751
+ cross_attentions=outputs.cross_attentions,
1752
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1753
+ encoder_hidden_states=outputs.encoder_hidden_states,
1754
+ encoder_attentions=outputs.encoder_attentions,
1755
+ )
1756
+
1757
+
1758
+ @add_start_docstrings(
1759
+ """
1760
+ UMT5 Encoder Model with a token classification head on top (a linear layer on top of the hidden-states output)
1761
+ e.g. for Named-Entity-Recognition (NER) tasks.
1762
+ """,
1763
+ UMT5_START_DOCSTRING,
1764
+ )
1765
+ class UMT5ForTokenClassification(UMT5PreTrainedModel):
1766
+ _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
1767
+ _tied_weights_keys = ["transformer.encoder.embed_tokens.weight"]
1768
+
1769
+ # Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.__init__ with T5->UMT5
1770
+ def __init__(self, config: UMT5Config):
1771
+ super().__init__(config)
1772
+ self.num_labels = config.num_labels
1773
+
1774
+ self.transformer = UMT5EncoderModel(config)
1775
+ self.dropout = nn.Dropout(config.classifier_dropout)
1776
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1777
+
1778
+ # Initialize weights and apply final processing
1779
+ self.post_init()
1780
+
1781
+ @add_start_docstrings_to_model_forward(UMT5_INPUTS_DOCSTRING)
1782
+ @replace_return_docstrings(output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC)
1783
+ # Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.forward with T5->UMT5
1784
+ def forward(
1785
+ self,
1786
+ input_ids: Optional[torch.Tensor] = None,
1787
+ attention_mask: Optional[torch.Tensor] = None,
1788
+ head_mask: Optional[torch.Tensor] = None,
1789
+ inputs_embeds: Optional[torch.Tensor] = None,
1790
+ labels: Optional[torch.Tensor] = None,
1791
+ output_attentions: Optional[bool] = None,
1792
+ output_hidden_states: Optional[bool] = None,
1793
+ return_dict: Optional[bool] = None,
1794
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1795
+ r"""
1796
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1797
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1798
+ Returns:
1799
+ """
1800
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1801
+
1802
+ outputs = self.transformer(
1803
+ input_ids,
1804
+ attention_mask=attention_mask,
1805
+ head_mask=head_mask,
1806
+ inputs_embeds=inputs_embeds,
1807
+ output_attentions=output_attentions,
1808
+ output_hidden_states=output_hidden_states,
1809
+ return_dict=return_dict,
1810
+ )
1811
+
1812
+ hidden_states = outputs[0]
1813
+ hidden_states = self.dropout(hidden_states)
1814
+ logits = self.classifier(hidden_states)
1815
+
1816
+ loss = None
1817
+ if labels is not None:
1818
+ loss_fct = CrossEntropyLoss()
1819
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1820
+
1821
+ if not return_dict:
1822
+ output = (logits, outputs[2:-1])
1823
+ return ((loss,) + output) if loss is not None else output
1824
+
1825
+ return TokenClassifierOutput(
1826
+ loss=loss,
1827
+ logits=logits,
1828
+ hidden_states=outputs.hidden_states,
1829
+ attentions=outputs.attentions,
1830
+ )
1831
+
1832
+
1833
+ @add_start_docstrings(
1834
+ """
1835
+ UMT5 Model with a span classification head on top for extractive question-answering tasks like SQuAD (linear layers
1836
+ on top of the hidden-states output to compute `span start logits` and `span end logits`).
1837
+ """,
1838
+ UMT5_START_DOCSTRING,
1839
+ )
1840
+ class UMT5ForQuestionAnswering(UMT5PreTrainedModel):
1841
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1842
+
1843
+ def __init__(self, config):
1844
+ super().__init__(config)
1845
+ self.model_dim = config.d_model
1846
+
1847
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1848
+
1849
+ encoder_config = copy.deepcopy(config)
1850
+ encoder_config.is_decoder = False
1851
+ encoder_config.use_cache = False
1852
+ encoder_config.is_encoder_decoder = False
1853
+ self.encoder = UMT5Stack(encoder_config, self.shared)
1854
+
1855
+ decoder_config = copy.deepcopy(config)
1856
+ decoder_config.is_decoder = True
1857
+ decoder_config.is_encoder_decoder = False
1858
+ decoder_config.num_layers = config.num_decoder_layers
1859
+ self.decoder = UMT5Stack(decoder_config, self.shared)
1860
+
1861
+ self.num_labels = config.num_labels
1862
+ self.qa_outputs = nn.Linear(config.d_model, config.num_labels)
1863
+
1864
+ # Initialize weights and apply final processing
1865
+ self.post_init()
1866
+
1867
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.get_input_embeddings
1868
+ def get_input_embeddings(self):
1869
+ return self.shared
1870
+
1871
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.set_input_embeddings
1872
+ def set_input_embeddings(self, new_embeddings):
1873
+ self.shared = new_embeddings
1874
+ self.encoder.set_input_embeddings(new_embeddings)
1875
+ self.decoder.set_input_embeddings(new_embeddings)
1876
+
1877
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering._tie_weights
1878
+ def _tie_weights(self):
1879
+ if self.config.tie_word_embeddings:
1880
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1881
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1882
+
1883
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.get_encoder
1884
+ def get_encoder(self):
1885
+ return self.encoder
1886
+
1887
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.get_decoder
1888
+ def get_decoder(self):
1889
+ return self.decoder
1890
+
1891
+ @add_start_docstrings_to_model_forward(UMT5_INPUTS_DOCSTRING)
1892
+ @replace_return_docstrings(output_type=Seq2SeqQuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC)
1893
+ def forward(
1894
+ self,
1895
+ input_ids: Optional[torch.LongTensor] = None,
1896
+ attention_mask: Optional[torch.FloatTensor] = None,
1897
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1898
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1899
+ head_mask: Optional[torch.FloatTensor] = None,
1900
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
1901
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1902
+ encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1903
+ start_positions: Optional[torch.LongTensor] = None,
1904
+ end_positions: Optional[torch.LongTensor] = None,
1905
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1906
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1907
+ use_cache: Optional[bool] = None,
1908
+ output_attentions: Optional[bool] = None,
1909
+ output_hidden_states: Optional[bool] = None,
1910
+ return_dict: Optional[bool] = None,
1911
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqQuestionAnsweringModelOutput]:
1912
+ r"""
1913
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1914
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1915
+ Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
1916
+ are not taken into account for computing the loss.
1917
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1918
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1919
+ Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
1920
+ are not taken into account for computing the loss.
1921
+ Returns:
1922
+ """
1923
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1924
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1925
+ if start_positions is not None and end_positions is not None:
1926
+ use_cache = False
1927
+
1928
+ # Copied from models.bart.modeling_bart.BartModel.forward
1929
+ # different to other models, T5 automatically creates decoder_input_ids from
1930
+ # input_ids if no decoder_input_ids are provided
1931
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1932
+ if input_ids is None:
1933
+ raise ValueError(
1934
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
1935
+ "passed, `input_ids` cannot be `None`. Please pass either "
1936
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
1937
+ )
1938
+ decoder_input_ids = self._shift_right(input_ids)
1939
+
1940
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1941
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1942
+
1943
+ # Encode if needed (training, first prediction pass)
1944
+ if encoder_outputs is None:
1945
+ encoder_outputs = self.encoder(
1946
+ input_ids=input_ids,
1947
+ attention_mask=attention_mask,
1948
+ inputs_embeds=inputs_embeds,
1949
+ head_mask=head_mask,
1950
+ output_attentions=output_attentions,
1951
+ output_hidden_states=output_hidden_states,
1952
+ return_dict=return_dict,
1953
+ )
1954
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1955
+ encoder_outputs = BaseModelOutput(
1956
+ last_hidden_state=encoder_outputs[0],
1957
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1958
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1959
+ )
1960
+
1961
+ hidden_states = encoder_outputs[0]
1962
+
1963
+ # Decode
1964
+ decoder_outputs = self.decoder(
1965
+ input_ids=decoder_input_ids,
1966
+ attention_mask=decoder_attention_mask,
1967
+ inputs_embeds=decoder_inputs_embeds,
1968
+ past_key_values=None,
1969
+ encoder_hidden_states=hidden_states,
1970
+ encoder_attention_mask=attention_mask,
1971
+ head_mask=decoder_head_mask,
1972
+ cross_attn_head_mask=cross_attn_head_mask,
1973
+ use_cache=use_cache,
1974
+ output_attentions=output_attentions,
1975
+ output_hidden_states=output_hidden_states,
1976
+ return_dict=return_dict,
1977
+ )
1978
+
1979
+ sequence_output = decoder_outputs[0]
1980
+
1981
+ logits = self.qa_outputs(sequence_output)
1982
+ start_logits, end_logits = logits.split(1, dim=-1)
1983
+ start_logits = start_logits.squeeze(-1).contiguous()
1984
+ end_logits = end_logits.squeeze(-1).contiguous()
1985
+
1986
+ total_loss = None
1987
+ if start_positions is not None and end_positions is not None:
1988
+ # If we are on multi-GPU, split add a dimension
1989
+ if len(start_positions.size()) > 1:
1990
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1991
+ if len(end_positions.size()) > 1:
1992
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1993
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1994
+ ignored_index = start_logits.size(1)
1995
+ start_positions = start_positions.clamp(0, ignored_index)
1996
+ end_positions = end_positions.clamp(0, ignored_index)
1997
+
1998
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1999
+ start_loss = loss_fct(start_logits, start_positions)
2000
+ end_loss = loss_fct(end_logits, end_positions)
2001
+ total_loss = (start_loss + end_loss) / 2
2002
+
2003
+ if not return_dict:
2004
+ output = (start_logits, end_logits) + decoder_outputs[1:] + encoder_outputs
2005
+ return ((total_loss,) + output) if total_loss is not None else output
2006
+
2007
+ return Seq2SeqQuestionAnsweringModelOutput(
2008
+ loss=total_loss,
2009
+ start_logits=start_logits,
2010
+ end_logits=end_logits,
2011
+ past_key_values=decoder_outputs.past_key_values,
2012
+ decoder_hidden_states=decoder_outputs.hidden_states,
2013
+ decoder_attentions=decoder_outputs.attentions,
2014
+ cross_attentions=decoder_outputs.cross_attentions,
2015
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
2016
+ encoder_hidden_states=encoder_outputs.hidden_states,
2017
+ encoder_attentions=encoder_outputs.attentions,
2018
+ )
2019
+
2020
+
2021
+ __all__ = [
2022
+ "UMT5EncoderModel",
2023
+ "UMT5ForConditionalGeneration",
2024
+ "UMT5ForQuestionAnswering",
2025
+ "UMT5ForSequenceClassification",
2026
+ "UMT5ForTokenClassification",
2027
+ "UMT5Model",
2028
+ "UMT5PreTrainedModel",
2029
+ ]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_unispeech import *
22
+ from .modeling_unispeech import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/configuration_unispeech.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """UniSpeech model configuration"""
16
+
17
+ import functools
18
+ import operator
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class UniSpeechConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`UniSpeechModel`]. It is used to instantiate an
30
+ UniSpeech model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the UniSpeech
32
+ [microsoft/unispeech-large-1500h-cv](https://huggingface.co/microsoft/unispeech-large-1500h-cv) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32):
40
+ Vocabulary size of the UniSpeech model. Defines the number of different tokens that can be represented by
41
+ the `inputs_ids` passed when calling [`UniSpeechModel`]. Vocabulary size of the model. Defines the
42
+ different tokens that can be represented by the *inputs_ids* passed to the forward method of
43
+ [`UniSpeechModel`].
44
+ hidden_size (`int`, *optional*, defaults to 768):
45
+ Dimensionality of the encoder layers and the pooler layer.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ intermediate_size (`int`, *optional*, defaults to 3072):
51
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
55
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ activation_dropout (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for activations inside the fully connected layer.
59
+ attention_dropout (`float`, *optional*, defaults to 0.1):
60
+ The dropout ratio for the attention probabilities.
61
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
62
+ The dropout probability for output of the feature encoder.
63
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout probability for the output of the feature encoder that's used by the quantizer.
65
+ final_dropout (`float`, *optional*, defaults to 0.1):
66
+ The dropout probability for the final projection layer of [`UniSpeechForCTC`].
67
+ layerdrop (`float`, *optional*, defaults to 0.1):
68
+ The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more
69
+ details.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
73
+ The epsilon used by the layer normalization layers.
74
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
75
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
76
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
77
+ convolutional layers.
78
+ feat_extract_activation (`str, *optional*, defaults to `"gelu"`):
79
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
80
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
81
+ conv_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
82
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
83
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
84
+ conv_stride (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
85
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
86
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
87
+ conv_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 2, 2)`):
88
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
89
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
90
+ *conv_dim*.
91
+ conv_bias (`bool`, *optional*, defaults to `False`):
92
+ Whether the 1D convolutional layers have a bias.
93
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
94
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
95
+ embeddings layer.
96
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
97
+ Number of groups of 1D convolutional positional embeddings layer.
98
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
99
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
100
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
101
+ False` corresponds to applying layer norm after the attention layer.
102
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
103
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
104
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
105
+ Recognition](https://arxiv.org/abs/1904.08779).
106
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
107
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
108
+ procecure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
109
+ reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
110
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
111
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
112
+ mask_time_length (`int`, *optional*, defaults to 10):
113
+ Length of vector span along the time axis.
114
+ mask_time_min_masks (`int`, *optional*, defaults to 2):
115
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
116
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
117
+ mask_time_min_masks''
118
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
119
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
120
+ masking procecure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
121
+ the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
122
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
123
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
124
+ True`.
125
+ mask_feature_length (`int`, *optional*, defaults to 10):
126
+ Length of vector span along the feature axis.
127
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
128
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
129
+ step, irrespectively of `mask_feature_prob`. Only relevant if
130
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
131
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
132
+ Number of entries in each quantization codebook (group).
133
+ num_codevector_groups (`int`, *optional*, defaults to 2):
134
+ Number of codevector groups for product codevector quantization.
135
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
136
+ The temperature *kappa* in the contrastive loss.
137
+ num_negatives (`int`, *optional*, defaults to 100):
138
+ Number of negative samples for the contrastive loss.
139
+ codevector_dim (`int`, *optional*, defaults to 256):
140
+ Dimensionality of the quantized feature vectors.
141
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
142
+ Dimensionality of the final projection of both the quantized and the transformer features.
143
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
144
+ The weight of the codebook diversity loss component.
145
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
146
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
147
+ instance of [`UniSpeechForCTC`].
148
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
149
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
150
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
151
+ of [`UniSpeechForCTC`].
152
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
153
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
154
+ instance of [`UniSpeechForSequenceClassification`].
155
+ classifier_proj_size (`int`, *optional*, defaults to 256):
156
+ Dimensionality of the projection before token mean-pooling for classification.
157
+ num_ctc_classes (`int`, *optional*, defaults to 80):
158
+ Specifies the number of classes (phoneme tokens and blank token) for phoneme-level CTC loss. Only relevant
159
+ when using an instance of [`UniSpeechForPreTraining`].
160
+ pad_token_id (`int`, *optional*, defaults to 0):
161
+ The id of the padding token.
162
+ bos_token_id (`int`, *optional*, defaults to 1):
163
+ The id of the "beginning-of-sequence" token.
164
+ eos_token_id (`int`, *optional*, defaults to 2):
165
+ The id of the "end-of-sequence" token.
166
+ replace_prob (`float`, *optional*, defaults to 0.5):
167
+ Propability that transformer feature is replaced by quantized feature for pretraining.
168
+
169
+ Example:
170
+
171
+ ```python
172
+ >>> from transformers import UniSpeechConfig, UniSpeechModel
173
+
174
+ >>> # Initializing a UniSpeech facebook/unispeech-base-960h style configuration
175
+ >>> configuration = UniSpeechConfig()
176
+
177
+ >>> # Initializing a model (with random weights) from the facebook/unispeech-base-960h style configuration
178
+ >>> model = UniSpeechModel(configuration)
179
+
180
+ >>> # Accessing the model configuration
181
+ >>> configuration = model.config
182
+ ```"""
183
+
184
+ model_type = "unispeech"
185
+
186
+ def __init__(
187
+ self,
188
+ vocab_size=32,
189
+ hidden_size=768,
190
+ num_hidden_layers=12,
191
+ num_attention_heads=12,
192
+ intermediate_size=3072,
193
+ hidden_act="gelu",
194
+ hidden_dropout=0.1,
195
+ activation_dropout=0.1,
196
+ attention_dropout=0.1,
197
+ feat_proj_dropout=0.0,
198
+ feat_quantizer_dropout=0.0,
199
+ final_dropout=0.1,
200
+ layerdrop=0.1,
201
+ initializer_range=0.02,
202
+ layer_norm_eps=1e-5,
203
+ feat_extract_norm="group",
204
+ feat_extract_activation="gelu",
205
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
206
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
207
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
208
+ conv_bias=False,
209
+ num_conv_pos_embeddings=128,
210
+ num_conv_pos_embedding_groups=16,
211
+ do_stable_layer_norm=False,
212
+ apply_spec_augment=True,
213
+ mask_time_prob=0.05,
214
+ mask_time_length=10,
215
+ mask_time_min_masks=2,
216
+ mask_feature_prob=0.0,
217
+ mask_feature_length=10,
218
+ mask_feature_min_masks=0,
219
+ num_codevectors_per_group=320,
220
+ num_codevector_groups=2,
221
+ contrastive_logits_temperature=0.1,
222
+ num_negatives=100,
223
+ codevector_dim=256,
224
+ proj_codevector_dim=256,
225
+ diversity_loss_weight=0.1,
226
+ ctc_loss_reduction="mean",
227
+ ctc_zero_infinity=False,
228
+ use_weighted_layer_sum=False,
229
+ classifier_proj_size=256,
230
+ num_ctc_classes=80,
231
+ pad_token_id=0,
232
+ bos_token_id=1,
233
+ eos_token_id=2,
234
+ replace_prob=0.5,
235
+ **kwargs,
236
+ ):
237
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
238
+ self.hidden_size = hidden_size
239
+ self.feat_extract_norm = feat_extract_norm
240
+ self.feat_extract_activation = feat_extract_activation
241
+ self.conv_dim = list(conv_dim)
242
+ self.conv_stride = list(conv_stride)
243
+ self.conv_kernel = list(conv_kernel)
244
+ self.conv_bias = conv_bias
245
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
246
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
247
+ self.num_feat_extract_layers = len(self.conv_dim)
248
+ self.num_hidden_layers = num_hidden_layers
249
+ self.intermediate_size = intermediate_size
250
+ self.hidden_act = hidden_act
251
+ self.num_attention_heads = num_attention_heads
252
+ self.hidden_dropout = hidden_dropout
253
+ self.attention_dropout = attention_dropout
254
+ self.activation_dropout = activation_dropout
255
+ self.feat_proj_dropout = feat_proj_dropout
256
+ self.final_dropout = final_dropout
257
+ self.layerdrop = layerdrop
258
+ self.layer_norm_eps = layer_norm_eps
259
+ self.initializer_range = initializer_range
260
+ self.num_ctc_classes = num_ctc_classes
261
+ self.vocab_size = vocab_size
262
+ self.do_stable_layer_norm = do_stable_layer_norm
263
+ self.use_weighted_layer_sum = use_weighted_layer_sum
264
+ self.classifier_proj_size = classifier_proj_size
265
+
266
+ if (
267
+ (len(self.conv_stride) != self.num_feat_extract_layers)
268
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
269
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
270
+ ):
271
+ raise ValueError(
272
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
273
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
274
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
275
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
276
+ )
277
+
278
+ # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
279
+ self.apply_spec_augment = apply_spec_augment
280
+ self.mask_time_prob = mask_time_prob
281
+ self.mask_time_length = mask_time_length
282
+ self.mask_time_min_masks = mask_time_min_masks
283
+ self.mask_feature_prob = mask_feature_prob
284
+ self.mask_feature_length = mask_feature_length
285
+ self.mask_feature_min_masks = mask_feature_min_masks
286
+
287
+ # parameters for pretraining with codevector quantized representations
288
+ self.num_codevectors_per_group = num_codevectors_per_group
289
+ self.num_codevector_groups = num_codevector_groups
290
+ self.contrastive_logits_temperature = contrastive_logits_temperature
291
+ self.feat_quantizer_dropout = feat_quantizer_dropout
292
+ self.num_negatives = num_negatives
293
+ self.codevector_dim = codevector_dim
294
+ self.proj_codevector_dim = proj_codevector_dim
295
+ self.diversity_loss_weight = diversity_loss_weight
296
+
297
+ # ctc loss
298
+ self.ctc_loss_reduction = ctc_loss_reduction
299
+ self.ctc_zero_infinity = ctc_zero_infinity
300
+
301
+ # pretraining loss
302
+ self.replace_prob = replace_prob
303
+
304
+ @property
305
+ def inputs_to_logits_ratio(self):
306
+ return functools.reduce(operator.mul, self.conv_stride, 1)
307
+
308
+
309
+ __all__ = ["UniSpeechConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert UniSpeech checkpoint."""
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+
21
+ import fairseq
22
+ import torch
23
+ from fairseq.data import Dictionary
24
+
25
+ from transformers import (
26
+ UniSpeechConfig,
27
+ UniSpeechForCTC,
28
+ UniSpeechForPreTraining,
29
+ Wav2Vec2FeatureExtractor,
30
+ Wav2Vec2PhonemeCTCTokenizer,
31
+ Wav2Vec2Processor,
32
+ logging,
33
+ )
34
+
35
+
36
+ logging.set_verbosity_info()
37
+ logger = logging.get_logger(__name__)
38
+
39
+ MAPPING = {
40
+ "post_extract_proj": "feature_projection.projection",
41
+ "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
42
+ "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
43
+ "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
44
+ "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
45
+ "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
46
+ "self_attn_layer_norm": "encoder.layers.*.layer_norm",
47
+ "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
48
+ "fc2": "encoder.layers.*.feed_forward.output_dense",
49
+ "final_layer_norm": "encoder.layers.*.final_layer_norm",
50
+ "encoder.layer_norm": "encoder.layer_norm",
51
+ "w2v_model.layer_norm": "feature_projection.layer_norm",
52
+ "quantizer.weight_proj": "quantizer.weight_proj",
53
+ "quantizer.vars": "quantizer.codevectors",
54
+ "project_q": "project_q",
55
+ "final_proj": "project_hid",
56
+ "w2v_encoder.proj": "ctc_proj",
57
+ "mask_emb": "masked_spec_embed",
58
+ }
59
+ TOP_LEVEL_KEYS = [
60
+ "ctc_proj",
61
+ "quantizer.weight_proj",
62
+ "quantizer.codevectors",
63
+ "project_q",
64
+ "project_hid",
65
+ ]
66
+
67
+
68
+ def set_recursively(hf_pointer, key, value, full_name, weight_type, is_finetuned):
69
+ for attribute in key.split("."):
70
+ if is_finetuned:
71
+ if attribute in ["quantizer", "project_q", "project_hid"]:
72
+ # those layers are only relevant for pretraining and should be dropped
73
+ return
74
+
75
+ if attribute == "ctc_proj":
76
+ # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
77
+ attribute = "lm_head"
78
+
79
+ hf_pointer = getattr(hf_pointer, attribute)
80
+
81
+ if weight_type is not None:
82
+ hf_shape = getattr(hf_pointer, weight_type).shape
83
+ else:
84
+ hf_shape = hf_pointer.shape
85
+
86
+ assert hf_shape == value.shape, (
87
+ f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
88
+ f" {value.shape} for {full_name}"
89
+ )
90
+
91
+ if weight_type == "weight":
92
+ hf_pointer.weight.data = value
93
+ elif weight_type == "weight_g":
94
+ hf_pointer.weight_g.data = value
95
+ elif weight_type == "weight_v":
96
+ hf_pointer.weight_v.data = value
97
+ elif weight_type == "bias":
98
+ hf_pointer.bias.data = value
99
+ else:
100
+ hf_pointer.data = value
101
+
102
+ logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.")
103
+
104
+
105
+ def recursively_load_weights(fairseq_model, hf_model, is_finetuned):
106
+ unused_weights = []
107
+ fairseq_dict = fairseq_model.state_dict()
108
+
109
+ feature_extractor = hf_model.unispeech.feature_extractor
110
+
111
+ for name, value in fairseq_dict.items():
112
+ is_used = False
113
+ if "conv_layers" in name:
114
+ load_conv_layer(
115
+ name,
116
+ value,
117
+ feature_extractor,
118
+ unused_weights,
119
+ hf_model.config.feat_extract_norm == "group",
120
+ )
121
+ is_used = True
122
+ else:
123
+ for key, mapped_key in MAPPING.items():
124
+ mapped_key = "unispeech." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
125
+ if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
126
+ is_used = True
127
+ if "*" in mapped_key:
128
+ layer_index = name.split(key)[0].split(".")[-2]
129
+ mapped_key = mapped_key.replace("*", layer_index)
130
+ if "weight_g" in name:
131
+ weight_type = "weight_g"
132
+ elif "weight_v" in name:
133
+ weight_type = "weight_v"
134
+ elif "bias" in name:
135
+ weight_type = "bias"
136
+ elif "weight" in name:
137
+ # TODO: don't match quantizer.weight_proj
138
+ weight_type = "weight"
139
+ else:
140
+ weight_type = None
141
+ set_recursively(hf_model, mapped_key, value, name, weight_type, is_finetuned)
142
+ continue
143
+ if not is_used:
144
+ unused_weights.append(name)
145
+
146
+ logger.warning(f"Unused weights: {unused_weights}")
147
+
148
+
149
+ def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm):
150
+ name = full_name.split("conv_layers.")[-1]
151
+ items = name.split(".")
152
+ layer_id = int(items[0])
153
+ type_id = int(items[1])
154
+
155
+ if type_id == 0:
156
+ if "bias" in name:
157
+ assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
158
+ f"{full_name} has size {value.shape}, but"
159
+ f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
160
+ )
161
+ feature_extractor.conv_layers[layer_id].conv.bias.data = value
162
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
163
+ elif "weight" in name:
164
+ assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
165
+ f"{full_name} has size {value.shape}, but"
166
+ f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
167
+ )
168
+ feature_extractor.conv_layers[layer_id].conv.weight.data = value
169
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
170
+ elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
171
+ if "bias" in name:
172
+ assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
173
+ f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
174
+ " found."
175
+ )
176
+ feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value
177
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
178
+ elif "weight" in name:
179
+ assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
180
+ f"{full_name} has size {value.shape}, but"
181
+ f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
182
+ )
183
+ feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value
184
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
185
+ else:
186
+ unused_weights.append(full_name)
187
+
188
+
189
+ @torch.no_grad()
190
+ def convert_unispeech_checkpoint(
191
+ checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True
192
+ ):
193
+ """
194
+ Copy/paste/tweak model's weights to transformers design.
195
+ """
196
+ if config_path is not None:
197
+ config = UniSpeechConfig.from_pretrained(config_path)
198
+ else:
199
+ config = UniSpeechConfig()
200
+
201
+ if is_finetuned:
202
+ if dict_path:
203
+ target_dict = Dictionary.load_from_json(dict_path)
204
+
205
+ # important change bos & pad token id since CTC symbol is <pad> and
206
+ # not <s> as in fairseq
207
+ config.bos_token_id = target_dict.pad_index
208
+ config.pad_token_id = target_dict.bos_index
209
+ config.eos_token_id = target_dict.eos_index
210
+ config.vocab_size = len(target_dict.symbols)
211
+ vocab_path = os.path.join(pytorch_dump_folder_path, "vocab.json")
212
+ if not os.path.isdir(pytorch_dump_folder_path):
213
+ logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(pytorch_dump_folder_path))
214
+ return
215
+ os.makedirs(pytorch_dump_folder_path, exist_ok=True)
216
+ vocab_dict = target_dict.indices
217
+
218
+ # fairseq has the <pad> and <s> switched
219
+ vocab_dict["<pad>"] = 42
220
+ vocab_dict["<s>"] = 43
221
+ with open(vocab_path, "w", encoding="utf-8") as vocab_handle:
222
+ json.dump(vocab_dict, vocab_handle)
223
+ tokenizer = Wav2Vec2PhonemeCTCTokenizer(
224
+ vocab_path,
225
+ unk_token=target_dict.unk_word,
226
+ pad_token=target_dict.pad_word,
227
+ bos_token=target_dict.bos_word,
228
+ eos_token=target_dict.eos_word,
229
+ word_delimiter_token="|",
230
+ do_lower_case=False,
231
+ )
232
+ return_attention_mask = True if config.feat_extract_norm == "layer" else False
233
+ feature_extractor = Wav2Vec2FeatureExtractor(
234
+ feature_size=1,
235
+ sampling_rate=16000,
236
+ padding_value=0,
237
+ do_normalize=True,
238
+ return_attention_mask=return_attention_mask,
239
+ )
240
+ processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
241
+ processor.save_pretrained(pytorch_dump_folder_path)
242
+
243
+ hf_unispeech = UniSpeechForCTC(config)
244
+ else:
245
+ hf_unispeech = UniSpeechForPreTraining(config)
246
+
247
+ if is_finetuned:
248
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
249
+ [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/")[:-1]), "w2v_path": checkpoint_path}
250
+ )
251
+ else:
252
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path])
253
+
254
+ model = model[0].eval()
255
+
256
+ recursively_load_weights(model, hf_unispeech, is_finetuned)
257
+
258
+ hf_unispeech.save_pretrained(pytorch_dump_folder_path)
259
+
260
+
261
+ if __name__ == "__main__":
262
+ parser = argparse.ArgumentParser()
263
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
264
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
265
+ parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
266
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
267
+ parser.add_argument(
268
+ "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
269
+ )
270
+ args = parser.parse_args()
271
+ convert_unispeech_checkpoint(
272
+ args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
273
+ )
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech/modeling_unispeech.py ADDED
@@ -0,0 +1,1908 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch UniSpeech model."""
16
+
17
+ import math
18
+ import warnings
19
+ from dataclasses import dataclass
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import CrossEntropyLoss
27
+
28
+ from ...activations import ACT2FN
29
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
30
+ from ...integrations.fsdp import is_fsdp_managed_module
31
+ from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput, Wav2Vec2BaseModelOutput
32
+ from ...modeling_utils import PreTrainedModel
33
+ from ...utils import (
34
+ ModelOutput,
35
+ add_code_sample_docstrings,
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_flash_attn_2_available,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from .configuration_unispeech import UniSpeechConfig
44
+
45
+
46
+ if is_flash_attn_2_available():
47
+ from ...modeling_flash_attention_utils import _flash_attention_forward
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ _HIDDEN_STATES_START_POSITION = 2
54
+
55
+ # General docstring
56
+ _CONFIG_FOR_DOC = "UniSpeechConfig"
57
+
58
+ # Base docstring
59
+ _CHECKPOINT_FOR_DOC = "patrickvonplaten/unispeech-large-1500h-cv-timit"
60
+ _EXPECTED_OUTPUT_SHAPE = [1, 292, 1024]
61
+
62
+ # CTC docstring
63
+ _CTC_EXPECTED_OUTPUT = "'mister quilter is the apposl of the midle classes and weare glad to welcom his gosepl'"
64
+ _CTC_EXPECTED_LOSS = 17.17
65
+
66
+
67
+ @dataclass
68
+ class UniSpeechForPreTrainingOutput(ModelOutput):
69
+ """
70
+ Output type of [`UniSpeechForPreTrainingOutput`], with potential hidden states and attentions.
71
+
72
+ Args:
73
+ loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
74
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
75
+ paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
76
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
77
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
78
+ projected quantized states.
79
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
80
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
81
+ target vectors for contrastive loss.
82
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
83
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
84
+ shape `(batch_size, sequence_length, hidden_size)`.
85
+
86
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
87
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
88
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
89
+ sequence_length)`.
90
+
91
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
92
+ heads.
93
+ """
94
+
95
+ loss: Optional[torch.FloatTensor] = None
96
+ projected_states: torch.FloatTensor = None
97
+ projected_quantized_states: torch.FloatTensor = None
98
+ codevector_perplexity: torch.FloatTensor = None
99
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
100
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
101
+
102
+
103
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2._compute_mask_indices
104
+ def _compute_mask_indices(
105
+ shape: Tuple[int, int],
106
+ mask_prob: float,
107
+ mask_length: int,
108
+ attention_mask: Optional[torch.LongTensor] = None,
109
+ min_masks: int = 0,
110
+ ) -> np.ndarray:
111
+ """
112
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
113
+ ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on
114
+ CPU as part of the preprocessing during training.
115
+
116
+ Args:
117
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
118
+ the first element is the batch size and the second element is the length of the axis to span.
119
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
120
+ independently generated mask spans of length `mask_length` is computed by
121
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
122
+ actual percentage will be smaller.
123
+ mask_length: size of the mask
124
+ min_masks: minimum number of masked spans
125
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
126
+ each batch dimension.
127
+ """
128
+ batch_size, sequence_length = shape
129
+
130
+ if mask_length < 1:
131
+ raise ValueError("`mask_length` has to be bigger than 0.")
132
+
133
+ if mask_length > sequence_length:
134
+ raise ValueError(
135
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
136
+ f" and `sequence_length`: {sequence_length}`"
137
+ )
138
+
139
+ # epsilon is used for probabilistic rounding
140
+ epsilon = np.random.rand(1).item()
141
+
142
+ def compute_num_masked_span(input_length):
143
+ """Given input length, compute how many spans should be masked"""
144
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
145
+ num_masked_span = max(num_masked_span, min_masks)
146
+
147
+ # make sure num masked span <= sequence_length
148
+ if num_masked_span * mask_length > sequence_length:
149
+ num_masked_span = sequence_length // mask_length
150
+
151
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
152
+ if input_length - (mask_length - 1) < num_masked_span:
153
+ num_masked_span = max(input_length - (mask_length - 1), 0)
154
+
155
+ return num_masked_span
156
+
157
+ # compute number of masked spans in batch
158
+ input_lengths = (
159
+ attention_mask.sum(-1).detach().tolist()
160
+ if attention_mask is not None
161
+ else [sequence_length for _ in range(batch_size)]
162
+ )
163
+
164
+ # SpecAugment mask to fill
165
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
166
+ spec_aug_mask_idxs = []
167
+
168
+ max_num_masked_span = compute_num_masked_span(sequence_length)
169
+
170
+ if max_num_masked_span == 0:
171
+ return spec_aug_mask
172
+
173
+ for input_length in input_lengths:
174
+ # compute num of masked spans for this input
175
+ num_masked_span = compute_num_masked_span(input_length)
176
+
177
+ # get random indices to mask
178
+ spec_aug_mask_idx = np.random.choice(
179
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
180
+ )
181
+
182
+ # pick first sampled index that will serve as a dummy index to pad vector
183
+ # to ensure same dimension for all batches due to probabilistic rounding
184
+ # Picking first sample just pads those vectors twice.
185
+ if len(spec_aug_mask_idx) == 0:
186
+ # this case can only happen if `input_length` is strictly smaller then
187
+ # `sequence_length` in which case the last token has to be a padding
188
+ # token which we can use as a dummy mask id
189
+ dummy_mask_idx = sequence_length - 1
190
+ else:
191
+ dummy_mask_idx = spec_aug_mask_idx[0]
192
+
193
+ spec_aug_mask_idx = np.concatenate(
194
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
195
+ )
196
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
197
+
198
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
199
+
200
+ # expand masked indices to masked spans
201
+ spec_aug_mask_idxs = np.broadcast_to(
202
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
203
+ )
204
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
205
+
206
+ # add offset to the starting indexes so that indexes now create a span
207
+ offsets = np.arange(mask_length)[None, None, :]
208
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
209
+ batch_size, max_num_masked_span * mask_length
210
+ )
211
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
212
+
213
+ # ensure that we cannot have indices larger than sequence_length
214
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
215
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
216
+
217
+ # scatter indices to mask
218
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
219
+
220
+ return spec_aug_mask
221
+
222
+
223
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2NoLayerNormConvLayer with Wav2Vec2->UniSpeech
224
+ class UniSpeechNoLayerNormConvLayer(nn.Module):
225
+ def __init__(self, config, layer_id=0):
226
+ super().__init__()
227
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
228
+ self.out_conv_dim = config.conv_dim[layer_id]
229
+
230
+ self.conv = nn.Conv1d(
231
+ self.in_conv_dim,
232
+ self.out_conv_dim,
233
+ kernel_size=config.conv_kernel[layer_id],
234
+ stride=config.conv_stride[layer_id],
235
+ bias=config.conv_bias,
236
+ )
237
+ self.activation = ACT2FN[config.feat_extract_activation]
238
+
239
+ def forward(self, hidden_states):
240
+ hidden_states = self.conv(hidden_states)
241
+ hidden_states = self.activation(hidden_states)
242
+ return hidden_states
243
+
244
+
245
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2LayerNormConvLayer with Wav2Vec2->UniSpeech
246
+ class UniSpeechLayerNormConvLayer(nn.Module):
247
+ def __init__(self, config, layer_id=0):
248
+ super().__init__()
249
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
250
+ self.out_conv_dim = config.conv_dim[layer_id]
251
+
252
+ self.conv = nn.Conv1d(
253
+ self.in_conv_dim,
254
+ self.out_conv_dim,
255
+ kernel_size=config.conv_kernel[layer_id],
256
+ stride=config.conv_stride[layer_id],
257
+ bias=config.conv_bias,
258
+ )
259
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
260
+ self.activation = ACT2FN[config.feat_extract_activation]
261
+
262
+ def forward(self, hidden_states):
263
+ hidden_states = self.conv(hidden_states)
264
+
265
+ hidden_states = hidden_states.transpose(-2, -1)
266
+ hidden_states = self.layer_norm(hidden_states)
267
+ hidden_states = hidden_states.transpose(-2, -1)
268
+
269
+ hidden_states = self.activation(hidden_states)
270
+ return hidden_states
271
+
272
+
273
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2GroupNormConvLayer with Wav2Vec2->UniSpeech
274
+ class UniSpeechGroupNormConvLayer(nn.Module):
275
+ def __init__(self, config, layer_id=0):
276
+ super().__init__()
277
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
278
+ self.out_conv_dim = config.conv_dim[layer_id]
279
+
280
+ self.conv = nn.Conv1d(
281
+ self.in_conv_dim,
282
+ self.out_conv_dim,
283
+ kernel_size=config.conv_kernel[layer_id],
284
+ stride=config.conv_stride[layer_id],
285
+ bias=config.conv_bias,
286
+ )
287
+ self.activation = ACT2FN[config.feat_extract_activation]
288
+
289
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
290
+
291
+ def forward(self, hidden_states):
292
+ hidden_states = self.conv(hidden_states)
293
+ hidden_states = self.layer_norm(hidden_states)
294
+ hidden_states = self.activation(hidden_states)
295
+ return hidden_states
296
+
297
+
298
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2PositionalConvEmbedding with Wav2Vec2->UniSpeech
299
+ class UniSpeechPositionalConvEmbedding(nn.Module):
300
+ def __init__(self, config):
301
+ super().__init__()
302
+ self.conv = nn.Conv1d(
303
+ config.hidden_size,
304
+ config.hidden_size,
305
+ kernel_size=config.num_conv_pos_embeddings,
306
+ padding=config.num_conv_pos_embeddings // 2,
307
+ groups=config.num_conv_pos_embedding_groups,
308
+ )
309
+
310
+ weight_norm = nn.utils.weight_norm
311
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
312
+ weight_norm = nn.utils.parametrizations.weight_norm
313
+
314
+ if is_deepspeed_zero3_enabled():
315
+ import deepspeed
316
+
317
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
318
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
319
+ if hasattr(self.conv, "parametrizations"):
320
+ weight_g = self.conv.parametrizations.weight.original0
321
+ weight_v = self.conv.parametrizations.weight.original1
322
+ else:
323
+ weight_g = self.conv.weight_g
324
+ weight_v = self.conv.weight_v
325
+ deepspeed.zero.register_external_parameter(self, weight_v)
326
+ deepspeed.zero.register_external_parameter(self, weight_g)
327
+ else:
328
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
329
+
330
+ self.padding = UniSpeechSamePadLayer(config.num_conv_pos_embeddings)
331
+ self.activation = ACT2FN[config.feat_extract_activation]
332
+
333
+ def forward(self, hidden_states):
334
+ hidden_states = hidden_states.transpose(1, 2)
335
+
336
+ hidden_states = self.conv(hidden_states)
337
+ hidden_states = self.padding(hidden_states)
338
+ hidden_states = self.activation(hidden_states)
339
+
340
+ hidden_states = hidden_states.transpose(1, 2)
341
+ return hidden_states
342
+
343
+
344
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2SamePadLayer with Wav2Vec2->UniSpeech
345
+ class UniSpeechSamePadLayer(nn.Module):
346
+ def __init__(self, num_conv_pos_embeddings):
347
+ super().__init__()
348
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
349
+
350
+ def forward(self, hidden_states):
351
+ if self.num_pad_remove > 0:
352
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
353
+ return hidden_states
354
+
355
+
356
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureEncoder with Wav2Vec2->UniSpeech
357
+ class UniSpeechFeatureEncoder(nn.Module):
358
+ """Construct the features from raw audio waveform"""
359
+
360
+ def __init__(self, config):
361
+ super().__init__()
362
+
363
+ if config.feat_extract_norm == "group":
364
+ conv_layers = [UniSpeechGroupNormConvLayer(config, layer_id=0)] + [
365
+ UniSpeechNoLayerNormConvLayer(config, layer_id=i + 1)
366
+ for i in range(config.num_feat_extract_layers - 1)
367
+ ]
368
+ elif config.feat_extract_norm == "layer":
369
+ conv_layers = [
370
+ UniSpeechLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
371
+ ]
372
+ else:
373
+ raise ValueError(
374
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
375
+ )
376
+ self.conv_layers = nn.ModuleList(conv_layers)
377
+ self.gradient_checkpointing = False
378
+ self._requires_grad = True
379
+
380
+ def _freeze_parameters(self):
381
+ for param in self.parameters():
382
+ param.requires_grad = False
383
+ self._requires_grad = False
384
+
385
+ def forward(self, input_values):
386
+ hidden_states = input_values[:, None]
387
+
388
+ # make sure hidden_states require grad for gradient_checkpointing
389
+ if self._requires_grad and self.training:
390
+ hidden_states.requires_grad = True
391
+
392
+ for conv_layer in self.conv_layers:
393
+ if self._requires_grad and self.gradient_checkpointing and self.training:
394
+ hidden_states = self._gradient_checkpointing_func(
395
+ conv_layer.__call__,
396
+ hidden_states,
397
+ )
398
+ else:
399
+ hidden_states = conv_layer(hidden_states)
400
+
401
+ return hidden_states
402
+
403
+
404
+ class UniSpeechFeatureExtractor(UniSpeechFeatureEncoder):
405
+ def __init__(self, config):
406
+ super().__init__(config)
407
+ warnings.warn(
408
+ f"The class `{self.__class__.__name__}` has been depreciated "
409
+ "and will be removed in Transformers v5. "
410
+ f"Use `{self.__class__.__bases__[0].__name__}` instead.",
411
+ FutureWarning,
412
+ )
413
+
414
+
415
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureProjection with Wav2Vec2->UniSpeech
416
+ class UniSpeechFeatureProjection(nn.Module):
417
+ def __init__(self, config):
418
+ super().__init__()
419
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
420
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
421
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
422
+
423
+ def forward(self, hidden_states):
424
+ # non-projected hidden states are needed for quantization
425
+ norm_hidden_states = self.layer_norm(hidden_states)
426
+ hidden_states = self.projection(norm_hidden_states)
427
+ hidden_states = self.dropout(hidden_states)
428
+ return hidden_states, norm_hidden_states
429
+
430
+
431
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->UniSpeech
432
+ class UniSpeechAttention(nn.Module):
433
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
434
+
435
+ def __init__(
436
+ self,
437
+ embed_dim: int,
438
+ num_heads: int,
439
+ dropout: float = 0.0,
440
+ is_decoder: bool = False,
441
+ bias: bool = True,
442
+ is_causal: bool = False,
443
+ config: Optional[UniSpeechConfig] = None,
444
+ ):
445
+ super().__init__()
446
+ self.embed_dim = embed_dim
447
+ self.num_heads = num_heads
448
+ self.dropout = dropout
449
+ self.head_dim = embed_dim // num_heads
450
+ self.config = config
451
+
452
+ if (self.head_dim * num_heads) != self.embed_dim:
453
+ raise ValueError(
454
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
455
+ f" and `num_heads`: {num_heads})."
456
+ )
457
+ self.scaling = self.head_dim**-0.5
458
+ self.is_decoder = is_decoder
459
+ self.is_causal = is_causal
460
+
461
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
462
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
463
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
464
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
465
+
466
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
467
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
468
+
469
+ def forward(
470
+ self,
471
+ hidden_states: torch.Tensor,
472
+ key_value_states: Optional[torch.Tensor] = None,
473
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
474
+ attention_mask: Optional[torch.Tensor] = None,
475
+ layer_head_mask: Optional[torch.Tensor] = None,
476
+ output_attentions: bool = False,
477
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
478
+ """Input shape: Batch x Time x Channel"""
479
+
480
+ # if key_value_states are provided this layer is used as a cross-attention layer
481
+ # for the decoder
482
+ is_cross_attention = key_value_states is not None
483
+
484
+ bsz, tgt_len, _ = hidden_states.size()
485
+
486
+ # get query proj
487
+ query_states = self.q_proj(hidden_states) * self.scaling
488
+ # get key, value proj
489
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
490
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
491
+ # the provided `key_value_states` to support prefix tuning
492
+ if (
493
+ is_cross_attention
494
+ and past_key_value is not None
495
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
496
+ ):
497
+ # reuse k,v, cross_attentions
498
+ key_states = past_key_value[0]
499
+ value_states = past_key_value[1]
500
+ elif is_cross_attention:
501
+ # cross_attentions
502
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
503
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
504
+ elif past_key_value is not None:
505
+ # reuse k, v, self_attention
506
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
507
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
508
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
509
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
510
+ else:
511
+ # self_attention
512
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
513
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
514
+
515
+ if self.is_decoder:
516
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
517
+ # Further calls to cross_attention layer can then reuse all cross-attention
518
+ # key/value_states (first "if" case)
519
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
520
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
521
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
522
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
523
+ past_key_value = (key_states, value_states)
524
+
525
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
526
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
527
+ key_states = key_states.reshape(*proj_shape)
528
+ value_states = value_states.reshape(*proj_shape)
529
+
530
+ src_len = key_states.size(1)
531
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
532
+
533
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
534
+ raise ValueError(
535
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
536
+ f" {attn_weights.size()}"
537
+ )
538
+
539
+ if attention_mask is not None:
540
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
541
+ raise ValueError(
542
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
543
+ )
544
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
545
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
546
+
547
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
548
+
549
+ if layer_head_mask is not None:
550
+ if layer_head_mask.size() != (self.num_heads,):
551
+ raise ValueError(
552
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
553
+ f" {layer_head_mask.size()}"
554
+ )
555
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
556
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
557
+
558
+ if output_attentions:
559
+ # this operation is a bit awkward, but it's required to
560
+ # make sure that attn_weights keeps its gradient.
561
+ # In order to do so, attn_weights have to be reshaped
562
+ # twice and have to be reused in the following
563
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
564
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
565
+ else:
566
+ attn_weights_reshaped = None
567
+
568
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
569
+
570
+ attn_output = torch.bmm(attn_probs, value_states)
571
+
572
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
573
+ raise ValueError(
574
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
575
+ f" {attn_output.size()}"
576
+ )
577
+
578
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
579
+ attn_output = attn_output.transpose(1, 2)
580
+
581
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
582
+ # partitioned across GPUs when using tensor-parallelism.
583
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
584
+
585
+ attn_output = self.out_proj(attn_output)
586
+
587
+ return attn_output, attn_weights_reshaped, past_key_value
588
+
589
+
590
+ # Copied from transformers.models.bart.modeling_bart.BartFlashAttention2 with Bart->UniSpeech
591
+ class UniSpeechFlashAttention2(UniSpeechAttention):
592
+ """
593
+ UniSpeech flash attention module. This module inherits from `UniSpeechAttention` as the weights of the module stays
594
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
595
+ flash attention and deal with padding tokens in case the input contains any of them.
596
+ """
597
+
598
+ def __init__(self, *args, **kwargs):
599
+ super().__init__(*args, **kwargs)
600
+
601
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
602
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
603
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
604
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
605
+
606
+ def _reshape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
607
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
608
+
609
+ def forward(
610
+ self,
611
+ hidden_states: torch.Tensor,
612
+ key_value_states: Optional[torch.Tensor] = None,
613
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
614
+ attention_mask: Optional[torch.Tensor] = None,
615
+ layer_head_mask: Optional[torch.Tensor] = None,
616
+ output_attentions: bool = False,
617
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
618
+ # UniSpeechFlashAttention2 attention does not support output_attentions
619
+ if output_attentions:
620
+ raise ValueError("UniSpeechFlashAttention2 attention does not support output_attentions")
621
+
622
+ # if key_value_states are provided this layer is used as a cross-attention layer
623
+ # for the decoder
624
+ is_cross_attention = key_value_states is not None
625
+
626
+ bsz, q_len, _ = hidden_states.size()
627
+
628
+ # get query proj
629
+ query_states = self._reshape(self.q_proj(hidden_states), -1, bsz)
630
+ # get key, value proj
631
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
632
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
633
+ # the provided `key_value_states` to support prefix tuning
634
+ if (
635
+ is_cross_attention
636
+ and past_key_value is not None
637
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
638
+ ):
639
+ # reuse k,v, cross_attentions
640
+ key_states = past_key_value[0].transpose(1, 2)
641
+ value_states = past_key_value[1].transpose(1, 2)
642
+ elif is_cross_attention:
643
+ # cross_attentions
644
+ key_states = self._reshape(self.k_proj(key_value_states), -1, bsz)
645
+ value_states = self._reshape(self.v_proj(key_value_states), -1, bsz)
646
+ elif past_key_value is not None:
647
+ # reuse k, v, self_attention
648
+ key_states = self._reshape(self.k_proj(hidden_states), -1, bsz)
649
+ value_states = self._reshape(self.v_proj(hidden_states), -1, bsz)
650
+ key_states = torch.cat([past_key_value[0].transpose(1, 2), key_states], dim=1)
651
+ value_states = torch.cat([past_key_value[1].transpose(1, 2), value_states], dim=1)
652
+ else:
653
+ # self_attention
654
+ key_states = self._reshape(self.k_proj(hidden_states), -1, bsz)
655
+ value_states = self._reshape(self.v_proj(hidden_states), -1, bsz)
656
+
657
+ if self.is_decoder:
658
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
659
+ # Further calls to cross_attention layer can then reuse all cross-attention
660
+ # key/value_states (first "if" case)
661
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
662
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
663
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
664
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
665
+ past_key_value = (key_states.transpose(1, 2), value_states.transpose(1, 2))
666
+
667
+ kv_seq_len = key_states.shape[-2]
668
+ if past_key_value is not None:
669
+ kv_seq_len += past_key_value[0].shape[-2]
670
+
671
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
672
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
673
+ # cast them back in the correct dtype just to be sure everything works as expected.
674
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
675
+ # in fp32. (LlamaRMSNorm handles it correctly)
676
+
677
+ input_dtype = query_states.dtype
678
+ if input_dtype == torch.float32:
679
+ if torch.is_autocast_enabled():
680
+ target_dtype = torch.get_autocast_gpu_dtype()
681
+ # Handle the case where the model is quantized
682
+ elif hasattr(self.config, "_pre_quantization_dtype"):
683
+ target_dtype = self.config._pre_quantization_dtype
684
+ else:
685
+ target_dtype = self.q_proj.weight.dtype
686
+
687
+ logger.warning_once(
688
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
689
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
690
+ f" {target_dtype}."
691
+ )
692
+
693
+ query_states = query_states.to(target_dtype)
694
+ key_states = key_states.to(target_dtype)
695
+ value_states = value_states.to(target_dtype)
696
+
697
+ attn_output = _flash_attention_forward(
698
+ query_states,
699
+ key_states,
700
+ value_states,
701
+ attention_mask,
702
+ q_len,
703
+ dropout=self.dropout if self.training else 0.0,
704
+ is_causal=self.is_causal,
705
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
706
+ )
707
+
708
+ attn_output = attn_output.reshape(bsz, q_len, -1)
709
+ attn_output = self.out_proj(attn_output)
710
+
711
+ if not output_attentions:
712
+ attn_weights = None
713
+
714
+ return attn_output, attn_weights, past_key_value
715
+
716
+
717
+ class UniSpeechSdpaAttention(UniSpeechAttention):
718
+ # Copied from transformers.models.bart.modeling_bart.BartSdpaAttention.forward with Bart->UniSpeech
719
+ def forward(
720
+ self,
721
+ hidden_states: torch.Tensor,
722
+ key_value_states: Optional[torch.Tensor] = None,
723
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
724
+ attention_mask: Optional[torch.Tensor] = None,
725
+ layer_head_mask: Optional[torch.Tensor] = None,
726
+ output_attentions: bool = False,
727
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
728
+ """Input shape: Batch x Time x Channel"""
729
+ if output_attentions or layer_head_mask is not None:
730
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented.
731
+ logger.warning_once(
732
+ "UniSpeechModel is using UniSpeechSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention"
733
+ ' implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
734
+ )
735
+ return super().forward(
736
+ hidden_states,
737
+ key_value_states=key_value_states,
738
+ past_key_value=past_key_value,
739
+ attention_mask=attention_mask,
740
+ layer_head_mask=layer_head_mask,
741
+ output_attentions=output_attentions,
742
+ )
743
+
744
+ # if key_value_states are provided this layer is used as a cross-attention layer
745
+ # for the decoder
746
+ is_cross_attention = key_value_states is not None
747
+
748
+ bsz, tgt_len, _ = hidden_states.size()
749
+
750
+ # get query proj
751
+ query_states = self.q_proj(hidden_states)
752
+ # get key, value proj
753
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
754
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
755
+ # the provided `key_value_states` to support prefix tuning
756
+ if (
757
+ is_cross_attention
758
+ and past_key_value is not None
759
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
760
+ ):
761
+ # reuse k,v, cross_attentions
762
+ key_states = past_key_value[0]
763
+ value_states = past_key_value[1]
764
+ elif is_cross_attention:
765
+ # cross_attentions
766
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
767
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
768
+ elif past_key_value is not None:
769
+ # reuse k, v, self_attention
770
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
771
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
772
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
773
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
774
+ else:
775
+ # self_attention
776
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
777
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
778
+
779
+ if self.is_decoder:
780
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
781
+ # Further calls to cross_attention layer can then reuse all cross-attention
782
+ # key/value_states (first "if" case)
783
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
784
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
785
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
786
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
787
+ past_key_value = (key_states, value_states)
788
+
789
+ query_states = self._shape(query_states, tgt_len, bsz)
790
+
791
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
792
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
793
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1.
794
+ is_causal = True if self.is_causal and attention_mask is None and tgt_len > 1 else False
795
+
796
+ # NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask,
797
+ # but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577
798
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
799
+ query_states,
800
+ key_states,
801
+ value_states,
802
+ attn_mask=attention_mask,
803
+ dropout_p=self.dropout if self.training else 0.0,
804
+ is_causal=is_causal,
805
+ )
806
+
807
+ if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
808
+ raise ValueError(
809
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
810
+ f" {attn_output.size()}"
811
+ )
812
+
813
+ attn_output = attn_output.transpose(1, 2)
814
+
815
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
816
+ # partitioned across GPUs when using tensor-parallelism.
817
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
818
+
819
+ attn_output = self.out_proj(attn_output)
820
+
821
+ return attn_output, None, past_key_value
822
+
823
+
824
+ UNISPEECH_ATTENTION_CLASSES = {
825
+ "eager": UniSpeechAttention,
826
+ "sdpa": UniSpeechSdpaAttention,
827
+ "flash_attention_2": UniSpeechFlashAttention2,
828
+ }
829
+
830
+
831
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeedForward with Wav2Vec2->UniSpeech
832
+ class UniSpeechFeedForward(nn.Module):
833
+ def __init__(self, config):
834
+ super().__init__()
835
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
836
+
837
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
838
+ if isinstance(config.hidden_act, str):
839
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
840
+ else:
841
+ self.intermediate_act_fn = config.hidden_act
842
+
843
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
844
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
845
+
846
+ def forward(self, hidden_states):
847
+ hidden_states = self.intermediate_dense(hidden_states)
848
+ hidden_states = self.intermediate_act_fn(hidden_states)
849
+ hidden_states = self.intermediate_dropout(hidden_states)
850
+
851
+ hidden_states = self.output_dense(hidden_states)
852
+ hidden_states = self.output_dropout(hidden_states)
853
+ return hidden_states
854
+
855
+
856
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderLayer with Wav2Vec2->UniSpeech, WAV2VEC2->UNISPEECH
857
+ class UniSpeechEncoderLayer(nn.Module):
858
+ def __init__(self, config):
859
+ super().__init__()
860
+ self.attention = UNISPEECH_ATTENTION_CLASSES[config._attn_implementation](
861
+ embed_dim=config.hidden_size,
862
+ num_heads=config.num_attention_heads,
863
+ dropout=config.attention_dropout,
864
+ is_decoder=False,
865
+ )
866
+
867
+ self.dropout = nn.Dropout(config.hidden_dropout)
868
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
869
+ self.feed_forward = UniSpeechFeedForward(config)
870
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
871
+
872
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
873
+ attn_residual = hidden_states
874
+ hidden_states, attn_weights, _ = self.attention(
875
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
876
+ )
877
+ hidden_states = self.dropout(hidden_states)
878
+ hidden_states = attn_residual + hidden_states
879
+
880
+ hidden_states = self.layer_norm(hidden_states)
881
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
882
+ hidden_states = self.final_layer_norm(hidden_states)
883
+
884
+ outputs = (hidden_states,)
885
+
886
+ if output_attentions:
887
+ outputs += (attn_weights,)
888
+
889
+ return outputs
890
+
891
+
892
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2AttnAdapterLayer with Wav2Vec2->UniSpeech
893
+ class UniSpeechAttnAdapterLayer(nn.Module):
894
+ def __init__(self, config):
895
+ """
896
+ Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
897
+ up training throughput.
898
+ """
899
+ super().__init__()
900
+ self.input_dim = config.adapter_attn_dim
901
+ self.hidden_dim = config.hidden_size
902
+
903
+ self.norm = nn.LayerNorm(self.hidden_dim)
904
+ self.linear_1 = nn.Linear(self.hidden_dim, self.input_dim)
905
+ self.act_fn = nn.ReLU()
906
+ self.linear_2 = nn.Linear(self.input_dim, self.hidden_dim)
907
+
908
+ def forward(self, hidden_states: torch.FloatTensor):
909
+ hidden_states = self.norm(hidden_states)
910
+
911
+ hidden_states = self.linear_1(hidden_states)
912
+ hidden_states = self.act_fn(hidden_states)
913
+ hidden_states = self.linear_2(hidden_states)
914
+
915
+ return hidden_states
916
+
917
+
918
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderLayerStableLayerNorm with Wav2Vec2->UniSpeech, WAV2VEC2->UNISPEECH
919
+ class UniSpeechEncoderLayerStableLayerNorm(nn.Module):
920
+ def __init__(self, config):
921
+ super().__init__()
922
+ self.attention = UNISPEECH_ATTENTION_CLASSES[config._attn_implementation](
923
+ embed_dim=config.hidden_size,
924
+ num_heads=config.num_attention_heads,
925
+ dropout=config.attention_dropout,
926
+ is_decoder=False,
927
+ )
928
+ self.dropout = nn.Dropout(config.hidden_dropout)
929
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
930
+ self.feed_forward = UniSpeechFeedForward(config)
931
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
932
+
933
+ if getattr(config, "adapter_attn_dim", None) is not None:
934
+ self.adapter_layer = UniSpeechAttnAdapterLayer(config)
935
+ else:
936
+ self.adapter_layer = None
937
+
938
+ def forward(
939
+ self,
940
+ hidden_states: torch.Tensor,
941
+ attention_mask: Optional[torch.Tensor] = None,
942
+ output_attentions: bool = False,
943
+ ):
944
+ attn_residual = hidden_states
945
+ hidden_states = self.layer_norm(hidden_states)
946
+ hidden_states, attn_weights, _ = self.attention(
947
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
948
+ )
949
+ hidden_states = self.dropout(hidden_states)
950
+ hidden_states = attn_residual + hidden_states
951
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
952
+
953
+ if self.adapter_layer is not None:
954
+ hidden_states = hidden_states + self.adapter_layer(hidden_states)
955
+
956
+ outputs = (hidden_states,)
957
+
958
+ if output_attentions:
959
+ outputs += (attn_weights,)
960
+
961
+ return outputs
962
+
963
+
964
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Encoder with Wav2Vec2->UniSpeech
965
+ class UniSpeechEncoder(nn.Module):
966
+ def __init__(self, config):
967
+ super().__init__()
968
+ self.config = config
969
+ self.pos_conv_embed = UniSpeechPositionalConvEmbedding(config)
970
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
971
+ self.dropout = nn.Dropout(config.hidden_dropout)
972
+ self.layers = nn.ModuleList([UniSpeechEncoderLayer(config) for _ in range(config.num_hidden_layers)])
973
+ self.gradient_checkpointing = False
974
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
975
+
976
+ def forward(
977
+ self,
978
+ hidden_states: torch.tensor,
979
+ attention_mask: Optional[torch.Tensor] = None,
980
+ output_attentions: bool = False,
981
+ output_hidden_states: bool = False,
982
+ return_dict: bool = True,
983
+ ):
984
+ all_hidden_states = () if output_hidden_states else None
985
+ all_self_attentions = () if output_attentions else None
986
+
987
+ if attention_mask is not None:
988
+ # make sure padded tokens output 0
989
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
990
+ hidden_states[~expand_attention_mask] = 0
991
+ if self._use_flash_attention_2:
992
+ # 2d mask is passed through the layers
993
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
994
+ else:
995
+ # extend attention_mask
996
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
997
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
998
+ attention_mask = attention_mask.expand(
999
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
1000
+ )
1001
+
1002
+ position_embeddings = self.pos_conv_embed(hidden_states)
1003
+ hidden_states = hidden_states + position_embeddings
1004
+ hidden_states = self.layer_norm(hidden_states)
1005
+ hidden_states = self.dropout(hidden_states)
1006
+
1007
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
1008
+
1009
+ for layer in self.layers:
1010
+ if output_hidden_states:
1011
+ all_hidden_states = all_hidden_states + (hidden_states,)
1012
+
1013
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1014
+ dropout_probability = torch.rand([])
1015
+
1016
+ skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False
1017
+ if not skip_the_layer or synced_gpus:
1018
+ # under fsdp or deepspeed zero3 all gpus must run in sync
1019
+ if self.gradient_checkpointing and self.training:
1020
+ layer_outputs = self._gradient_checkpointing_func(
1021
+ layer.__call__,
1022
+ hidden_states,
1023
+ attention_mask,
1024
+ output_attentions,
1025
+ )
1026
+ else:
1027
+ layer_outputs = layer(
1028
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
1029
+ )
1030
+ hidden_states = layer_outputs[0]
1031
+
1032
+ if skip_the_layer:
1033
+ layer_outputs = (None, None)
1034
+
1035
+ if output_attentions:
1036
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
1037
+
1038
+ if output_hidden_states:
1039
+ all_hidden_states = all_hidden_states + (hidden_states,)
1040
+
1041
+ if not return_dict:
1042
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
1043
+ return BaseModelOutput(
1044
+ last_hidden_state=hidden_states,
1045
+ hidden_states=all_hidden_states,
1046
+ attentions=all_self_attentions,
1047
+ )
1048
+
1049
+
1050
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderStableLayerNorm with Wav2Vec2->UniSpeech
1051
+ class UniSpeechEncoderStableLayerNorm(nn.Module):
1052
+ def __init__(self, config):
1053
+ super().__init__()
1054
+ self.config = config
1055
+ self.pos_conv_embed = UniSpeechPositionalConvEmbedding(config)
1056
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1057
+ self.dropout = nn.Dropout(config.hidden_dropout)
1058
+ self.layers = nn.ModuleList(
1059
+ [UniSpeechEncoderLayerStableLayerNorm(config) for _ in range(config.num_hidden_layers)]
1060
+ )
1061
+ self.gradient_checkpointing = False
1062
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1063
+
1064
+ def forward(
1065
+ self,
1066
+ hidden_states,
1067
+ attention_mask=None,
1068
+ output_attentions=False,
1069
+ output_hidden_states=False,
1070
+ return_dict=True,
1071
+ ):
1072
+ all_hidden_states = () if output_hidden_states else None
1073
+ all_self_attentions = () if output_attentions else None
1074
+
1075
+ if attention_mask is not None:
1076
+ # make sure padded tokens are not attended to
1077
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1078
+ hidden_states = hidden_states * expand_attention_mask.to(dtype=hidden_states.dtype)
1079
+ if self._use_flash_attention_2:
1080
+ # 2d mask is passed through the layers
1081
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1082
+ else:
1083
+ # extend attention_mask
1084
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
1085
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
1086
+ attention_mask = attention_mask.expand(
1087
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
1088
+ )
1089
+
1090
+ position_embeddings = self.pos_conv_embed(hidden_states)
1091
+ hidden_states = hidden_states + position_embeddings
1092
+ hidden_states = self.dropout(hidden_states)
1093
+
1094
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
1095
+
1096
+ for layer in self.layers:
1097
+ if output_hidden_states:
1098
+ all_hidden_states = all_hidden_states + (hidden_states,)
1099
+
1100
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1101
+ dropout_probability = torch.rand([])
1102
+
1103
+ skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False
1104
+ if not skip_the_layer or synced_gpus:
1105
+ # under fsdp or deepspeed zero3 all gpus must run in sync
1106
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
1107
+ if self.gradient_checkpointing and self.training:
1108
+ layer_outputs = self._gradient_checkpointing_func(
1109
+ layer.__call__,
1110
+ hidden_states,
1111
+ attention_mask,
1112
+ output_attentions,
1113
+ )
1114
+ else:
1115
+ layer_outputs = layer(
1116
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
1117
+ )
1118
+ hidden_states = layer_outputs[0]
1119
+
1120
+ if skip_the_layer:
1121
+ layer_outputs = (None, None)
1122
+
1123
+ if output_attentions:
1124
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
1125
+
1126
+ hidden_states = self.layer_norm(hidden_states)
1127
+
1128
+ if output_hidden_states:
1129
+ all_hidden_states = all_hidden_states + (hidden_states,)
1130
+
1131
+ if not return_dict:
1132
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
1133
+ return BaseModelOutput(
1134
+ last_hidden_state=hidden_states,
1135
+ hidden_states=all_hidden_states,
1136
+ attentions=all_self_attentions,
1137
+ )
1138
+
1139
+
1140
+ class UniSpeechGumbelVectorQuantizer(nn.Module):
1141
+ """
1142
+ Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH
1143
+ GUMBEL-SOFTMAX](https://arxiv.org/pdf/1611.01144.pdf) for more information.
1144
+ """
1145
+
1146
+ def __init__(self, config):
1147
+ super().__init__()
1148
+ self.num_groups = config.num_codevector_groups
1149
+ self.num_vars = config.num_codevectors_per_group
1150
+
1151
+ if config.codevector_dim % self.num_groups != 0:
1152
+ raise ValueError(
1153
+ f"`config.codevector_dim {config.codevector_dim} must be divisible by `config.num_codevector_groups`"
1154
+ f" {self.num_groups} for concatenation"
1155
+ )
1156
+
1157
+ # storage for codebook variables (codewords)
1158
+ self.codevectors = nn.Parameter(
1159
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
1160
+ )
1161
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
1162
+
1163
+ # can be decayed for training
1164
+ self.temperature = 2
1165
+
1166
+ @staticmethod
1167
+ def _compute_perplexity(probs):
1168
+ marginal_probs = probs.mean(dim=0)
1169
+ perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
1170
+ return perplexity
1171
+
1172
+ def forward(self, hidden_states):
1173
+ batch_size, sequence_length, hidden_size = hidden_states.shape
1174
+
1175
+ # project to codevector dim
1176
+ hidden_states = self.weight_proj(hidden_states)
1177
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
1178
+
1179
+ if self.training:
1180
+ # sample code vector probs via gumbel in differentiateable way
1181
+ codevector_probs = nn.functional.gumbel_softmax(
1182
+ hidden_states.float(), tau=self.temperature, hard=True
1183
+ ).type_as(hidden_states)
1184
+
1185
+ # compute perplexity
1186
+ codevector_soft_dist = torch.softmax(
1187
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
1188
+ )
1189
+ perplexity = self._compute_perplexity(codevector_soft_dist)
1190
+ else:
1191
+ # take argmax in non-differentiable way
1192
+ # comptute hard codevector distribution (one hot)
1193
+ codevector_idx = hidden_states.argmax(dim=-1)
1194
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
1195
+ -1, codevector_idx.view(-1, 1), 1.0
1196
+ )
1197
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
1198
+
1199
+ perplexity = self._compute_perplexity(codevector_probs)
1200
+
1201
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
1202
+ # use probs to retrieve codevectors
1203
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
1204
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
1205
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
1206
+
1207
+ return codevectors, perplexity
1208
+
1209
+
1210
+ class UniSpeechPreTrainedModel(PreTrainedModel):
1211
+ """
1212
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1213
+ models.
1214
+ """
1215
+
1216
+ config_class = UniSpeechConfig
1217
+ base_model_prefix = "unispeech"
1218
+ main_input_name = "input_values"
1219
+ supports_gradient_checkpointing = True
1220
+ _supports_flash_attn_2 = True
1221
+ _supports_sdpa = True
1222
+
1223
+ def _init_weights(self, module):
1224
+ """Initialize the weights"""
1225
+ # gumbel softmax requires special init
1226
+ if isinstance(module, UniSpeechGumbelVectorQuantizer):
1227
+ module.weight_proj.weight.data.normal_(mean=0.0, std=1)
1228
+ module.weight_proj.bias.data.zero_()
1229
+ nn.init.uniform_(module.codevectors)
1230
+ elif isinstance(module, UniSpeechPositionalConvEmbedding):
1231
+ nn.init.normal_(
1232
+ module.conv.weight,
1233
+ mean=0,
1234
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
1235
+ )
1236
+ nn.init.constant_(module.conv.bias, 0)
1237
+ elif isinstance(module, UniSpeechFeatureProjection):
1238
+ k = math.sqrt(1 / module.projection.in_features)
1239
+ nn.init.uniform_(module.projection.weight, a=-k, b=k)
1240
+ nn.init.uniform_(module.projection.bias, a=-k, b=k)
1241
+ elif isinstance(module, nn.Linear):
1242
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1243
+
1244
+ if module.bias is not None:
1245
+ module.bias.data.zero_()
1246
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
1247
+ module.bias.data.zero_()
1248
+ module.weight.data.fill_(1.0)
1249
+ elif isinstance(module, nn.Conv1d):
1250
+ nn.init.kaiming_normal_(module.weight)
1251
+
1252
+ if module.bias is not None:
1253
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
1254
+ nn.init.uniform_(module.bias, a=-k, b=k)
1255
+
1256
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
1257
+ """
1258
+ Computes the output length of the convolutional layers
1259
+ """
1260
+
1261
+ def _conv_out_length(input_length, kernel_size, stride):
1262
+ # 1D convolutional layer output length formula taken
1263
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
1264
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
1265
+
1266
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
1267
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
1268
+
1269
+ return input_lengths
1270
+
1271
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
1272
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
1273
+ # on inference mode.
1274
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
1275
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long)
1276
+ batch_size = attention_mask.shape[0]
1277
+
1278
+ attention_mask = torch.zeros(
1279
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
1280
+ )
1281
+ # these two operations makes sure that all values before the output lengths idxs are attended to
1282
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
1283
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
1284
+ return attention_mask
1285
+
1286
+
1287
+ UNISPEECH_START_DOCSTRING = r"""
1288
+ UniSpeech was proposed in [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled
1289
+ Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei,
1290
+ Michael Zeng, Xuedong Huang.
1291
+
1292
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1293
+ library implements for all its model (such as downloading or saving etc.).
1294
+
1295
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
1296
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
1297
+ behavior.
1298
+
1299
+ Parameters:
1300
+ config ([`UniSpeechConfig`]): Model configuration class with all the parameters of the model.
1301
+ Initializing with a config file does not load the weights associated with the model, only the
1302
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1303
+ """
1304
+
1305
+
1306
+ UNISPEECH_INPUTS_DOCSTRING = r"""
1307
+ Args:
1308
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1309
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1310
+ into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install
1311
+ soundfile`). To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and
1312
+ conversion into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
1313
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1314
+ Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,
1315
+ 1]`:
1316
+
1317
+ - 1 for tokens that are **not masked**,
1318
+ - 0 for tokens that are **masked**.
1319
+
1320
+ [What are attention masks?](../glossary#attention-mask)
1321
+
1322
+ <Tip warning={true}>
1323
+
1324
+ `attention_mask` should only be passed if the corresponding processor has `config.return_attention_mask ==
1325
+ True`. For all models whose processor has `config.return_attention_mask == False`, `attention_mask` should
1326
+ **not** be passed to avoid degraded performance when doing batched inference. For such models
1327
+ `input_values` should simply be padded with 0 and passed without `attention_mask`. Be aware that these
1328
+ models also yield slightly different results depending on whether `input_values` is padded or not.
1329
+
1330
+ </Tip>
1331
+
1332
+ output_attentions (`bool`, *optional*):
1333
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1334
+ tensors for more detail.
1335
+ output_hidden_states (`bool`, *optional*):
1336
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1337
+ more detail.
1338
+ return_dict (`bool`, *optional*):
1339
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1340
+ """
1341
+
1342
+
1343
+ @add_start_docstrings(
1344
+ "The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.",
1345
+ UNISPEECH_START_DOCSTRING,
1346
+ )
1347
+ class UniSpeechModel(UniSpeechPreTrainedModel):
1348
+ def __init__(self, config: UniSpeechConfig):
1349
+ super().__init__(config)
1350
+ self.config = config
1351
+ self.feature_extractor = UniSpeechFeatureEncoder(config)
1352
+ self.feature_projection = UniSpeechFeatureProjection(config)
1353
+
1354
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
1355
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
1356
+
1357
+ if config.do_stable_layer_norm:
1358
+ self.encoder = UniSpeechEncoderStableLayerNorm(config)
1359
+ else:
1360
+ self.encoder = UniSpeechEncoder(config)
1361
+
1362
+ # Initialize weights and apply final processing
1363
+ self.post_init()
1364
+
1365
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model._mask_hidden_states
1366
+ def _mask_hidden_states(
1367
+ self,
1368
+ hidden_states: torch.FloatTensor,
1369
+ mask_time_indices: Optional[torch.FloatTensor] = None,
1370
+ attention_mask: Optional[torch.LongTensor] = None,
1371
+ ):
1372
+ """
1373
+ Masks extracted features along time axis and/or along feature axis according to
1374
+ [SpecAugment](https://arxiv.org/abs/1904.08779).
1375
+ """
1376
+
1377
+ # `config.apply_spec_augment` can set masking to False
1378
+ if not getattr(self.config, "apply_spec_augment", True):
1379
+ return hidden_states
1380
+
1381
+ # generate indices & apply SpecAugment along time axis
1382
+ batch_size, sequence_length, hidden_size = hidden_states.size()
1383
+
1384
+ if mask_time_indices is not None:
1385
+ # apply SpecAugment along time axis with given mask_time_indices
1386
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1387
+ elif self.config.mask_time_prob > 0 and self.training:
1388
+ mask_time_indices = _compute_mask_indices(
1389
+ (batch_size, sequence_length),
1390
+ mask_prob=self.config.mask_time_prob,
1391
+ mask_length=self.config.mask_time_length,
1392
+ attention_mask=attention_mask,
1393
+ min_masks=self.config.mask_time_min_masks,
1394
+ )
1395
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
1396
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1397
+
1398
+ if self.config.mask_feature_prob > 0 and self.training:
1399
+ # generate indices & apply SpecAugment along feature axis
1400
+ mask_feature_indices = _compute_mask_indices(
1401
+ (batch_size, hidden_size),
1402
+ mask_prob=self.config.mask_feature_prob,
1403
+ mask_length=self.config.mask_feature_length,
1404
+ min_masks=self.config.mask_feature_min_masks,
1405
+ )
1406
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
1407
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
1408
+ hidden_states[mask_feature_indices] = 0
1409
+
1410
+ return hidden_states
1411
+
1412
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1413
+ @add_code_sample_docstrings(
1414
+ checkpoint=_CHECKPOINT_FOR_DOC,
1415
+ output_type=Wav2Vec2BaseModelOutput,
1416
+ config_class=_CONFIG_FOR_DOC,
1417
+ modality="audio",
1418
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
1419
+ )
1420
+ def forward(
1421
+ self,
1422
+ input_values: Optional[torch.Tensor],
1423
+ attention_mask: Optional[torch.Tensor] = None,
1424
+ mask_time_indices: Optional[torch.FloatTensor] = None,
1425
+ output_attentions: Optional[bool] = None,
1426
+ output_hidden_states: Optional[bool] = None,
1427
+ return_dict: Optional[bool] = None,
1428
+ ) -> Union[Tuple, Wav2Vec2BaseModelOutput]:
1429
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1430
+ output_hidden_states = (
1431
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1432
+ )
1433
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1434
+
1435
+ extract_features = self.feature_extractor(input_values)
1436
+ extract_features = extract_features.transpose(1, 2)
1437
+
1438
+ if attention_mask is not None:
1439
+ # compute reduced attention_mask corresponding to feature vectors
1440
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
1441
+
1442
+ hidden_states, extract_features = self.feature_projection(extract_features)
1443
+ hidden_states = self._mask_hidden_states(
1444
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1445
+ )
1446
+
1447
+ encoder_outputs = self.encoder(
1448
+ hidden_states,
1449
+ attention_mask=attention_mask,
1450
+ output_attentions=output_attentions,
1451
+ output_hidden_states=output_hidden_states,
1452
+ return_dict=return_dict,
1453
+ )
1454
+
1455
+ hidden_states = encoder_outputs[0]
1456
+
1457
+ if not return_dict:
1458
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1459
+
1460
+ return Wav2Vec2BaseModelOutput(
1461
+ last_hidden_state=hidden_states,
1462
+ extract_features=extract_features,
1463
+ hidden_states=encoder_outputs.hidden_states,
1464
+ attentions=encoder_outputs.attentions,
1465
+ )
1466
+
1467
+
1468
+ @add_start_docstrings(
1469
+ """UniSpeech Model with a vector-quantization module and ctc loss for pre-training.""", UNISPEECH_START_DOCSTRING
1470
+ )
1471
+ class UniSpeechForPreTraining(UniSpeechPreTrainedModel):
1472
+ def __init__(self, config: UniSpeechConfig):
1473
+ super().__init__(config)
1474
+ self.unispeech = UniSpeechModel(config)
1475
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
1476
+
1477
+ self.quantizer = UniSpeechGumbelVectorQuantizer(config)
1478
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
1479
+ self.project_hid = nn.Linear(config.proj_codevector_dim, config.hidden_size)
1480
+
1481
+ self.ctc_proj = nn.Linear(config.hidden_size, config.num_ctc_classes)
1482
+ self.dropout = nn.Dropout(config.final_dropout)
1483
+
1484
+ # Initialize weights and apply final processing
1485
+ self.post_init()
1486
+
1487
+ def set_gumbel_temperature(self, temperature: int):
1488
+ """
1489
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
1490
+ """
1491
+ self.quantizer.temperature = temperature
1492
+
1493
+ def freeze_feature_extractor(self):
1494
+ """
1495
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1496
+ not be updated during training.
1497
+ """
1498
+ warnings.warn(
1499
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1500
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1501
+ FutureWarning,
1502
+ )
1503
+ self.freeze_feature_encoder()
1504
+
1505
+ def freeze_feature_encoder(self):
1506
+ """
1507
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1508
+ not be updated during training.
1509
+ """
1510
+ self.unispeech.feature_extractor._freeze_parameters()
1511
+
1512
+ @staticmethod
1513
+ def compute_contrastive_logits(
1514
+ target_features: torch.FloatTensor,
1515
+ negative_features: torch.FloatTensor,
1516
+ predicted_features: torch.FloatTensor,
1517
+ temperature: int = 1,
1518
+ ):
1519
+ """
1520
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
1521
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
1522
+ """
1523
+ target_features = torch.cat([target_features, negative_features], dim=0)
1524
+
1525
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1)
1526
+ logits = logits.type_as(target_features)
1527
+
1528
+ # apply temperature
1529
+ logits = logits / temperature
1530
+ return logits
1531
+
1532
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1533
+ @replace_return_docstrings(output_type=UniSpeechForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1534
+ def forward(
1535
+ self,
1536
+ input_values: Optional[torch.Tensor],
1537
+ attention_mask: Optional[torch.Tensor] = None,
1538
+ output_attentions: Optional[bool] = None,
1539
+ output_hidden_states: Optional[bool] = None,
1540
+ return_dict: Optional[bool] = None,
1541
+ ) -> Union[Tuple, UniSpeechForPreTrainingOutput]:
1542
+ r"""
1543
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1544
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1545
+ masked extracted features in *config.proj_codevector_dim* space.
1546
+ sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):
1547
+ Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.
1548
+ Required input for pre-training.
1549
+
1550
+ Returns:
1551
+
1552
+ Example:
1553
+
1554
+ ```python
1555
+ >>> import torch
1556
+ >>> from transformers import AutoFeatureExtractor, UniSpeechForPreTraining
1557
+
1558
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-large-1500h-cv")
1559
+ >>> model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv")
1560
+ >>> # TODO: Add full pretraining example
1561
+ ```"""
1562
+
1563
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1564
+
1565
+ outputs = self.unispeech(
1566
+ input_values,
1567
+ attention_mask=attention_mask,
1568
+ output_attentions=output_attentions,
1569
+ output_hidden_states=output_hidden_states,
1570
+ return_dict=return_dict,
1571
+ )
1572
+ transformer_features = outputs[0]
1573
+
1574
+ # quantize all (unmasked) extracted features and project to final vq dim
1575
+ extract_features = self.dropout_features(outputs[1])
1576
+ quantized_features, codevector_perplexity = self.quantizer(extract_features)
1577
+
1578
+ # project quantized features twice
1579
+ quantized_features = self.project_q(quantized_features.to(self.project_q.weight.dtype))
1580
+ quantized_features = self.project_hid(quantized_features)
1581
+
1582
+ prob_replace_matrix = torch.empty(transformer_features.size(0), transformer_features.size(1)).fill_(
1583
+ self.config.replace_prob
1584
+ )
1585
+ prob_replace_matrix = prob_replace_matrix.transpose(0, 1)
1586
+ sampled_replace_matrix = torch.bernoulli(prob_replace_matrix).bool().to(transformer_features.device)
1587
+ sampled_replace_matrix = sampled_replace_matrix.transpose(0, 1)
1588
+ sampled_replace_matrix = sampled_replace_matrix.unsqueeze(-1)
1589
+ logits = transformer_features.masked_fill(sampled_replace_matrix, 0.0) + (
1590
+ quantized_features.masked_fill(~sampled_replace_matrix, 0.0)
1591
+ )
1592
+
1593
+ # project to ctc units
1594
+ logits = self.dropout(logits)
1595
+ logits = self.ctc_proj(logits)
1596
+
1597
+ # TODO(PVP) - add negative sampling & loss computation
1598
+ loss = None
1599
+ if not return_dict:
1600
+ if loss is not None:
1601
+ return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1602
+ return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1603
+
1604
+ return UniSpeechForPreTrainingOutput(
1605
+ loss=loss,
1606
+ projected_states=transformer_features,
1607
+ projected_quantized_states=quantized_features,
1608
+ codevector_perplexity=codevector_perplexity,
1609
+ hidden_states=outputs.hidden_states,
1610
+ attentions=outputs.attentions,
1611
+ )
1612
+
1613
+
1614
+ @add_start_docstrings(
1615
+ """UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).""",
1616
+ UNISPEECH_START_DOCSTRING,
1617
+ """
1618
+ target_lang (`str`, *optional*):
1619
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1620
+ adapter.<lang>.bin. Only relevant when using an instance of [`UniSpeechForCTC`] with adapters. Uses 'eng'
1621
+ by default.
1622
+ """,
1623
+ )
1624
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC with Wav2Vec2->UniSpeech, wav2vec2->unispeech, WAV_2_VEC_2->UNISPEECH
1625
+ class UniSpeechForCTC(UniSpeechPreTrainedModel):
1626
+ def __init__(self, config, target_lang: Optional[str] = None):
1627
+ super().__init__(config)
1628
+
1629
+ self.unispeech = UniSpeechModel(config)
1630
+ self.dropout = nn.Dropout(config.final_dropout)
1631
+
1632
+ self.target_lang = target_lang
1633
+
1634
+ if config.vocab_size is None:
1635
+ raise ValueError(
1636
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1637
+ "does not define the vocabulary size of the language model head. Please "
1638
+ "instantiate the model as follows: `UniSpeechForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1639
+ "or define `vocab_size` of your model's configuration."
1640
+ )
1641
+ output_hidden_size = (
1642
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1643
+ )
1644
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1645
+
1646
+ # Initialize weights and apply final processing
1647
+ self.post_init()
1648
+
1649
+ def tie_weights(self):
1650
+ """
1651
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
1652
+ passing `target_lang=...` to `from_pretrained(...)`.
1653
+
1654
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
1655
+ """
1656
+
1657
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
1658
+ # correctly load adapter layers for UniSpeech so that we do not have to introduce a new API to
1659
+ # [`PreTrainedModel`]. While slightly hacky, UniSpeech never has to tie input and output embeddings, so that it is
1660
+ # ok to repurpose this function here.
1661
+ target_lang = self.target_lang
1662
+
1663
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
1664
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
1665
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
1666
+ logger.info("By default `target_lang` is set to 'eng'.")
1667
+ elif target_lang is not None:
1668
+ self.load_adapter(target_lang, force_load=True)
1669
+
1670
+ def freeze_feature_extractor(self):
1671
+ """
1672
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1673
+ not be updated during training.
1674
+ """
1675
+ warnings.warn(
1676
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1677
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1678
+ FutureWarning,
1679
+ )
1680
+ self.freeze_feature_encoder()
1681
+
1682
+ def freeze_feature_encoder(self):
1683
+ """
1684
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1685
+ not be updated during training.
1686
+ """
1687
+ self.unispeech.feature_extractor._freeze_parameters()
1688
+
1689
+ def freeze_base_model(self):
1690
+ """
1691
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1692
+ be updated during training. Only the classification head will be updated.
1693
+ """
1694
+ for param in self.unispeech.parameters():
1695
+ param.requires_grad = False
1696
+
1697
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1698
+ @add_code_sample_docstrings(
1699
+ checkpoint=_CHECKPOINT_FOR_DOC,
1700
+ output_type=CausalLMOutput,
1701
+ config_class=_CONFIG_FOR_DOC,
1702
+ expected_output=_CTC_EXPECTED_OUTPUT,
1703
+ expected_loss=_CTC_EXPECTED_LOSS,
1704
+ )
1705
+ def forward(
1706
+ self,
1707
+ input_values: Optional[torch.Tensor],
1708
+ attention_mask: Optional[torch.Tensor] = None,
1709
+ output_attentions: Optional[bool] = None,
1710
+ output_hidden_states: Optional[bool] = None,
1711
+ return_dict: Optional[bool] = None,
1712
+ labels: Optional[torch.Tensor] = None,
1713
+ ) -> Union[Tuple, CausalLMOutput]:
1714
+ r"""
1715
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1716
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1717
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1718
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1719
+ config.vocab_size - 1]`.
1720
+ """
1721
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1722
+
1723
+ if labels is not None and labels.max() >= self.config.vocab_size:
1724
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1725
+
1726
+ outputs = self.unispeech(
1727
+ input_values,
1728
+ attention_mask=attention_mask,
1729
+ output_attentions=output_attentions,
1730
+ output_hidden_states=output_hidden_states,
1731
+ return_dict=return_dict,
1732
+ )
1733
+
1734
+ hidden_states = outputs[0]
1735
+ hidden_states = self.dropout(hidden_states)
1736
+
1737
+ logits = self.lm_head(hidden_states)
1738
+
1739
+ loss = None
1740
+ if labels is not None:
1741
+ # retrieve loss input_lengths from attention_mask
1742
+ attention_mask = (
1743
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1744
+ )
1745
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1746
+
1747
+ # assuming that padded tokens are filled with -100
1748
+ # when not being attended to
1749
+ labels_mask = labels >= 0
1750
+ target_lengths = labels_mask.sum(-1)
1751
+ flattened_targets = labels.masked_select(labels_mask)
1752
+
1753
+ # ctc_loss doesn't support fp16
1754
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1755
+
1756
+ with torch.backends.cudnn.flags(enabled=False):
1757
+ loss = nn.functional.ctc_loss(
1758
+ log_probs,
1759
+ flattened_targets,
1760
+ input_lengths,
1761
+ target_lengths,
1762
+ blank=self.config.pad_token_id,
1763
+ reduction=self.config.ctc_loss_reduction,
1764
+ zero_infinity=self.config.ctc_zero_infinity,
1765
+ )
1766
+
1767
+ if not return_dict:
1768
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1769
+ return ((loss,) + output) if loss is not None else output
1770
+
1771
+ return CausalLMOutput(
1772
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1773
+ )
1774
+
1775
+
1776
+ @add_start_docstrings(
1777
+ """
1778
+ UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1779
+ SUPERB Keyword Spotting.
1780
+ """,
1781
+ UNISPEECH_START_DOCSTRING,
1782
+ )
1783
+ class UniSpeechForSequenceClassification(UniSpeechPreTrainedModel):
1784
+ def __init__(self, config):
1785
+ super().__init__(config)
1786
+
1787
+ if hasattr(config, "add_adapter") and config.add_adapter:
1788
+ raise ValueError(
1789
+ "Sequence classification does not support the use of UniSpeech adapters (config.add_adapter=True)"
1790
+ )
1791
+ self.unispeech = UniSpeechModel(config)
1792
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1793
+ if config.use_weighted_layer_sum:
1794
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1795
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1796
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1797
+
1798
+ # Initialize weights and apply final processing
1799
+ self.post_init()
1800
+
1801
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.freeze_feature_extractor
1802
+ def freeze_feature_extractor(self):
1803
+ """
1804
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1805
+ not be updated during training.
1806
+ """
1807
+ warnings.warn(
1808
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1809
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1810
+ FutureWarning,
1811
+ )
1812
+ self.freeze_feature_encoder()
1813
+
1814
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.freeze_feature_encoder with wav2vec2->unispeech
1815
+ def freeze_feature_encoder(self):
1816
+ """
1817
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1818
+ not be updated during training.
1819
+ """
1820
+ self.unispeech.feature_extractor._freeze_parameters()
1821
+
1822
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.freeze_base_model with wav2vec2->unispeech
1823
+ def freeze_base_model(self):
1824
+ """
1825
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1826
+ be updated during training. Only the classification head will be updated.
1827
+ """
1828
+ for param in self.unispeech.parameters():
1829
+ param.requires_grad = False
1830
+
1831
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1832
+ @add_code_sample_docstrings(
1833
+ checkpoint=_CHECKPOINT_FOR_DOC,
1834
+ output_type=SequenceClassifierOutput,
1835
+ config_class=_CONFIG_FOR_DOC,
1836
+ modality="audio",
1837
+ )
1838
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.forward with Wav2Vec2->UniSpeech, wav2vec2->unispeech
1839
+ def forward(
1840
+ self,
1841
+ input_values: Optional[torch.Tensor],
1842
+ attention_mask: Optional[torch.Tensor] = None,
1843
+ output_attentions: Optional[bool] = None,
1844
+ output_hidden_states: Optional[bool] = None,
1845
+ return_dict: Optional[bool] = None,
1846
+ labels: Optional[torch.Tensor] = None,
1847
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1848
+ r"""
1849
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1850
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1851
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1852
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1853
+ """
1854
+
1855
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1856
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1857
+
1858
+ outputs = self.unispeech(
1859
+ input_values,
1860
+ attention_mask=attention_mask,
1861
+ output_attentions=output_attentions,
1862
+ output_hidden_states=output_hidden_states,
1863
+ return_dict=return_dict,
1864
+ )
1865
+
1866
+ if self.config.use_weighted_layer_sum:
1867
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1868
+ hidden_states = torch.stack(hidden_states, dim=1)
1869
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1870
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1871
+ else:
1872
+ hidden_states = outputs[0]
1873
+
1874
+ hidden_states = self.projector(hidden_states)
1875
+ if attention_mask is None:
1876
+ pooled_output = hidden_states.mean(dim=1)
1877
+ else:
1878
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1879
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1880
+ hidden_states[~expand_padding_mask] = 0.0
1881
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1882
+
1883
+ logits = self.classifier(pooled_output)
1884
+
1885
+ loss = None
1886
+ if labels is not None:
1887
+ loss_fct = CrossEntropyLoss()
1888
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1889
+
1890
+ if not return_dict:
1891
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1892
+ return ((loss,) + output) if loss is not None else output
1893
+
1894
+ return SequenceClassifierOutput(
1895
+ loss=loss,
1896
+ logits=logits,
1897
+ hidden_states=outputs.hidden_states,
1898
+ attentions=outputs.attentions,
1899
+ )
1900
+
1901
+
1902
+ __all__ = [
1903
+ "UniSpeechForCTC",
1904
+ "UniSpeechForPreTraining",
1905
+ "UniSpeechForSequenceClassification",
1906
+ "UniSpeechModel",
1907
+ "UniSpeechPreTrainedModel",
1908
+ ]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_unispeech_sat import *
22
+ from .modeling_unispeech_sat import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/configuration_unispeech_sat.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """UniSpeechSat model configuration"""
16
+
17
+ import functools
18
+ import operator
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class UniSpeechSatConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`UniSpeechSatModel`]. It is used to instantiate an
30
+ UniSpeechSat model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the UniSpeechSat
32
+ [microsoft/unispeech-sat-base-100h-libri-ft](https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft)
33
+ architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32):
41
+ Vocabulary size of the UniSpeechSat model. Defines the number of different tokens that can be represented
42
+ by the `inputs_ids` passed when calling [`UniSpeechSatModel`]. Vocabulary size of the model. Defines the
43
+ different tokens that can be represented by the *inputs_ids* passed to the forward method of
44
+ [`UniSpeechSatModel`].
45
+ hidden_size (`int`, *optional*, defaults to 768):
46
+ Dimensionality of the encoder layers and the pooler layer.
47
+ num_hidden_layers (`int`, *optional*, defaults to 12):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 12):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ intermediate_size (`int`, *optional*, defaults to 3072):
52
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
54
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
55
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
56
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
57
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
58
+ activation_dropout (`float`, *optional*, defaults to 0.1):
59
+ The dropout ratio for activations inside the fully connected layer.
60
+ attention_dropout (`float`, *optional*, defaults to 0.1):
61
+ The dropout ratio for the attention probabilities.
62
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout probability for output of the feature encoder.
64
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout probability for the output of the feature encoder that's used by the quantizer.
66
+ final_dropout (`float`, *optional*, defaults to 0.1):
67
+ The dropout probability for the final projection layer of [`UniSpeechSatForCTC`].
68
+ layerdrop (`float`, *optional*, defaults to 0.1):
69
+ The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more
70
+ details.
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
74
+ The epsilon used by the layer normalization layers.
75
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
76
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
77
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
78
+ convolutional layers.
79
+ feat_extract_activation (`str, *optional*, defaults to `"gelu"`):
80
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
81
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
82
+ conv_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
83
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
84
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
85
+ conv_stride (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
86
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
87
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
88
+ conv_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 2, 2)`):
89
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
90
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
91
+ *conv_dim*.
92
+ conv_bias (`bool`, *optional*, defaults to `False`):
93
+ Whether the 1D convolutional layers have a bias.
94
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
95
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
96
+ embeddings layer.
97
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
98
+ Number of groups of 1D convolutional positional embeddings layer.
99
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
100
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
101
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
102
+ False` corresponds to applying layer norm after the attention layer.
103
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
104
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
105
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
106
+ Recognition](https://arxiv.org/abs/1904.08779).
107
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
108
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
109
+ procecure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
110
+ reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
111
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
112
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
113
+ mask_time_length (`int`, *optional*, defaults to 10):
114
+ Length of vector span along the time axis.
115
+ mask_time_min_masks (`int`, *optional*, defaults to 2):
116
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
117
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
118
+ mask_time_min_masks''
119
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
120
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
121
+ masking procecure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
122
+ the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
123
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
124
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
125
+ True`.
126
+ mask_feature_length (`int`, *optional*, defaults to 10):
127
+ Length of vector span along the feature axis.
128
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
129
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
130
+ step, irrespectively of `mask_feature_prob`. Only relevant if
131
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
132
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
133
+ Number of entries in each quantization codebook (group).
134
+ num_codevector_groups (`int`, *optional*, defaults to 2):
135
+ Number of codevector groups for product codevector quantization.
136
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
137
+ The temperature *kappa* in the contrastive loss.
138
+ num_negatives (`int`, *optional*, defaults to 100):
139
+ Number of negative samples for the contrastive loss.
140
+ codevector_dim (`int`, *optional*, defaults to 256):
141
+ Dimensionality of the quantized feature vectors.
142
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
143
+ Dimensionality of the final projection of both the quantized and the transformer features.
144
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
145
+ The weight of the codebook diversity loss component.
146
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
147
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
148
+ instance of [`UniSpeechSatForCTC`].
149
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
150
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
151
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
152
+ of [`UniSpeechSatForCTC`].
153
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
154
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
155
+ instance of [`UniSpeechSatForSequenceClassification`].
156
+ classifier_proj_size (`int`, *optional*, defaults to 256):
157
+ Dimensionality of the projection before token mean-pooling for classification.
158
+ tdnn_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
159
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
160
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
161
+ tdnn_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
162
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
163
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
164
+ tdnn_dilation (`Tuple[int]` or `List[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
165
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
166
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
167
+ xvector_output_dim (`int`, *optional*, defaults to 512):
168
+ Dimensionality of the *XVector* embedding vectors.
169
+ pad_token_id (`int`, *optional*, defaults to 0):
170
+ The id of the padding token.
171
+ bos_token_id (`int`, *optional*, defaults to 1):
172
+ The id of the "beginning-of-sequence" token.
173
+ eos_token_id (`int`, *optional*, defaults to 2):
174
+ The id of the "end-of-sequence" token.
175
+ num_clusters (`int`, *optional*, defaults to 504):
176
+ Number of clusters for weak labeling. Only relevant when using an instance of
177
+ [`UniSpeechSatForPreTraining`].
178
+
179
+ Example:
180
+
181
+ ```python
182
+ >>> from transformers import UniSpeechSatModel, UniSpeechSatConfig
183
+
184
+ >>> # Initializing a UniSpeechSat microsoft/unispeech-sat-base-100h-libri-ft style configuration
185
+ >>> configuration = UniSpeechSatConfig()
186
+
187
+ >>> # Initializing a model from the microsoft/unispeech-sat-base-100h-libri-ft style configuration
188
+ >>> model = UniSpeechSatModel(configuration)
189
+
190
+ >>> # Accessing the model configuration
191
+ >>> configuration = model.config
192
+ ```"""
193
+
194
+ model_type = "unispeech-sat"
195
+
196
+ def __init__(
197
+ self,
198
+ vocab_size=32,
199
+ hidden_size=768,
200
+ num_hidden_layers=12,
201
+ num_attention_heads=12,
202
+ intermediate_size=3072,
203
+ hidden_act="gelu",
204
+ hidden_dropout=0.1,
205
+ activation_dropout=0.1,
206
+ attention_dropout=0.1,
207
+ feat_proj_dropout=0.0,
208
+ feat_quantizer_dropout=0.0,
209
+ final_dropout=0.1,
210
+ layerdrop=0.1,
211
+ initializer_range=0.02,
212
+ layer_norm_eps=1e-5,
213
+ feat_extract_norm="group",
214
+ feat_extract_activation="gelu",
215
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
216
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
217
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
218
+ conv_bias=False,
219
+ num_conv_pos_embeddings=128,
220
+ num_conv_pos_embedding_groups=16,
221
+ do_stable_layer_norm=False,
222
+ apply_spec_augment=True,
223
+ mask_time_prob=0.05,
224
+ mask_time_length=10,
225
+ mask_time_min_masks=2,
226
+ mask_feature_prob=0.0,
227
+ mask_feature_length=10,
228
+ mask_feature_min_masks=0,
229
+ num_codevectors_per_group=320,
230
+ num_codevector_groups=2,
231
+ contrastive_logits_temperature=0.1,
232
+ num_negatives=100,
233
+ codevector_dim=256,
234
+ proj_codevector_dim=256,
235
+ diversity_loss_weight=0.1,
236
+ ctc_loss_reduction="mean",
237
+ ctc_zero_infinity=False,
238
+ use_weighted_layer_sum=False,
239
+ classifier_proj_size=256,
240
+ tdnn_dim=(512, 512, 512, 512, 1500),
241
+ tdnn_kernel=(5, 3, 3, 1, 1),
242
+ tdnn_dilation=(1, 2, 3, 1, 1),
243
+ xvector_output_dim=512,
244
+ pad_token_id=0,
245
+ bos_token_id=1,
246
+ eos_token_id=2,
247
+ num_clusters=504,
248
+ **kwargs,
249
+ ):
250
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
251
+ self.hidden_size = hidden_size
252
+ self.feat_extract_norm = feat_extract_norm
253
+ self.feat_extract_activation = feat_extract_activation
254
+ self.conv_dim = list(conv_dim)
255
+ self.conv_stride = list(conv_stride)
256
+ self.conv_kernel = list(conv_kernel)
257
+ self.conv_bias = conv_bias
258
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
259
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
260
+ self.num_feat_extract_layers = len(self.conv_dim)
261
+ self.num_hidden_layers = num_hidden_layers
262
+ self.intermediate_size = intermediate_size
263
+ self.hidden_act = hidden_act
264
+ self.num_attention_heads = num_attention_heads
265
+ self.hidden_dropout = hidden_dropout
266
+ self.attention_dropout = attention_dropout
267
+ self.activation_dropout = activation_dropout
268
+ self.feat_proj_dropout = feat_proj_dropout
269
+ self.final_dropout = final_dropout
270
+ self.layerdrop = layerdrop
271
+ self.layer_norm_eps = layer_norm_eps
272
+ self.initializer_range = initializer_range
273
+ self.vocab_size = vocab_size
274
+ self.num_clusters = num_clusters
275
+ self.do_stable_layer_norm = do_stable_layer_norm
276
+ self.use_weighted_layer_sum = use_weighted_layer_sum
277
+
278
+ if (
279
+ (len(self.conv_stride) != self.num_feat_extract_layers)
280
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
281
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
282
+ ):
283
+ raise ValueError(
284
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
285
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
286
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
287
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
288
+ )
289
+
290
+ # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
291
+ self.apply_spec_augment = apply_spec_augment
292
+ self.mask_time_prob = mask_time_prob
293
+ self.mask_time_length = mask_time_length
294
+ self.mask_time_min_masks = mask_time_min_masks
295
+ self.mask_feature_prob = mask_feature_prob
296
+ self.mask_feature_length = mask_feature_length
297
+ self.mask_feature_min_masks = mask_feature_min_masks
298
+
299
+ # parameters for pretraining with codevector quantized representations
300
+ self.num_codevectors_per_group = num_codevectors_per_group
301
+ self.num_codevector_groups = num_codevector_groups
302
+ self.contrastive_logits_temperature = contrastive_logits_temperature
303
+ self.feat_quantizer_dropout = feat_quantizer_dropout
304
+ self.num_negatives = num_negatives
305
+ self.codevector_dim = codevector_dim
306
+ self.proj_codevector_dim = proj_codevector_dim
307
+ self.diversity_loss_weight = diversity_loss_weight
308
+
309
+ # ctc loss
310
+ self.ctc_loss_reduction = ctc_loss_reduction
311
+ self.ctc_zero_infinity = ctc_zero_infinity
312
+
313
+ # SequenceClassification-specific parameter. Feel free to ignore for other classes.
314
+ self.classifier_proj_size = classifier_proj_size
315
+
316
+ # XVector-specific parameters. Feel free to ignore for other classes.
317
+ self.tdnn_dim = list(tdnn_dim)
318
+ self.tdnn_kernel = list(tdnn_kernel)
319
+ self.tdnn_dilation = list(tdnn_dilation)
320
+ self.xvector_output_dim = xvector_output_dim
321
+
322
+ @property
323
+ def inputs_to_logits_ratio(self):
324
+ return functools.reduce(operator.mul, self.conv_stride, 1)
325
+
326
+
327
+ __all__ = ["UniSpeechSatConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert Hubert checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+
21
+ from transformers import (
22
+ UniSpeechSatConfig,
23
+ UniSpeechSatForAudioFrameClassification,
24
+ UniSpeechSatForSequenceClassification,
25
+ UniSpeechSatForXVector,
26
+ Wav2Vec2FeatureExtractor,
27
+ logging,
28
+ )
29
+
30
+
31
+ logging.set_verbosity_info()
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ def convert_classification(base_model_name, hf_config, downstream_dict):
36
+ model = UniSpeechSatForSequenceClassification.from_pretrained(base_model_name, config=hf_config)
37
+ model.projector.weight.data = downstream_dict["projector.weight"]
38
+ model.projector.bias.data = downstream_dict["projector.bias"]
39
+ model.classifier.weight.data = downstream_dict["model.post_net.linear.weight"]
40
+ model.classifier.bias.data = downstream_dict["model.post_net.linear.bias"]
41
+ return model
42
+
43
+
44
+ def convert_diarization(base_model_name, hf_config, downstream_dict):
45
+ model = UniSpeechSatForAudioFrameClassification.from_pretrained(base_model_name, config=hf_config)
46
+ model.classifier.weight.data = downstream_dict["model.linear.weight"]
47
+ model.classifier.bias.data = downstream_dict["model.linear.bias"]
48
+ return model
49
+
50
+
51
+ def convert_xvector(base_model_name, hf_config, downstream_dict):
52
+ model = UniSpeechSatForXVector.from_pretrained(base_model_name, config=hf_config)
53
+ model.projector.weight.data = downstream_dict["connector.weight"]
54
+ model.projector.bias.data = downstream_dict["connector.bias"]
55
+ for i, kernel_size in enumerate(hf_config.tdnn_kernel):
56
+ model.tdnn[i].kernel.weight.data = downstream_dict[
57
+ f"model.framelevel_feature_extractor.module.{i}.kernel.weight"
58
+ ]
59
+ model.tdnn[i].kernel.bias.data = downstream_dict[f"model.framelevel_feature_extractor.module.{i}.kernel.bias"]
60
+
61
+ model.feature_extractor.weight.data = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"]
62
+ model.feature_extractor.bias.data = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"]
63
+ model.classifier.weight.data = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"]
64
+ model.classifier.bias.data = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"]
65
+ model.objective.weight.data = downstream_dict["objective.W"]
66
+ return model
67
+
68
+
69
+ @torch.no_grad()
70
+ def convert_s3prl_checkpoint(base_model_name, config_path, checkpoint_path, model_dump_path):
71
+ """
72
+ Copy/paste/tweak model's weights to transformers design.
73
+ """
74
+ checkpoint = torch.load(checkpoint_path, map_location="cpu")
75
+
76
+ downstream_dict = checkpoint["Downstream"]
77
+
78
+ hf_config = UniSpeechSatConfig.from_pretrained(config_path)
79
+ hf_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
80
+ base_model_name, return_attention_mask=True, do_normalize=False
81
+ )
82
+
83
+ arch = hf_config.architectures[0]
84
+ if arch.endswith("ForSequenceClassification"):
85
+ hf_model = convert_classification(base_model_name, hf_config, downstream_dict)
86
+ elif arch.endswith("ForAudioFrameClassification"):
87
+ hf_model = convert_diarization(base_model_name, hf_config, downstream_dict)
88
+ elif arch.endswith("ForXVector"):
89
+ hf_model = convert_xvector(base_model_name, hf_config, downstream_dict)
90
+ else:
91
+ raise NotImplementedError(f"S3PRL weights conversion is not supported for {arch}")
92
+
93
+ if hf_config.use_weighted_layer_sum:
94
+ hf_model.layer_weights.data = checkpoint["Featurizer"]["weights"]
95
+
96
+ hf_feature_extractor.save_pretrained(model_dump_path)
97
+ hf_model.save_pretrained(model_dump_path)
98
+
99
+
100
+ if __name__ == "__main__":
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument(
103
+ "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model."
104
+ )
105
+ parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.")
106
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.")
107
+ parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.")
108
+ args = parser.parse_args()
109
+ convert_s3prl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert UniSpeechSat checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import fairseq
20
+ import torch
21
+
22
+ from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging
23
+
24
+
25
+ logging.set_verbosity_info()
26
+ logger = logging.get_logger(__name__)
27
+
28
+ MAPPING = {
29
+ "post_extract_proj": "feature_projection.projection",
30
+ "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
31
+ "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
32
+ "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
33
+ "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
34
+ "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
35
+ "self_attn_layer_norm": "encoder.layers.*.layer_norm",
36
+ "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
37
+ "fc2": "encoder.layers.*.feed_forward.output_dense",
38
+ "final_layer_norm": "encoder.layers.*.final_layer_norm",
39
+ "encoder.layer_norm": "encoder.layer_norm",
40
+ "encoder.layer_norm_for_extract": "layer_norm_for_extract",
41
+ "w2v_model.layer_norm": "feature_projection.layer_norm",
42
+ "quantizer.weight_proj": "quantizer.weight_proj",
43
+ "quantizer.vars": "quantizer.codevectors",
44
+ "project_q": "project_q",
45
+ "final_proj": "project_hid",
46
+ "w2v_encoder.proj": "lm_head",
47
+ "label_embs_concat": "label_embeddings_concat",
48
+ "mask_emb": "masked_spec_embed",
49
+ "spk_proj": "speaker_proj",
50
+ }
51
+ TOP_LEVEL_KEYS = [
52
+ "lm_head",
53
+ "quantizer.weight_proj",
54
+ "quantizer.codevectors",
55
+ "project_q",
56
+ "project_hid",
57
+ "label_embeddings_concat",
58
+ "speaker_proj",
59
+ "layer_norm_for_extract",
60
+ ]
61
+
62
+
63
+ def set_recursively(hf_pointer, key, value, full_name, weight_type):
64
+ for attribute in key.split("."):
65
+ hf_pointer = getattr(hf_pointer, attribute)
66
+
67
+ if weight_type is not None:
68
+ hf_shape = getattr(hf_pointer, weight_type).shape
69
+ else:
70
+ hf_shape = hf_pointer.shape
71
+
72
+ if hf_shape != value.shape:
73
+ raise ValueError(
74
+ f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
75
+ f" {value.shape} for {full_name}"
76
+ )
77
+
78
+ if weight_type == "weight":
79
+ hf_pointer.weight.data = value
80
+ elif weight_type == "weight_g":
81
+ hf_pointer.weight_g.data = value
82
+ elif weight_type == "weight_v":
83
+ hf_pointer.weight_v.data = value
84
+ elif weight_type == "bias":
85
+ hf_pointer.bias.data = value
86
+ else:
87
+ hf_pointer.data = value
88
+
89
+ logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.")
90
+
91
+
92
+ def recursively_load_weights(fairseq_model, hf_model):
93
+ unused_weights = []
94
+ fairseq_dict = fairseq_model.state_dict()
95
+
96
+ feature_extractor = hf_model.unispeech_sat.feature_extractor
97
+
98
+ for name, value in fairseq_dict.items():
99
+ is_used = False
100
+ if "conv_layers" in name:
101
+ load_conv_layer(
102
+ name,
103
+ value,
104
+ feature_extractor,
105
+ unused_weights,
106
+ hf_model.config.feat_extract_norm == "group",
107
+ )
108
+ is_used = True
109
+ else:
110
+ for key, mapped_key in MAPPING.items():
111
+ mapped_key = "unispeech_sat." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
112
+ if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
113
+ if "layer_norm_for_extract" in name and (".".join(name.split(".")[:-1]) != key):
114
+ # special case since naming is very similar
115
+ continue
116
+ is_used = True
117
+ if "*" in mapped_key:
118
+ layer_index = name.split(key)[0].split(".")[-2]
119
+ mapped_key = mapped_key.replace("*", layer_index)
120
+ if "weight_g" in name:
121
+ weight_type = "weight_g"
122
+ elif "weight_v" in name:
123
+ weight_type = "weight_v"
124
+ elif "bias" in name:
125
+ weight_type = "bias"
126
+ elif "weight" in name:
127
+ # TODO: don't match quantizer.weight_proj
128
+ weight_type = "weight"
129
+ else:
130
+ weight_type = None
131
+ set_recursively(hf_model, mapped_key, value, name, weight_type)
132
+ continue
133
+ if not is_used:
134
+ unused_weights.append(name)
135
+
136
+ logger.warning(f"Unused weights: {unused_weights}")
137
+
138
+
139
+ def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm):
140
+ name = full_name.split("conv_layers.")[-1]
141
+ items = name.split(".")
142
+ layer_id = int(items[0])
143
+ type_id = int(items[1])
144
+
145
+ if type_id == 0:
146
+ if "bias" in name:
147
+ if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
148
+ raise ValueError(
149
+ f"{full_name} has size {value.shape}, but"
150
+ f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
151
+ )
152
+ feature_extractor.conv_layers[layer_id].conv.bias.data = value
153
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
154
+ elif "weight" in name:
155
+ if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
156
+ raise ValueError(
157
+ f"{full_name} has size {value.shape}, but"
158
+ f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
159
+ )
160
+ feature_extractor.conv_layers[layer_id].conv.weight.data = value
161
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
162
+ elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
163
+ if "bias" in name:
164
+ if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
165
+ raise ValueError(
166
+ f"{full_name} has size {value.shape}, but"
167
+ f" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found."
168
+ )
169
+ feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value
170
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
171
+ elif "weight" in name:
172
+ if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
173
+ raise ValueError(
174
+ f"{full_name} has size {value.shape}, but"
175
+ f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
176
+ )
177
+ feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value
178
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
179
+ else:
180
+ unused_weights.append(full_name)
181
+
182
+
183
+ @torch.no_grad()
184
+ def convert_unispeech_sat_checkpoint(
185
+ checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True
186
+ ):
187
+ """
188
+ Copy/paste/tweak model's weights to transformers design.
189
+ """
190
+ if config_path is not None:
191
+ config = UniSpeechSatConfig.from_pretrained(config_path)
192
+ else:
193
+ config = UniSpeechSatConfig()
194
+
195
+ dict_path = ""
196
+
197
+ if is_finetuned:
198
+ hf_wav2vec = UniSpeechSatForCTC(config)
199
+ else:
200
+ hf_wav2vec = UniSpeechSatForPreTraining(config)
201
+
202
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
203
+ [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/")[:-1])}
204
+ )
205
+ model = model[0].eval()
206
+
207
+ recursively_load_weights(model, hf_wav2vec)
208
+
209
+ hf_wav2vec.save_pretrained(pytorch_dump_folder_path)
210
+
211
+
212
+ if __name__ == "__main__":
213
+ parser = argparse.ArgumentParser()
214
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
215
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
216
+ parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
217
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
218
+ parser.add_argument(
219
+ "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
220
+ )
221
+ args = parser.parse_args()
222
+ convert_unispeech_sat_checkpoint(
223
+ args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
224
+ )
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/unispeech_sat/modeling_unispeech_sat.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_univnet import *
22
+ from .feature_extraction_univnet import *
23
+ from .modeling_univnet import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/configuration_univnet.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
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
+ """UnivNetModel model configuration"""
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class UnivNetConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`UnivNetModel`]. It is used to instantiate a
26
+ UnivNet vocoder model according to the specified arguments, defining the model architecture. Instantiating a
27
+ configuration with the defaults will yield a similar configuration to that of the UnivNet
28
+ [dg845/univnet-dev](https://huggingface.co/dg845/univnet-dev) architecture, which corresponds to the 'c32'
29
+ architecture in [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/master/config/default_c32.yaml).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ model_in_channels (`int`, *optional*, defaults to 64):
36
+ The number of input channels for the UnivNet residual network. This should correspond to
37
+ `noise_sequence.shape[1]` and the value used in the [`UnivNetFeatureExtractor`] class.
38
+ model_hidden_channels (`int`, *optional*, defaults to 32):
39
+ The number of hidden channels of each residual block in the UnivNet residual network.
40
+ num_mel_bins (`int`, *optional*, defaults to 100):
41
+ The number of frequency bins in the conditioning log-mel spectrogram. This should correspond to the value
42
+ used in the [`UnivNetFeatureExtractor`] class.
43
+ resblock_kernel_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[3, 3, 3]`):
44
+ A tuple of integers defining the kernel sizes of the 1D convolutional layers in the UnivNet residual
45
+ network. The length of `resblock_kernel_sizes` defines the number of resnet blocks and should match that of
46
+ `resblock_stride_sizes` and `resblock_dilation_sizes`.
47
+ resblock_stride_sizes (`Tuple[int]` or `List[int]`, *optional*, defaults to `[8, 8, 4]`):
48
+ A tuple of integers defining the stride sizes of the 1D convolutional layers in the UnivNet residual
49
+ network. The length of `resblock_stride_sizes` should match that of `resblock_kernel_sizes` and
50
+ `resblock_dilation_sizes`.
51
+ resblock_dilation_sizes (`Tuple[Tuple[int]]` or `List[List[int]]`, *optional*, defaults to `[[1, 3, 9, 27], [1, 3, 9, 27], [1, 3, 9, 27]]`):
52
+ A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
53
+ UnivNet residual network. The length of `resblock_dilation_sizes` should match that of
54
+ `resblock_kernel_sizes` and `resblock_stride_sizes`. The length of each nested list in
55
+ `resblock_dilation_sizes` defines the number of convolutional layers per resnet block.
56
+ kernel_predictor_num_blocks (`int`, *optional*, defaults to 3):
57
+ The number of residual blocks in the kernel predictor network, which calculates the kernel and bias for
58
+ each location variable convolution layer in the UnivNet residual network.
59
+ kernel_predictor_hidden_channels (`int`, *optional*, defaults to 64):
60
+ The number of hidden channels for each residual block in the kernel predictor network.
61
+ kernel_predictor_conv_size (`int`, *optional*, defaults to 3):
62
+ The kernel size of each 1D convolutional layer in the kernel predictor network.
63
+ kernel_predictor_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout probability for each residual block in the kernel predictor network.
65
+ initializer_range (`float`, *optional*, defaults to 0.01):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ leaky_relu_slope (`float`, *optional*, defaults to 0.2):
68
+ The angle of the negative slope used by the leaky ReLU activation.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ >>> from transformers import UnivNetModel, UnivNetConfig
74
+
75
+ >>> # Initializing a Tortoise TTS style configuration
76
+ >>> configuration = UnivNetConfig()
77
+
78
+ >>> # Initializing a model (with random weights) from the Tortoise TTS style configuration
79
+ >>> model = UnivNetModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```
84
+ """
85
+
86
+ model_type = "univnet"
87
+
88
+ def __init__(
89
+ self,
90
+ model_in_channels=64,
91
+ model_hidden_channels=32,
92
+ num_mel_bins=100,
93
+ resblock_kernel_sizes=[3, 3, 3],
94
+ resblock_stride_sizes=[8, 8, 4],
95
+ resblock_dilation_sizes=[[1, 3, 9, 27], [1, 3, 9, 27], [1, 3, 9, 27]],
96
+ kernel_predictor_num_blocks=3,
97
+ kernel_predictor_hidden_channels=64,
98
+ kernel_predictor_conv_size=3,
99
+ kernel_predictor_dropout=0.0,
100
+ initializer_range=0.01,
101
+ leaky_relu_slope=0.2,
102
+ **kwargs,
103
+ ):
104
+ if not (len(resblock_kernel_sizes) == len(resblock_stride_sizes) == len(resblock_dilation_sizes)):
105
+ raise ValueError(
106
+ "`resblock_kernel_sizes`, `resblock_stride_sizes`, and `resblock_dilation_sizes` must all have the"
107
+ " same length (which will be the number of resnet blocks in the model)."
108
+ )
109
+
110
+ self.model_in_channels = model_in_channels
111
+ self.model_hidden_channels = model_hidden_channels
112
+ self.num_mel_bins = num_mel_bins
113
+ self.resblock_kernel_sizes = resblock_kernel_sizes
114
+ self.resblock_stride_sizes = resblock_stride_sizes
115
+ self.resblock_dilation_sizes = resblock_dilation_sizes
116
+ self.kernel_predictor_num_blocks = kernel_predictor_num_blocks
117
+ self.kernel_predictor_hidden_channels = kernel_predictor_hidden_channels
118
+ self.kernel_predictor_conv_size = kernel_predictor_conv_size
119
+ self.kernel_predictor_dropout = kernel_predictor_dropout
120
+ self.initializer_range = initializer_range
121
+ self.leaky_relu_slope = leaky_relu_slope
122
+ super().__init__(**kwargs)
123
+
124
+
125
+ __all__ = ["UnivNetConfig"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/convert_univnet.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
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
+ import argparse
16
+
17
+ import torch
18
+
19
+ from transformers import UnivNetConfig, UnivNetModel, logging
20
+
21
+
22
+ logging.set_verbosity_info()
23
+ logger = logging.get_logger("transformers.models.univnet")
24
+
25
+
26
+ def get_kernel_predictor_key_mapping(config: UnivNetConfig, old_prefix: str = "", new_prefix: str = ""):
27
+ mapping = {}
28
+ # Initial conv layer
29
+ mapping[f"{old_prefix}.input_conv.0.weight_g"] = f"{new_prefix}.input_conv.weight_g"
30
+ mapping[f"{old_prefix}.input_conv.0.weight_v"] = f"{new_prefix}.input_conv.weight_v"
31
+ mapping[f"{old_prefix}.input_conv.0.bias"] = f"{new_prefix}.input_conv.bias"
32
+
33
+ # Kernel predictor resnet blocks
34
+ for i in range(config.kernel_predictor_num_blocks):
35
+ mapping[f"{old_prefix}.residual_convs.{i}.1.weight_g"] = f"{new_prefix}.resblocks.{i}.conv1.weight_g"
36
+ mapping[f"{old_prefix}.residual_convs.{i}.1.weight_v"] = f"{new_prefix}.resblocks.{i}.conv1.weight_v"
37
+ mapping[f"{old_prefix}.residual_convs.{i}.1.bias"] = f"{new_prefix}.resblocks.{i}.conv1.bias"
38
+
39
+ mapping[f"{old_prefix}.residual_convs.{i}.3.weight_g"] = f"{new_prefix}.resblocks.{i}.conv2.weight_g"
40
+ mapping[f"{old_prefix}.residual_convs.{i}.3.weight_v"] = f"{new_prefix}.resblocks.{i}.conv2.weight_v"
41
+ mapping[f"{old_prefix}.residual_convs.{i}.3.bias"] = f"{new_prefix}.resblocks.{i}.conv2.bias"
42
+
43
+ # Kernel output conv
44
+ mapping[f"{old_prefix}.kernel_conv.weight_g"] = f"{new_prefix}.kernel_conv.weight_g"
45
+ mapping[f"{old_prefix}.kernel_conv.weight_v"] = f"{new_prefix}.kernel_conv.weight_v"
46
+ mapping[f"{old_prefix}.kernel_conv.bias"] = f"{new_prefix}.kernel_conv.bias"
47
+
48
+ # Bias output conv
49
+ mapping[f"{old_prefix}.bias_conv.weight_g"] = f"{new_prefix}.bias_conv.weight_g"
50
+ mapping[f"{old_prefix}.bias_conv.weight_v"] = f"{new_prefix}.bias_conv.weight_v"
51
+ mapping[f"{old_prefix}.bias_conv.bias"] = f"{new_prefix}.bias_conv.bias"
52
+
53
+ return mapping
54
+
55
+
56
+ def get_key_mapping(config: UnivNetConfig):
57
+ mapping = {}
58
+
59
+ # NOTE: inital conv layer keys are the same
60
+
61
+ # LVC Residual blocks
62
+ for i in range(len(config.resblock_stride_sizes)):
63
+ # LVCBlock initial convt layer
64
+ mapping[f"res_stack.{i}.convt_pre.1.weight_g"] = f"resblocks.{i}.convt_pre.weight_g"
65
+ mapping[f"res_stack.{i}.convt_pre.1.weight_v"] = f"resblocks.{i}.convt_pre.weight_v"
66
+ mapping[f"res_stack.{i}.convt_pre.1.bias"] = f"resblocks.{i}.convt_pre.bias"
67
+
68
+ # Kernel predictor
69
+ kernel_predictor_mapping = get_kernel_predictor_key_mapping(
70
+ config, old_prefix=f"res_stack.{i}.kernel_predictor", new_prefix=f"resblocks.{i}.kernel_predictor"
71
+ )
72
+ mapping.update(kernel_predictor_mapping)
73
+
74
+ # LVC Residual blocks
75
+ for j in range(len(config.resblock_dilation_sizes[i])):
76
+ mapping[f"res_stack.{i}.conv_blocks.{j}.1.weight_g"] = f"resblocks.{i}.resblocks.{j}.conv.weight_g"
77
+ mapping[f"res_stack.{i}.conv_blocks.{j}.1.weight_v"] = f"resblocks.{i}.resblocks.{j}.conv.weight_v"
78
+ mapping[f"res_stack.{i}.conv_blocks.{j}.1.bias"] = f"resblocks.{i}.resblocks.{j}.conv.bias"
79
+
80
+ # Output conv layer
81
+ mapping["conv_post.1.weight_g"] = "conv_post.weight_g"
82
+ mapping["conv_post.1.weight_v"] = "conv_post.weight_v"
83
+ mapping["conv_post.1.bias"] = "conv_post.bias"
84
+
85
+ return mapping
86
+
87
+
88
+ def rename_state_dict(state_dict, keys_to_modify, keys_to_remove):
89
+ model_state_dict = {}
90
+ for key, value in state_dict.items():
91
+ if key in keys_to_remove:
92
+ continue
93
+
94
+ if key in keys_to_modify:
95
+ new_key = keys_to_modify[key]
96
+ model_state_dict[new_key] = value
97
+ else:
98
+ model_state_dict[key] = value
99
+ return model_state_dict
100
+
101
+
102
+ def convert_univnet_checkpoint(
103
+ checkpoint_path,
104
+ pytorch_dump_folder_path,
105
+ config_path=None,
106
+ repo_id=None,
107
+ safe_serialization=False,
108
+ ):
109
+ model_state_dict_base = torch.load(checkpoint_path, map_location="cpu")
110
+ # Get the generator's state dict
111
+ state_dict = model_state_dict_base["model_g"]
112
+
113
+ if config_path is not None:
114
+ config = UnivNetConfig.from_pretrained(config_path)
115
+ else:
116
+ config = UnivNetConfig()
117
+
118
+ keys_to_modify = get_key_mapping(config)
119
+ keys_to_remove = set()
120
+ hf_state_dict = rename_state_dict(state_dict, keys_to_modify, keys_to_remove)
121
+
122
+ model = UnivNetModel(config)
123
+ # Apply weight norm since the original checkpoint has weight norm applied
124
+ model.apply_weight_norm()
125
+ model.load_state_dict(hf_state_dict)
126
+ # Remove weight norm in preparation for inference
127
+ model.remove_weight_norm()
128
+
129
+ model.save_pretrained(pytorch_dump_folder_path, safe_serialization=safe_serialization)
130
+
131
+ if repo_id:
132
+ print("Pushing to the hub...")
133
+ model.push_to_hub(repo_id)
134
+
135
+
136
+ def main():
137
+ parser = argparse.ArgumentParser()
138
+ parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint")
139
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
140
+ parser.add_argument(
141
+ "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
142
+ )
143
+ parser.add_argument(
144
+ "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
145
+ )
146
+ parser.add_argument(
147
+ "--safe_serialization", action="store_true", help="Whether to save the model using `safetensors`."
148
+ )
149
+
150
+ args = parser.parse_args()
151
+
152
+ convert_univnet_checkpoint(
153
+ args.checkpoint_path,
154
+ args.pytorch_dump_folder_path,
155
+ args.config_path,
156
+ args.push_to_hub,
157
+ args.safe_serialization,
158
+ )
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/feature_extraction_univnet.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
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
+ """Feature extractor class for UnivNetModel."""
15
+
16
+ from typing import Any, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+
20
+ from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
21
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
22
+ from ...feature_extraction_utils import BatchFeature
23
+ from ...utils import PaddingStrategy, TensorType, logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class UnivNetFeatureExtractor(SequenceFeatureExtractor):
30
+ r"""
31
+ Constructs a UnivNet feature extractor.
32
+
33
+ This class extracts log-mel-filter bank features from raw speech using the short time Fourier Transform (STFT). The
34
+ STFT implementation follows that of TacoTron 2 and Hifi-GAN.
35
+
36
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
37
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
38
+
39
+ Args:
40
+ feature_size (`int`, *optional*, defaults to 1):
41
+ The feature dimension of the extracted features.
42
+ sampling_rate (`int`, *optional*, defaults to 24000):
43
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
44
+ padding_value (`float`, *optional*, defaults to 0.0):
45
+ The value to pad with when applying the padding strategy defined by the `padding` argument to
46
+ [`UnivNetFeatureExtractor.__call__`]. Should correspond to audio silence. The `pad_end` argument to
47
+ `__call__` will also use this padding value.
48
+ do_normalize (`bool`, *optional*, defaults to `False`):
49
+ Whether to perform Tacotron 2 normalization on the input. Normalizing can help to significantly improve the
50
+ performance for some models.
51
+ num_mel_bins (`int`, *optional*, defaults to 100):
52
+ The number of mel-frequency bins in the extracted spectrogram features. This should match
53
+ `UnivNetModel.config.num_mel_bins`.
54
+ hop_length (`int`, *optional*, defaults to 256):
55
+ The direct number of samples between sliding windows. Otherwise referred to as "shift" in many papers. Note
56
+ that this is different from other audio feature extractors such as [`SpeechT5FeatureExtractor`] which take
57
+ the `hop_length` in ms.
58
+ win_length (`int`, *optional*, defaults to 1024):
59
+ The direct number of samples for each sliding window. Note that this is different from other audio feature
60
+ extractors such as [`SpeechT5FeatureExtractor`] which take the `win_length` in ms.
61
+ win_function (`str`, *optional*, defaults to `"hann_window"`):
62
+ Name for the window function used for windowing, must be accessible via `torch.{win_function}`
63
+ filter_length (`int`, *optional*, defaults to 1024):
64
+ The number of FFT components to use. If `None`, this is determined using
65
+ `transformers.audio_utils.optimal_fft_length`.
66
+ max_length_s (`int`, *optional*, defaults to 10):
67
+ The maximum input lenght of the model in seconds. This is used to pad the audio.
68
+ fmin (`float`, *optional*, defaults to 0.0):
69
+ Minimum mel frequency in Hz.
70
+ fmax (`float`, *optional*):
71
+ Maximum mel frequency in Hz. If not set, defaults to `sampling_rate / 2`.
72
+ mel_floor (`float`, *optional*, defaults to 1e-09):
73
+ Minimum value of mel frequency banks. Note that the way [`UnivNetFeatureExtractor`] uses `mel_floor` is
74
+ different than in [`transformers.audio_utils.spectrogram`].
75
+ center (`bool`, *optional*, defaults to `False`):
76
+ Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `False`, frame
77
+ `t` will start at time `t * hop_length`.
78
+ compression_factor (`float`, *optional*, defaults to 1.0):
79
+ The multiplicative compression factor for dynamic range compression during spectral normalization.
80
+ compression_clip_val (`float`, *optional*, defaults to 1e-05):
81
+ The clip value applied to the waveform before applying dynamic range compression during spectral
82
+ normalization.
83
+ normalize_min (`float`, *optional*, defaults to -11.512925148010254):
84
+ The min value used for Tacotron 2-style linear normalization. The default is the original value from the
85
+ Tacotron 2 implementation.
86
+ normalize_max (`float`, *optional*, defaults to 2.3143386840820312):
87
+ The max value used for Tacotron 2-style linear normalization. The default is the original value from the
88
+ Tacotron 2 implementation.
89
+ model_in_channels (`int`, *optional*, defaults to 64):
90
+ The number of input channels to the [`UnivNetModel`] model. This should match
91
+ `UnivNetModel.config.model_in_channels`.
92
+ pad_end_length (`int`, *optional*, defaults to 10):
93
+ If padding the end of each waveform, the number of spectrogram frames worth of samples to append. The
94
+ number of appended samples will be `pad_end_length * hop_length`.
95
+ return_attention_mask (`bool`, *optional*, defaults to `True`):
96
+ Whether or not [`~UnivNetFeatureExtractor.__call__`] should return `attention_mask`.
97
+ """
98
+
99
+ model_input_names = ["input_features", "noise_sequence", "padding_mask"]
100
+
101
+ def __init__(
102
+ self,
103
+ feature_size: int = 1,
104
+ sampling_rate: int = 24000,
105
+ padding_value: float = 0.0,
106
+ do_normalize: bool = False,
107
+ num_mel_bins: int = 100,
108
+ hop_length: int = 256,
109
+ win_length: int = 1024,
110
+ win_function: str = "hann_window",
111
+ filter_length: Optional[int] = 1024,
112
+ max_length_s: int = 10,
113
+ fmin: float = 0.0,
114
+ fmax: Optional[float] = None,
115
+ mel_floor: float = 1e-9,
116
+ center: bool = False,
117
+ compression_factor: float = 1.0,
118
+ compression_clip_val: float = 1e-5,
119
+ normalize_min: float = -11.512925148010254,
120
+ normalize_max: float = 2.3143386840820312,
121
+ model_in_channels: int = 64,
122
+ pad_end_length: int = 10,
123
+ return_attention_mask=True,
124
+ **kwargs,
125
+ ):
126
+ super().__init__(
127
+ feature_size=feature_size,
128
+ sampling_rate=sampling_rate,
129
+ padding_value=padding_value,
130
+ return_attention_mask=return_attention_mask,
131
+ **kwargs,
132
+ )
133
+
134
+ self.do_normalize = do_normalize
135
+
136
+ self.num_mel_bins = num_mel_bins
137
+ self.hop_length = hop_length
138
+ self.win_length = win_length
139
+ self.win_function = win_function
140
+ self.filter_length = filter_length
141
+ self.fmin = fmin
142
+ if fmax is None:
143
+ # Follows the librosa.filters.mel implementation
144
+ fmax = float(sampling_rate) / 2
145
+ self.fmax = fmax
146
+ self.mel_floor = mel_floor
147
+
148
+ self.max_length_s = max_length_s
149
+ self.num_max_samples = max_length_s * sampling_rate
150
+
151
+ if self.filter_length is None:
152
+ self.n_fft = optimal_fft_length(self.win_length)
153
+ else:
154
+ self.n_fft = self.filter_length
155
+ self.n_freqs = (self.n_fft // 2) + 1
156
+
157
+ self.window = window_function(window_length=self.win_length, name=self.win_function, periodic=True)
158
+
159
+ self.mel_filters = mel_filter_bank(
160
+ num_frequency_bins=self.n_freqs,
161
+ num_mel_filters=self.num_mel_bins,
162
+ min_frequency=self.fmin,
163
+ max_frequency=self.fmax,
164
+ sampling_rate=self.sampling_rate,
165
+ norm="slaney",
166
+ mel_scale="slaney",
167
+ )
168
+
169
+ self.center = center
170
+ self.compression_factor = compression_factor
171
+ self.compression_clip_val = compression_clip_val
172
+ self.normalize_min = normalize_min
173
+ self.normalize_max = normalize_max
174
+ self.model_in_channels = model_in_channels
175
+ self.pad_end_length = pad_end_length
176
+
177
+ def normalize(self, spectrogram):
178
+ return 2 * ((spectrogram - self.normalize_min) / (self.normalize_max - self.normalize_min)) - 1
179
+
180
+ def denormalize(self, spectrogram):
181
+ return self.normalize_min + (self.normalize_max - self.normalize_min) * ((spectrogram + 1) / 2)
182
+
183
+ def mel_spectrogram(self, waveform: np.ndarray) -> np.ndarray:
184
+ """
185
+ Calculates log MEL spectrograms from a batch of waveforms. Note that the input waveform(s) will be padded by
186
+ `int(self.n_fft - self.hop_length) / 2` on both sides using the `reflect` padding mode.
187
+
188
+ Args:
189
+ waveform (`np.ndarray` of shape `(length,)`):
190
+ The input waveform. This must be a single real-valued, mono waveform.
191
+
192
+ Returns:
193
+ `numpy.ndarray`: Array containing a log-mel spectrogram of shape `(num_frames, num_mel_bins)`.
194
+ """
195
+ # Do custom padding based on the official MelGAN and Hifi-GAN implementations
196
+ # See https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/utils/stft.py#L84-L86
197
+ waveform = np.pad(
198
+ waveform,
199
+ (int((self.n_fft - self.hop_length) / 2), int((self.n_fft - self.hop_length) / 2)),
200
+ mode="reflect",
201
+ )
202
+
203
+ # Get the complex spectrogram.
204
+ # Note: waveform must be unbatched currently due to the implementation of spectrogram(...).
205
+ complex_spectrogram = spectrogram(
206
+ waveform,
207
+ window=self.window,
208
+ frame_length=self.n_fft,
209
+ hop_length=self.hop_length,
210
+ fft_length=self.n_fft,
211
+ power=None,
212
+ center=self.center,
213
+ mel_filters=None,
214
+ mel_floor=None,
215
+ )
216
+
217
+ # Apply the MEL filter bank and MEL floor manually since UnivNet uses a slightly different implementation
218
+ amplitude_spectrogram = np.sqrt(
219
+ np.real(complex_spectrogram) ** 2 + np.imag(complex_spectrogram) ** 2 + self.mel_floor
220
+ )
221
+ mel_spectrogram = np.matmul(self.mel_filters.T, amplitude_spectrogram)
222
+
223
+ # Perform spectral normalization to get the log mel spectrogram.
224
+ log_mel_spectrogram = np.log(
225
+ np.clip(mel_spectrogram, a_min=self.compression_clip_val, a_max=None) * self.compression_factor
226
+ )
227
+
228
+ # Return spectrogram with num_mel_bins last
229
+ return log_mel_spectrogram.T
230
+
231
+ def generate_noise(
232
+ self,
233
+ noise_length: int,
234
+ generator: Optional[np.random.Generator] = None,
235
+ ) -> np.ndarray:
236
+ """
237
+ Generates a random noise sequence of standard Gaussian noise for use in the `noise_sequence` argument of
238
+ [`UnivNetModel.forward`].
239
+
240
+ Args:
241
+ spectrogram_length (`int`):
242
+ The length (dim 0) of the generated noise.
243
+ model_in_channels (`int`, *optional*, defaults to `None`):
244
+ The number of features (dim 1) of the generated noise. This should correspond to the
245
+ `model_in_channels` of the [`UnivNetGan`] model. If not set, this will default to
246
+ `self.config.model_in_channels`.
247
+ generator (`numpy.random.Generator`, *optional*, defaults to `None`)
248
+ An optional `numpy.random.Generator` random number generator to control noise generation. If not set, a
249
+ new generator with fresh entropy will be created.
250
+
251
+ Returns:
252
+ `numpy.ndarray`: Array containing random standard Gaussian noise of shape `(noise_length,
253
+ model_in_channels)`.
254
+ """
255
+ if generator is None:
256
+ generator = np.random.default_rng()
257
+
258
+ noise_shape = (noise_length, self.model_in_channels)
259
+ noise = generator.standard_normal(noise_shape, dtype=np.float32)
260
+
261
+ return noise
262
+
263
+ def batch_decode(self, waveforms, waveform_lengths=None) -> List[np.ndarray]:
264
+ r"""
265
+ Removes padding from generated audio after running [`UnivNetModel.forward`]. This returns a ragged list of 1D
266
+ audio waveform arrays and not a single tensor/array because in general the waveforms will have different
267
+ lengths after removing padding.
268
+
269
+ Args:
270
+ waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
271
+ The batched output waveforms from the [`UnivNetModel`].
272
+ waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`, *optional*):
273
+ The batched lengths of each waveform before padding.
274
+
275
+ Returns:
276
+ `List[np.ndarray]`: A ragged list of 1D waveform arrays with padding removed.
277
+ """
278
+ # Collapse the batched waveform tensor to a list of 1D audio waveforms
279
+ waveforms = [waveform.detach().clone().cpu().numpy() for waveform in waveforms]
280
+
281
+ if waveform_lengths is not None:
282
+ waveforms = [waveform[: waveform_lengths[i]] for i, waveform in enumerate(waveforms)]
283
+
284
+ return waveforms
285
+
286
+ def __call__(
287
+ self,
288
+ raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
289
+ sampling_rate: Optional[int] = None,
290
+ padding: Union[bool, str, PaddingStrategy] = True,
291
+ max_length: Optional[int] = None,
292
+ truncation: bool = True,
293
+ pad_to_multiple_of: Optional[int] = None,
294
+ return_noise: bool = True,
295
+ generator: Optional[np.random.Generator] = None,
296
+ pad_end: bool = False,
297
+ pad_length: Optional[int] = None,
298
+ do_normalize: Optional[str] = None,
299
+ return_attention_mask: Optional[bool] = None,
300
+ return_tensors: Optional[Union[str, TensorType]] = None,
301
+ ) -> BatchFeature:
302
+ """
303
+ Main method to featurize and prepare for the model one or several sequence(s).
304
+
305
+ Args:
306
+ raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
307
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
308
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
309
+ stereo, i.e. single float per timestep.
310
+ sampling_rate (`int`, *optional*):
311
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
312
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
313
+ pipeline.
314
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
315
+ Select a strategy to pad the input `raw_speech` waveforms (according to the model's padding side and
316
+ padding index) among:
317
+
318
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
319
+ sequence if provided).
320
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
321
+ acceptable input length for the model if that argument is not provided.
322
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
323
+ lengths).
324
+
325
+ If `pad_end = True`, that padding will occur before the `padding` strategy is applied.
326
+ max_length (`int`, *optional*):
327
+ Maximum length of the returned list and optionally padding length (see above).
328
+ truncation (`bool`, *optional*, defaults to `True`):
329
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
330
+ pad_to_multiple_of (`int`, *optional*):
331
+ If set will pad the sequence to a multiple of the provided value.
332
+
333
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
334
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
335
+ return_noise (`bool`, *optional*, defaults to `True`):
336
+ Whether to generate and return a noise waveform for use in [`UnivNetModel.forward`].
337
+ generator (`numpy.random.Generator`, *optional*, defaults to `None`):
338
+ An optional `numpy.random.Generator` random number generator to use when generating noise.
339
+ pad_end (`bool`, *optional*, defaults to `False`):
340
+ Whether to pad the end of each waveform with silence. This can help reduce artifacts at the end of the
341
+ generated audio sample; see https://github.com/seungwonpark/melgan/issues/8 for more details. This
342
+ padding will be done before the padding strategy specified in `padding` is performed.
343
+ pad_length (`int`, *optional*, defaults to `None`):
344
+ If padding the end of each waveform, the length of the padding in spectrogram frames. If not set, this
345
+ will default to `self.config.pad_end_length`.
346
+ do_normalize (`bool`, *optional*):
347
+ Whether to perform Tacotron 2 normalization on the input. Normalizing can help to significantly improve
348
+ the performance for some models. If not set, this will default to `self.config.do_normalize`.
349
+ return_attention_mask (`bool`, *optional*):
350
+ Whether to return the attention mask. If left to the default, will return the attention mask according
351
+ to the specific feature_extractor's default.
352
+
353
+ [What are attention masks?](../glossary#attention-mask)
354
+
355
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
356
+ If set, will return tensors instead of list of python integers. Acceptable values are:
357
+
358
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
359
+ - `'pt'`: Return PyTorch `torch.np.array` objects.
360
+ - `'np'`: Return Numpy `np.ndarray` objects.
361
+ """
362
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
363
+
364
+ if sampling_rate is not None:
365
+ if sampling_rate != self.sampling_rate:
366
+ raise ValueError(
367
+ f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
368
+ f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
369
+ f" was sampled with {self.sampling_rate} and not {sampling_rate}."
370
+ )
371
+ else:
372
+ logger.warning(
373
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
374
+ "Failing to do so can result in silent errors that might be hard to debug."
375
+ )
376
+
377
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
378
+ if is_batched_numpy and len(raw_speech.shape) > 2:
379
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
380
+ is_batched = is_batched_numpy or (
381
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
382
+ )
383
+
384
+ if is_batched:
385
+ raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
386
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
387
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
388
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
389
+ raw_speech = raw_speech.astype(np.float32)
390
+
391
+ # always return batch
392
+ if not is_batched:
393
+ raw_speech = [np.asarray(raw_speech, dtype=np.float32)]
394
+
395
+ # Pad end to reduce artifacts
396
+ if pad_end:
397
+ pad_length = pad_length if pad_length is not None else self.pad_end_length
398
+ raw_speech = [
399
+ np.pad(waveform, (0, pad_length * self.hop_length), constant_values=self.padding_value)
400
+ for waveform in raw_speech
401
+ ]
402
+
403
+ batched_speech = BatchFeature({"input_features": raw_speech})
404
+
405
+ padded_inputs = self.pad(
406
+ batched_speech,
407
+ padding=padding,
408
+ max_length=max_length if max_length is not None else self.num_max_samples,
409
+ truncation=truncation,
410
+ pad_to_multiple_of=pad_to_multiple_of,
411
+ return_attention_mask=return_attention_mask,
412
+ )
413
+
414
+ # make sure list is in array format
415
+ # input_features = padded_inputs.get("input_features").transpose(2, 0, 1)
416
+ input_features = padded_inputs.get("input_features")
417
+
418
+ mel_spectrograms = [self.mel_spectrogram(waveform) for waveform in input_features]
419
+
420
+ if isinstance(input_features[0], List):
421
+ batched_speech["input_features"] = [np.asarray(mel, dtype=np.float32) for mel in mel_spectrograms]
422
+ else:
423
+ batched_speech["input_features"] = [mel.astype(np.float32) for mel in mel_spectrograms]
424
+
425
+ # convert attention_mask to correct format
426
+ attention_mask = padded_inputs.get("attention_mask")
427
+ if attention_mask is not None:
428
+ batched_speech["padding_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
429
+
430
+ if return_noise:
431
+ noise = [
432
+ self.generate_noise(spectrogram.shape[0], generator)
433
+ for spectrogram in batched_speech["input_features"]
434
+ ]
435
+ batched_speech["noise_sequence"] = noise
436
+
437
+ if do_normalize:
438
+ batched_speech["input_features"] = [
439
+ self.normalize(spectrogram) for spectrogram in batched_speech["input_features"]
440
+ ]
441
+
442
+ if return_tensors is not None:
443
+ batched_speech = batched_speech.convert_to_tensors(return_tensors)
444
+
445
+ return batched_speech
446
+
447
+ def to_dict(self) -> Dict[str, Any]:
448
+ output = super().to_dict()
449
+
450
+ # Don't serialize these as they are derived from the other properties.
451
+ names = ["window", "mel_filters", "n_fft", "n_freqs", "num_max_samples"]
452
+ for name in names:
453
+ if name in output:
454
+ del output[name]
455
+
456
+ return output
457
+
458
+
459
+ __all__ = ["UnivNetFeatureExtractor"]
tasks/tasksmith-e0f68dd4420c/tests/source/src/transformers/models/univnet/modeling_univnet.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
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
+ """PyTorch UnivNetModel model."""
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+
23
+ from ...modeling_utils import ModelOutput, PreTrainedModel
24
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
25
+ from .configuration_univnet import UnivNetConfig
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ # General docstring
31
+ _CONFIG_FOR_DOC = "UnivNetConfig"
32
+
33
+ _CHECKPOINT_FOR_DOC = "dg845/univnet-dev"
34
+
35
+
36
+ @dataclass
37
+ class UnivNetModelOutput(ModelOutput):
38
+ """
39
+ Output class for the [`UnivNetModel`], which includes the generated audio waveforms and the original unpadded
40
+ lengths of those waveforms (so that the padding can be removed by [`UnivNetModel.batch_decode`]).
41
+
42
+ Args:
43
+ waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
44
+ Batched 1D (mono-channel) output audio waveforms.
45
+ waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`):
46
+ The batched length in samples of each unpadded waveform in `waveforms`.
47
+ """
48
+
49
+ waveforms: torch.FloatTensor = None
50
+ waveform_lengths: torch.FloatTensor = None
51
+
52
+
53
+ class UnivNetKernelPredictorResidualBlock(nn.Module):
54
+ """
55
+ Implementation of the residual block for the kernel predictor network inside each location variable convolution
56
+ block (LVCBlock).
57
+
58
+ Parameters:
59
+ config: (`UnivNetConfig`):
60
+ Config for the `UnivNetModel` model.
61
+ """
62
+
63
+ def __init__(
64
+ self,
65
+ config: UnivNetConfig,
66
+ ):
67
+ super().__init__()
68
+ self.channels = config.model_in_channels
69
+ self.kernel_size = config.kernel_predictor_conv_size
70
+ self.dropout_prob = config.kernel_predictor_dropout
71
+ self.leaky_relu_slope = config.leaky_relu_slope
72
+
73
+ padding = (self.kernel_size - 1) // 2
74
+
75
+ self.dropout = nn.Dropout(self.dropout_prob)
76
+ self.conv1 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
77
+ self.conv2 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
78
+
79
+ def forward(self, hidden_states: torch.FloatTensor):
80
+ # hidden_states should have shape (batch_size, channels, seq_length)
81
+ residual = hidden_states
82
+ hidden_states = self.dropout(hidden_states)
83
+ hidden_states = self.conv1(hidden_states)
84
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
85
+ hidden_states = self.conv2(hidden_states)
86
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
87
+ return hidden_states + residual
88
+
89
+ def apply_weight_norm(self):
90
+ weight_norm = nn.utils.weight_norm
91
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
92
+ weight_norm = nn.utils.parametrizations.weight_norm
93
+
94
+ weight_norm(self.conv1)
95
+ weight_norm(self.conv2)
96
+
97
+ def remove_weight_norm(self):
98
+ nn.utils.remove_weight_norm(self.conv1)
99
+ nn.utils.remove_weight_norm(self.conv2)
100
+
101
+
102
+ class UnivNetKernelPredictor(nn.Module):
103
+ """
104
+ Implementation of the kernel predictor network which supplies the kernel and bias for the location variable
105
+ convolutional layers (LVCs) in each UnivNet LVCBlock.
106
+
107
+ Based on the KernelPredictor implementation in
108
+ [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L7).
109
+
110
+ Parameters:
111
+ config: (`UnivNetConfig`):
112
+ Config for the `UnivNetModel` model.
113
+ conv_kernel_size (`int`, *optional*, defaults to 3):
114
+ The kernel size for the location variable convolutional layer kernels (convolutional weight tensor).
115
+ conv_layers (`int`, *optional*, defaults to 4):
116
+ The number of location variable convolutional layers to output kernels and biases for.
117
+ """
118
+
119
+ def __init__(
120
+ self,
121
+ config: UnivNetConfig,
122
+ conv_kernel_size: int = 3,
123
+ conv_layers: int = 4,
124
+ ):
125
+ super().__init__()
126
+
127
+ self.conv_in_channels = config.model_hidden_channels
128
+ self.conv_out_channels = 2 * config.model_hidden_channels
129
+ self.conv_kernel_size = conv_kernel_size
130
+ self.conv_layers = conv_layers
131
+
132
+ self.kernel_channels = (
133
+ self.conv_in_channels * self.conv_out_channels * self.conv_kernel_size * self.conv_layers
134
+ )
135
+ self.bias_channels = self.conv_out_channels * self.conv_layers
136
+
137
+ self.resnet_in_channels = config.num_mel_bins
138
+ self.resnet_hidden_channels = config.kernel_predictor_hidden_channels
139
+ self.resnet_kernel_size = config.kernel_predictor_conv_size
140
+ self.num_blocks = config.kernel_predictor_num_blocks
141
+
142
+ self.leaky_relu_slope = config.leaky_relu_slope
143
+
144
+ padding = (self.resnet_kernel_size - 1) // 2
145
+
146
+ self.input_conv = nn.Conv1d(self.resnet_in_channels, self.resnet_hidden_channels, 5, padding=2, bias=True)
147
+
148
+ self.resblocks = nn.ModuleList([UnivNetKernelPredictorResidualBlock(config) for _ in range(self.num_blocks)])
149
+
150
+ self.kernel_conv = nn.Conv1d(
151
+ self.resnet_hidden_channels, self.kernel_channels, self.resnet_kernel_size, padding=padding, bias=True
152
+ )
153
+ self.bias_conv = nn.Conv1d(
154
+ self.resnet_hidden_channels, self.bias_channels, self.resnet_kernel_size, padding=padding, bias=True
155
+ )
156
+
157
+ def forward(self, spectrogram: torch.FloatTensor):
158
+ """
159
+ Maps a conditioning log-mel spectrogram to a tensor of convolutional kernels and biases, for use in location
160
+ variable convolutional layers. Note that the input spectrogram should have shape (batch_size, input_channels,
161
+ seq_length).
162
+
163
+ Args:
164
+ spectrogram (`torch.FloatTensor` of shape `(batch_size, input_channels, seq_length)`):
165
+ Tensor containing the log-mel spectrograms.
166
+
167
+ Returns:
168
+ Tuple[`torch.FloatTensor, `torch.FloatTensor`]: tuple of tensors where the first element is the tensor of
169
+ location variable convolution kernels of shape `(batch_size, self.conv_layers, self.conv_in_channels,
170
+ self.conv_out_channels, self.conv_kernel_size, seq_length)` and the second element is the tensor of
171
+ location variable convolution biases of shape `(batch_size, self.conv_layers. self.conv_out_channels,
172
+ seq_length)`.
173
+ """
174
+ batch_size, _, seq_length = spectrogram.shape
175
+
176
+ hidden_states = self.input_conv(spectrogram)
177
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
178
+
179
+ for resblock in self.resblocks:
180
+ hidden_states = resblock(hidden_states)
181
+
182
+ kernel_hidden_states = self.kernel_conv(hidden_states)
183
+ bias_hidden_states = self.bias_conv(hidden_states)
184
+
185
+ # Reshape kernels and biases to appropriate shape
186
+ kernels = kernel_hidden_states.view(
187
+ batch_size,
188
+ self.conv_layers,
189
+ self.conv_in_channels,
190
+ self.conv_out_channels,
191
+ self.conv_kernel_size,
192
+ seq_length,
193
+ ).contiguous()
194
+ biases = bias_hidden_states.view(
195
+ batch_size,
196
+ self.conv_layers,
197
+ self.conv_out_channels,
198
+ seq_length,
199
+ ).contiguous()
200
+
201
+ return kernels, biases
202
+
203
+ def apply_weight_norm(self):
204
+ weight_norm = nn.utils.weight_norm
205
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
206
+ weight_norm = nn.utils.parametrizations.weight_norm
207
+
208
+ weight_norm(self.input_conv)
209
+ for layer in self.resblocks:
210
+ layer.apply_weight_norm()
211
+ weight_norm(self.kernel_conv)
212
+ weight_norm(self.bias_conv)
213
+
214
+ def remove_weight_norm(self):
215
+ nn.utils.remove_weight_norm(self.input_conv)
216
+ for layer in self.resblocks:
217
+ layer.remove_weight_norm()
218
+ nn.utils.remove_weight_norm(self.kernel_conv)
219
+ nn.utils.remove_weight_norm(self.bias_conv)
220
+
221
+
222
+ class UnivNetLvcResidualBlock(nn.Module):
223
+ """
224
+ Implementation of the location variable convolution (LVC) residual block for the UnivNet residual network.
225
+
226
+ Parameters:
227
+ config: (`UnivNetConfig`):
228
+ Config for the `UnivNetModel` model.
229
+ kernel_size (`int`):
230
+ The kernel size for the dilated 1D convolutional layer.
231
+ dilation (`int`):
232
+ The dilation for the dilated 1D convolutional layer.
233
+ """
234
+
235
+ def __init__(
236
+ self,
237
+ config: UnivNetConfig,
238
+ kernel_size: int,
239
+ dilation: int,
240
+ ):
241
+ super().__init__()
242
+ self.hidden_channels = config.model_hidden_channels
243
+ self.kernel_size = kernel_size
244
+ self.dilation = dilation
245
+ self.leaky_relu_slope = config.leaky_relu_slope
246
+
247
+ padding = self.dilation * (self.kernel_size - 1) // 2
248
+
249
+ self.conv = nn.Conv1d(
250
+ self.hidden_channels,
251
+ self.hidden_channels,
252
+ self.kernel_size,
253
+ padding=padding,
254
+ dilation=self.dilation,
255
+ )
256
+
257
+ def forward(self, hidden_states, kernel, bias, hop_size=256):
258
+ residual = hidden_states
259
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
260
+ hidden_states = self.conv(hidden_states)
261
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
262
+ hidden_states = self.location_variable_convolution(hidden_states, kernel, bias, hop_size=hop_size)
263
+ # Gated activation unit
264
+ hidden_states = torch.sigmoid(hidden_states[:, : self.hidden_channels, :]) * torch.tanh(
265
+ hidden_states[:, self.hidden_channels :, :]
266
+ )
267
+ # Skip connection
268
+ hidden_states = residual + hidden_states
269
+
270
+ return hidden_states
271
+
272
+ # Based on https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L171
273
+ def location_variable_convolution(
274
+ self,
275
+ hidden_states: torch.FloatTensor,
276
+ kernel: torch.FloatTensor,
277
+ bias: torch.FloatTensor,
278
+ dilation: int = 1,
279
+ hop_size: int = 256,
280
+ ):
281
+ """
282
+ Performs location-variable convolution operation on the input sequence (hidden_states) using the local
283
+ convolution kernel. This was introduced in [LVCNet: Efficient Condition-Dependent Modeling Network for Waveform
284
+ Generation](https://arxiv.org/abs/2102.10815) by Zhen Zheng, Jianzong Wang, Ning Cheng, and Jing Xiao.
285
+
286
+ Time: 414 μs ± 309 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each), test on NVIDIA V100.
287
+
288
+ Args:
289
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, in_channels, in_length)`):
290
+ The input sequence of shape (batch, in_channels, in_length).
291
+ kernel (`torch.FloatTensor` of shape `(batch_size, in_channels, out_channels, kernel_size, kernel_length)`):
292
+ The local convolution kernel of shape (batch, in_channels, out_channels, kernel_size, kernel_length).
293
+ bias (`torch.FloatTensor` of shape `(batch_size, out_channels, kernel_length)`):
294
+ The bias for the local convolution of shape (batch, out_channels, kernel_length).
295
+ dilation (`int`, *optional*, defaults to 1):
296
+ The dilation of convolution.
297
+ hop_size (`int`, *optional*, defaults to 256):
298
+ The hop_size of the conditioning sequence.
299
+ Returns:
300
+ `torch.FloatTensor`: the output sequence after performing local convolution with shape (batch_size,
301
+ out_channels, in_length).
302
+ """
303
+ batch, _, in_length = hidden_states.shape
304
+ batch, _, out_channels, kernel_size, kernel_length = kernel.shape
305
+ if in_length != (kernel_length * hop_size):
306
+ raise ValueError(
307
+ f"Dim 2 of `hidden_states` should be {kernel_length * hop_size}) but got {in_length}. Please check"
308
+ " `hidden_states` or `kernel` and `hop_size` to make sure they are correct."
309
+ )
310
+
311
+ padding = dilation * int((kernel_size - 1) / 2)
312
+
313
+ # (batch, in_channels, in_length + 2*padding)
314
+ hidden_states = nn.functional.pad(hidden_states, (padding, padding), "constant", 0)
315
+ # (batch, in_channels, kernel_length, hop_size + 2*padding)
316
+ hidden_states = hidden_states.unfold(2, hop_size + 2 * padding, hop_size)
317
+
318
+ if hop_size < dilation:
319
+ hidden_states = nn.functional.pad(hidden_states, (0, dilation), "constant", 0)
320
+ # (batch, in_channels, kernel_length, (hop_size + 2*padding)/dilation, dilation)
321
+ hidden_states = hidden_states.unfold(3, dilation, dilation)
322
+ hidden_states = hidden_states[:, :, :, :, :hop_size]
323
+ # (batch, in_channels, kernel_length, dilation, (hop_size + 2*padding)/dilation)
324
+ hidden_states = hidden_states.transpose(3, 4)
325
+ # (batch, in_channels, kernel_length, dilation, _, kernel_size)
326
+ hidden_states = hidden_states.unfold(4, kernel_size, 1)
327
+
328
+ # Apply local convolution kernel to hidden_states.
329
+ output_hidden_states = torch.einsum("bildsk,biokl->bolsd", hidden_states, kernel)
330
+
331
+ output_hidden_states = output_hidden_states.to(memory_format=torch.channels_last_3d)
332
+ bias = bias.unsqueeze(-1).unsqueeze(-1).to(memory_format=torch.channels_last_3d)
333
+ output_hidden_states = output_hidden_states + bias
334
+ output_hidden_states = output_hidden_states.contiguous().view(batch, out_channels, -1)
335
+
336
+ return output_hidden_states
337
+
338
+ def apply_weight_norm(self):
339
+ weight_norm = nn.utils.weight_norm
340
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
341
+ weight_norm = nn.utils.parametrizations.weight_norm
342
+
343
+ weight_norm(self.conv)
344
+
345
+ def remove_weight_norm(self):
346
+ nn.utils.remove_weight_norm(self.conv)
347
+
348
+
349
+ class UnivNetLvcBlock(nn.Module):
350
+ """
351
+ Implementation of the location variable convolution (LVC) residual block of the UnivNet residual block. Includes a
352
+ `UnivNetKernelPredictor` inside to predict the kernels and biases of the LVC layers.
353
+
354
+ Based on LVCBlock in
355
+ [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L98)
356
+
357
+ Parameters:
358
+ config (`UnivNetConfig`):
359
+ Config for the `UnivNetModel` model.
360
+ layer_id (`int`):
361
+ An integer corresponding to the index of the current LVC resnet block layer. This should be between 0 and
362
+ `len(config.resblock_stride_sizes) - 1)` inclusive.
363
+ lvc_hop_size (`int`, *optional*, defaults to 256):
364
+ The hop size for the location variable convolutional layers.
365
+ """
366
+
367
+ def __init__(
368
+ self,
369
+ config: UnivNetConfig,
370
+ layer_id: int,
371
+ lvc_hop_size: int = 256,
372
+ ):
373
+ super().__init__()
374
+ self.hidden_channels = config.model_hidden_channels
375
+ self.kernel_size = config.resblock_kernel_sizes[layer_id]
376
+ self.stride = config.resblock_stride_sizes[layer_id]
377
+ self.dilations = config.resblock_dilation_sizes[layer_id]
378
+ self.cond_hop_length = lvc_hop_size
379
+ self.leaky_relu_slope = config.leaky_relu_slope
380
+ self.num_blocks = len(self.dilations)
381
+
382
+ self.convt_pre = nn.ConvTranspose1d(
383
+ self.hidden_channels,
384
+ self.hidden_channels,
385
+ 2 * self.stride,
386
+ stride=self.stride,
387
+ padding=self.stride // 2 + self.stride % 2,
388
+ output_padding=self.stride % 2,
389
+ )
390
+
391
+ self.kernel_predictor = UnivNetKernelPredictor(config, self.kernel_size, self.num_blocks)
392
+
393
+ self.resblocks = nn.ModuleList(
394
+ [UnivNetLvcResidualBlock(config, self.kernel_size, self.dilations[i]) for i in range(self.num_blocks)]
395
+ )
396
+
397
+ def forward(self, hidden_states: torch.FloatTensor, spectrogram: torch.FloatTensor):
398
+ # hidden_states: (batch_size, hidden_channels, seq_length)
399
+ # spectrogram: (batch_size, cond_channels, cond_length)
400
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
401
+ hidden_states = self.convt_pre(hidden_states)
402
+
403
+ kernels, biases = self.kernel_predictor(spectrogram)
404
+
405
+ for i, resblock in enumerate(self.resblocks):
406
+ kernel = kernels[:, i, :, :, :, :]
407
+ bias = biases[:, i, :, :]
408
+ hidden_states = resblock(hidden_states, kernel, bias, hop_size=self.cond_hop_length)
409
+
410
+ return hidden_states
411
+
412
+ def apply_weight_norm(self):
413
+ weight_norm = nn.utils.weight_norm
414
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
415
+ weight_norm = nn.utils.parametrizations.weight_norm
416
+
417
+ weight_norm(self.convt_pre)
418
+ self.kernel_predictor.apply_weight_norm()
419
+ for layer in self.resblocks:
420
+ layer.apply_weight_norm()
421
+
422
+ def remove_weight_norm(self):
423
+ nn.utils.remove_weight_norm(self.convt_pre)
424
+ self.kernel_predictor.remove_weight_norm()
425
+ for layer in self.resblocks:
426
+ layer.remove_weight_norm()
427
+
428
+
429
+ UNIVNET_START_DOCSTRING = r"""
430
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
431
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
432
+ etc.)
433
+
434
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
435
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
436
+ and behavior.
437
+
438
+ Parameters:
439
+ config ([`UnivNetConfig`]):
440
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
441
+ load the weights associated with the model, only the configuration. Check out the
442
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
443
+ """
444
+
445
+
446
+ UNIVNET_INPUTS_DOCSTRING = r"""
447
+ Converts a noise waveform and a conditioning spectrogram to a speech waveform. Passing a batch of log-mel
448
+ spectrograms returns a batch of speech waveforms. Passing a single, un-batched log-mel spectrogram returns a
449
+ single, un-batched speech waveform.
450
+
451
+ Args:
452
+ input_features (`torch.FloatTensor`):
453
+ Tensor containing the log-mel spectrograms. Can be batched and of shape `(batch_size, sequence_length,
454
+ config.num_mel_channels)`, or un-batched and of shape `(sequence_length, config.num_mel_channels)`.
455
+ noise_sequence (`torch.FloatTensor`, *optional*):
456
+ Tensor containing a noise sequence of standard Gaussian noise. Can be batched and of shape `(batch_size,
457
+ sequence_length, config.model_in_channels)`, or un-batched and of shape (sequence_length,
458
+ config.model_in_channels)`. If not supplied, will be randomly generated.
459
+ padding_mask (`torch.BoolTensor`, *optional*):
460
+ Mask indicating which parts of each sequence are padded. Mask values are selected in `[0, 1]`:
461
+
462
+ - 1 for tokens that are **not masked**
463
+ - 0 for tokens that are **masked**
464
+
465
+ The mask can be batched and of shape `(batch_size, sequence_length)` or un-batched and of shape
466
+ `(sequence_length,)`.
467
+ generator (`torch.Generator`, *optional*):
468
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
469
+ deterministic.
470
+ return_dict:
471
+ Whether to return a [`~utils.ModelOutput`] subclass instead of a plain tuple.
472
+ """
473
+
474
+
475
+ @add_start_docstrings(
476
+ """UnivNet GAN vocoder.""",
477
+ UNIVNET_START_DOCSTRING,
478
+ )
479
+ class UnivNetModel(PreTrainedModel):
480
+ config_class = UnivNetConfig
481
+ main_input_name = "input_features"
482
+
483
+ def __init__(self, config: UnivNetConfig):
484
+ super().__init__(config)
485
+
486
+ self.num_kernels = len(config.resblock_kernel_sizes)
487
+ self.leaky_relu_slope = config.leaky_relu_slope
488
+
489
+ self.conv_pre = nn.Conv1d(
490
+ config.model_in_channels,
491
+ config.model_hidden_channels,
492
+ kernel_size=7,
493
+ stride=1,
494
+ padding=3,
495
+ padding_mode="reflect",
496
+ )
497
+
498
+ # Initialize location-variable convolution ResNet Blocks.
499
+ num_layers = len(config.resblock_stride_sizes)
500
+ hop_length = 1
501
+ hop_lengths = []
502
+ for stride in config.resblock_stride_sizes:
503
+ hop_length = hop_length * stride
504
+ hop_lengths.append(hop_length)
505
+
506
+ self.resblocks = nn.ModuleList(
507
+ [
508
+ UnivNetLvcBlock(
509
+ config,
510
+ layer_id=i,
511
+ lvc_hop_size=hop_lengths[i],
512
+ )
513
+ for i in range(num_layers)
514
+ ]
515
+ )
516
+
517
+ self.conv_post = nn.Conv1d(config.model_hidden_channels, 1, 7, padding=3, padding_mode="reflect")
518
+
519
+ # Initialize weights and apply final processing
520
+ self.post_init()
521
+
522
+ @add_start_docstrings_to_model_forward(UNIVNET_INPUTS_DOCSTRING)
523
+ @replace_return_docstrings(output_type=UnivNetModelOutput, config_class=_CONFIG_FOR_DOC)
524
+ def forward(
525
+ self,
526
+ input_features: torch.FloatTensor,
527
+ noise_sequence: Optional[torch.FloatTensor] = None,
528
+ padding_mask: Optional[torch.FloatTensor] = None,
529
+ generator: Optional[torch.Generator] = None,
530
+ return_dict: Optional[bool] = None,
531
+ ) -> Union[Tuple[torch.FloatTensor], UnivNetModelOutput]:
532
+ r"""
533
+ Returns:
534
+
535
+ Example:
536
+
537
+ ```python
538
+ >>> from transformers import UnivNetFeatureExtractor, UnivNetModel
539
+ >>> from datasets import load_dataset, Audio
540
+
541
+ >>> model = UnivNetModel.from_pretrained("dg845/univnet-dev")
542
+ >>> feature_extractor = UnivNetFeatureExtractor.from_pretrained("dg845/univnet-dev")
543
+
544
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
545
+ >>> # Resample the audio to the feature extractor's sampling rate.
546
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
547
+ >>> inputs = feature_extractor(
548
+ ... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
549
+ ... )
550
+ >>> audio = model(**inputs).waveforms
551
+ >>> list(audio.shape)
552
+ [1, 140288]
553
+ ```
554
+ """
555
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
556
+
557
+ # Resolve batch sizes for noise_sequence and spectrogram
558
+ spectrogram_batched = input_features.dim() == 3
559
+ if not spectrogram_batched:
560
+ input_features = input_features.unsqueeze(0)
561
+ spectrogram_batch_size, spectrogram_length, _ = input_features.shape
562
+
563
+ if noise_sequence is not None:
564
+ noise_sequence_batched = noise_sequence.dim() == 3
565
+ if not noise_sequence_batched:
566
+ noise_sequence = noise_sequence.unsqueeze(0)
567
+ else:
568
+ # Randomly generate noise_sequence
569
+ noise_sequence_shape = (spectrogram_batch_size, spectrogram_length, self.config.model_in_channels)
570
+ noise_sequence = torch.randn(
571
+ noise_sequence_shape, generator=generator, dtype=input_features.dtype, device=input_features.device
572
+ )
573
+ noise_sequence_batch_size = noise_sequence.shape[0]
574
+
575
+ if spectrogram_batch_size > 1 and noise_sequence_batch_size == 1:
576
+ # Repeat noise_sequence spectrogram_batch_size times
577
+ noise_sequence = noise_sequence.repeat(spectrogram_batch_size, 1, 1)
578
+ elif noise_sequence_batch_size > 1 and spectrogram_batch_size == 1:
579
+ # Repeat spectrogram noise_sequence_batch_size times
580
+ input_features = input_features.repeat(noise_sequence_batch_size, 1, 1)
581
+
582
+ if noise_sequence_batch_size != spectrogram_batch_size:
583
+ raise ValueError(
584
+ f"The batch size of `noise_sequence` is {noise_sequence_batch_size} and the batch size of"
585
+ f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
586
+ )
587
+
588
+ if padding_mask is not None:
589
+ if padding_mask.dim() == 1:
590
+ padding_mask = padding_mask.unsqueeze(0)
591
+ padding_mask_batch_size = padding_mask.shape[0]
592
+ if padding_mask_batch_size != spectrogram_batch_size:
593
+ raise ValueError(
594
+ f"The batch size of `padding_mask` is {padding_mask_batch_size} and the batch size of"
595
+ f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
596
+ )
597
+
598
+ # Change shapes to have channels before sequence lengths
599
+ hidden_states = noise_sequence.transpose(2, 1)
600
+ input_features = input_features.transpose(2, 1)
601
+
602
+ hidden_states = self.conv_pre(hidden_states)
603
+
604
+ for resblock in self.resblocks:
605
+ hidden_states = resblock(hidden_states, input_features)
606
+
607
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
608
+ hidden_states = self.conv_post(hidden_states)
609
+ hidden_states = torch.tanh(hidden_states)
610
+
611
+ # Remove sequence length dimension since this collapses to 1
612
+ # NOTE: keep waveforms batched even if there's only one
613
+ waveform = hidden_states.squeeze(1)
614
+
615
+ # Get sequence lengths for UnivNetFeatureExtractor.batch_decode.
616
+ waveform_lengths = None
617
+ if padding_mask is not None:
618
+ # Padding is always contiguous and added on the right
619
+ waveform_lengths = torch.sum(padding_mask, dim=1)
620
+
621
+ if not return_dict:
622
+ outputs = (waveform, waveform_lengths)
623
+ return outputs
624
+
625
+ return UnivNetModelOutput(
626
+ waveforms=waveform,
627
+ waveform_lengths=waveform_lengths,
628
+ )
629
+
630
+ def _init_weights(self, module):
631
+ """Initialize the weights."""
632
+ if isinstance(module, (nn.Linear, nn.Conv1d, nn.ConvTranspose1d)):
633
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
634
+ if module.bias is not None:
635
+ module.bias.data.zero_()
636
+
637
+ def apply_weight_norm(self):
638
+ weight_norm = nn.utils.weight_norm
639
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
640
+ weight_norm = nn.utils.parametrizations.weight_norm
641
+
642
+ weight_norm(self.conv_pre)
643
+ for layer in self.resblocks:
644
+ layer.apply_weight_norm()
645
+ weight_norm(self.conv_post)
646
+
647
+ def remove_weight_norm(self):
648
+ nn.utils.remove_weight_norm(self.conv_pre)
649
+ for layer in self.resblocks:
650
+ layer.remove_weight_norm()
651
+ nn.utils.remove_weight_norm(self.conv_post)
652
+
653
+
654
+ __all__ = ["UnivNetModel"]