chen459664 commited on
Commit
71db072
·
verified ·
1 Parent(s): af4292d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/swinv2/modeling_swinv2.py +1331 -0
  2. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/switch_transformers/configuration_switch_transformers.py +201 -0
  3. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/__init__.py +154 -0
  4. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/configuration_t5.py +165 -0
  5. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py +60 -0
  6. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py +235 -0
  7. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/modeling_flax_t5.py +1799 -0
  8. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/modeling_tf_t5.py +1628 -0
  9. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/tokenization_t5.py +351 -0
  10. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/table_transformer/convert_table_transformer_original_pytorch_checkpoint_to_pytorch.py +318 -0
  11. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/table_transformer/modeling_table_transformer.py +1943 -0
  12. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tapas/__init__.py +95 -0
  13. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tapas/tokenization_tapas.py +0 -0
  14. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tapex/tokenization_tapex.py +1486 -0
  15. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/time_series_transformer/__init__.py +62 -0
  16. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/time_series_transformer/configuration_time_series_transformer.py +235 -0
  17. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py +1827 -0
  18. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/timesformer/__init__.py +55 -0
  19. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/timesformer/configuration_timesformer.py +129 -0
  20. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/timesformer/convert_timesformer_to_pytorch.py +253 -0
  21. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/timesformer/modeling_timesformer.py +810 -0
  22. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trajectory_transformer/configuration_trajectory_transformer.py +158 -0
  23. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py +70 -0
  24. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trajectory_transformer/modeling_trajectory_transformer.py +618 -0
  25. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/__init__.py +97 -0
  26. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/configuration_transfo_xl.py +188 -0
  27. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py +121 -0
  28. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py +1165 -0
  29. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_tf_transfo_xl_utilities.py +178 -0
  30. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_transfo_xl.py +1294 -0
  31. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_transfo_xl_utilities.py +252 -0
  32. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/tokenization_transfo_xl.py +804 -0
  33. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/__init__.py +59 -0
  34. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/configuration_trocr.py +149 -0
  35. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py +238 -0
  36. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/modeling_trocr.py +1020 -0
  37. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/processing_trocr.py +138 -0
  38. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/__init__.py +101 -0
  39. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/configuration_tvlt.py +187 -0
  40. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/feature_extraction_tvlt.py +227 -0
  41. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/image_processing_tvlt.py +453 -0
  42. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/modeling_tvlt.py +1317 -0
  43. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/processing_tvlt.py +88 -0
  44. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/__init__.py +63 -0
  45. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/configuration_unispeech.py +300 -0
  46. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py +274 -0
  47. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/modeling_unispeech.py +1585 -0
  48. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech_sat/__init__.py +69 -0
  49. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech_sat/configuration_unispeech_sat.py +318 -0
  50. SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py +110 -0
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/swinv2/modeling_swinv2.py ADDED
@@ -0,0 +1,1331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft Research 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 Swinv2 Transformer model."""
16
+
17
+
18
+ import collections.abc
19
+ import math
20
+ import warnings
21
+ from dataclasses import dataclass
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from ...activations import ACT2FN
30
+ from ...modeling_utils import PreTrainedModel
31
+ from ...pytorch_utils import find_pruneable_heads_and_indices, meshgrid, prune_linear_layer
32
+ from ...utils import (
33
+ ModelOutput,
34
+ add_code_sample_docstrings,
35
+ add_start_docstrings,
36
+ add_start_docstrings_to_model_forward,
37
+ logging,
38
+ replace_return_docstrings,
39
+ )
40
+ from .configuration_swinv2 import Swinv2Config
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ # General docstring
46
+ _CONFIG_FOR_DOC = "Swinv2Config"
47
+
48
+ # Base docstring
49
+ _CHECKPOINT_FOR_DOC = "microsoft/swinv2-tiny-patch4-window8-256"
50
+ _EXPECTED_OUTPUT_SHAPE = [1, 64, 768]
51
+
52
+ # Image classification docstring
53
+ _IMAGE_CLASS_CHECKPOINT = "microsoft/swinv2-tiny-patch4-window8-256"
54
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
55
+
56
+
57
+ SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST = [
58
+ "microsoft/swinv2-tiny-patch4-window8-256",
59
+ # See all Swinv2 models at https://huggingface.co/models?filter=swinv2
60
+ ]
61
+
62
+
63
+ # drop_path, Swinv2PatchEmbeddings, Swinv2PatchMerging and Swinv2DropPath are from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/swin_transformer_v2.py.
64
+
65
+
66
+ @dataclass
67
+ # Copied from transformers.models.swin.modeling_swin.SwinEncoderOutput with Swin->Swinv2
68
+ class Swinv2EncoderOutput(ModelOutput):
69
+ """
70
+ Swinv2 encoder's outputs, with potential hidden states and attentions.
71
+
72
+ Args:
73
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
74
+ Sequence of hidden-states at the output of the last layer of the model.
75
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
76
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
77
+ shape `(batch_size, sequence_length, hidden_size)`.
78
+
79
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
80
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
81
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
82
+ sequence_length)`.
83
+
84
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
85
+ heads.
86
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
87
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
88
+ shape `(batch_size, hidden_size, height, width)`.
89
+
90
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
91
+ include the spatial dimensions.
92
+ """
93
+
94
+ last_hidden_state: torch.FloatTensor = None
95
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
96
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
97
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
98
+
99
+
100
+ @dataclass
101
+ # Copied from transformers.models.swin.modeling_swin.SwinModelOutput with Swin->Swinv2
102
+ class Swinv2ModelOutput(ModelOutput):
103
+ """
104
+ Swinv2 model's outputs that also contains a pooling of the last hidden states.
105
+
106
+ Args:
107
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
108
+ Sequence of hidden-states at the output of the last layer of the model.
109
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
110
+ Average pooling of the last layer hidden-state.
111
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
112
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
113
+ shape `(batch_size, sequence_length, hidden_size)`.
114
+
115
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
116
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
117
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
118
+ sequence_length)`.
119
+
120
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
121
+ heads.
122
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
123
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
124
+ shape `(batch_size, hidden_size, height, width)`.
125
+
126
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
127
+ include the spatial dimensions.
128
+ """
129
+
130
+ last_hidden_state: torch.FloatTensor = None
131
+ pooler_output: Optional[torch.FloatTensor] = None
132
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
133
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
134
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
135
+
136
+
137
+ @dataclass
138
+ # Copied from transformers.models.swin.modeling_swin.SwinMaskedImageModelingOutput with Swin->Swinv2
139
+ class Swinv2MaskedImageModelingOutput(ModelOutput):
140
+ """
141
+ Swinv2 masked image model outputs.
142
+
143
+ Args:
144
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
145
+ Masked image modeling (MLM) loss.
146
+ reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
147
+ Reconstructed pixel values.
148
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
149
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
150
+ shape `(batch_size, sequence_length, hidden_size)`.
151
+
152
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
153
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
154
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
155
+ sequence_length)`.
156
+
157
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
158
+ heads.
159
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
160
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
161
+ shape `(batch_size, hidden_size, height, width)`.
162
+
163
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
164
+ include the spatial dimensions.
165
+ """
166
+
167
+ loss: Optional[torch.FloatTensor] = None
168
+ reconstruction: torch.FloatTensor = None
169
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
170
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
171
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
172
+
173
+ @property
174
+ def logits(self):
175
+ warnings.warn(
176
+ "logits attribute is deprecated and will be removed in version 5 of Transformers."
177
+ " Please use the reconstruction attribute to retrieve the final output instead.",
178
+ FutureWarning,
179
+ )
180
+ return self.reconstruction
181
+
182
+
183
+ @dataclass
184
+ # Copied from transformers.models.swin.modeling_swin.SwinImageClassifierOutput with Swin->Swinv2
185
+ class Swinv2ImageClassifierOutput(ModelOutput):
186
+ """
187
+ Swinv2 outputs for image classification.
188
+
189
+ Args:
190
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
191
+ Classification (or regression if config.num_labels==1) loss.
192
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
193
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
194
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
195
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
196
+ shape `(batch_size, sequence_length, hidden_size)`.
197
+
198
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
199
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
200
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
201
+ sequence_length)`.
202
+
203
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
204
+ heads.
205
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
206
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
207
+ shape `(batch_size, hidden_size, height, width)`.
208
+
209
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
210
+ include the spatial dimensions.
211
+ """
212
+
213
+ loss: Optional[torch.FloatTensor] = None
214
+ logits: torch.FloatTensor = None
215
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
216
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
217
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
218
+
219
+
220
+ # Copied from transformers.models.swin.modeling_swin.window_partition
221
+ def window_partition(input_feature, window_size):
222
+ """
223
+ Partitions the given input into windows.
224
+ """
225
+ batch_size, height, width, num_channels = input_feature.shape
226
+ input_feature = input_feature.view(
227
+ batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
228
+ )
229
+ windows = input_feature.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
230
+ return windows
231
+
232
+
233
+ # Copied from transformers.models.swin.modeling_swin.window_reverse
234
+ def window_reverse(windows, window_size, height, width):
235
+ """
236
+ Merges windows to produce higher resolution features.
237
+ """
238
+ num_channels = windows.shape[-1]
239
+ windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
240
+ windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, height, width, num_channels)
241
+ return windows
242
+
243
+
244
+ # Copied from transformers.models.swin.modeling_swin.drop_path
245
+ def drop_path(input, drop_prob=0.0, training=False, scale_by_keep=True):
246
+ """
247
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
248
+
249
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
250
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
251
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
252
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
253
+ argument.
254
+ """
255
+ if drop_prob == 0.0 or not training:
256
+ return input
257
+ keep_prob = 1 - drop_prob
258
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
259
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
260
+ random_tensor.floor_() # binarize
261
+ output = input.div(keep_prob) * random_tensor
262
+ return output
263
+
264
+
265
+ # Copied from transformers.models.swin.modeling_swin.SwinDropPath with Swin->Swinv2
266
+ class Swinv2DropPath(nn.Module):
267
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
268
+
269
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
270
+ super().__init__()
271
+ self.drop_prob = drop_prob
272
+
273
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
274
+ return drop_path(hidden_states, self.drop_prob, self.training)
275
+
276
+ def extra_repr(self) -> str:
277
+ return "p={}".format(self.drop_prob)
278
+
279
+
280
+ # Copied from transformers.models.swin.modeling_swin.SwinEmbeddings with Swin->Swinv2
281
+ class Swinv2Embeddings(nn.Module):
282
+ """
283
+ Construct the patch and position embeddings. Optionally, also the mask token.
284
+ """
285
+
286
+ def __init__(self, config, use_mask_token=False):
287
+ super().__init__()
288
+
289
+ self.patch_embeddings = Swinv2PatchEmbeddings(config)
290
+ num_patches = self.patch_embeddings.num_patches
291
+ self.patch_grid = self.patch_embeddings.grid_size
292
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
293
+
294
+ if config.use_absolute_embeddings:
295
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim))
296
+ else:
297
+ self.position_embeddings = None
298
+
299
+ self.norm = nn.LayerNorm(config.embed_dim)
300
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
301
+
302
+ def forward(
303
+ self, pixel_values: Optional[torch.FloatTensor], bool_masked_pos: Optional[torch.BoolTensor] = None
304
+ ) -> Tuple[torch.Tensor]:
305
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
306
+ embeddings = self.norm(embeddings)
307
+ batch_size, seq_len, _ = embeddings.size()
308
+
309
+ if bool_masked_pos is not None:
310
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
311
+ # replace the masked visual tokens by mask_tokens
312
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
313
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
314
+
315
+ if self.position_embeddings is not None:
316
+ embeddings = embeddings + self.position_embeddings
317
+
318
+ embeddings = self.dropout(embeddings)
319
+
320
+ return embeddings, output_dimensions
321
+
322
+
323
+ # Copied from transformers.models.swin.modeling_swin.SwinPatchEmbeddings with Swin->Swinv2
324
+ class Swinv2PatchEmbeddings(nn.Module):
325
+ """
326
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
327
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
328
+ Transformer.
329
+ """
330
+
331
+ def __init__(self, config):
332
+ super().__init__()
333
+ image_size, patch_size = config.image_size, config.patch_size
334
+ num_channels, hidden_size = config.num_channels, config.embed_dim
335
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
336
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
337
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
338
+ self.image_size = image_size
339
+ self.patch_size = patch_size
340
+ self.num_channels = num_channels
341
+ self.num_patches = num_patches
342
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
343
+
344
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
345
+
346
+ def maybe_pad(self, pixel_values, height, width):
347
+ if width % self.patch_size[1] != 0:
348
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
349
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
350
+ if height % self.patch_size[0] != 0:
351
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
352
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
353
+ return pixel_values
354
+
355
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor, Tuple[int]]:
356
+ _, num_channels, height, width = pixel_values.shape
357
+ if num_channels != self.num_channels:
358
+ raise ValueError(
359
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
360
+ )
361
+ # pad the input to be divisible by self.patch_size, if needed
362
+ pixel_values = self.maybe_pad(pixel_values, height, width)
363
+ embeddings = self.projection(pixel_values)
364
+ _, _, height, width = embeddings.shape
365
+ output_dimensions = (height, width)
366
+ embeddings = embeddings.flatten(2).transpose(1, 2)
367
+
368
+ return embeddings, output_dimensions
369
+
370
+
371
+ class Swinv2PatchMerging(nn.Module):
372
+ """
373
+ Patch Merging Layer.
374
+
375
+ Args:
376
+ input_resolution (`Tuple[int]`):
377
+ Resolution of input feature.
378
+ dim (`int`):
379
+ Number of input channels.
380
+ norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
381
+ Normalization layer class.
382
+ """
383
+
384
+ def __init__(self, input_resolution: Tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
385
+ super().__init__()
386
+ self.input_resolution = input_resolution
387
+ self.dim = dim
388
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
389
+ self.norm = norm_layer(2 * dim)
390
+
391
+ def maybe_pad(self, input_feature, height, width):
392
+ should_pad = (height % 2 == 1) or (width % 2 == 1)
393
+ if should_pad:
394
+ pad_values = (0, 0, 0, width % 2, 0, height % 2)
395
+ input_feature = nn.functional.pad(input_feature, pad_values)
396
+
397
+ return input_feature
398
+
399
+ def forward(self, input_feature: torch.Tensor, input_dimensions: Tuple[int, int]) -> torch.Tensor:
400
+ height, width = input_dimensions
401
+ # `dim` is height * width
402
+ batch_size, dim, num_channels = input_feature.shape
403
+
404
+ input_feature = input_feature.view(batch_size, height, width, num_channels)
405
+ # pad input to be disible by width and height, if needed
406
+ input_feature = self.maybe_pad(input_feature, height, width)
407
+ # [batch_size, height/2, width/2, num_channels]
408
+ input_feature_0 = input_feature[:, 0::2, 0::2, :]
409
+ # [batch_size, height/2, width/2, num_channels]
410
+ input_feature_1 = input_feature[:, 1::2, 0::2, :]
411
+ # [batch_size, height/2, width/2, num_channels]
412
+ input_feature_2 = input_feature[:, 0::2, 1::2, :]
413
+ # [batch_size, height/2, width/2, num_channels]
414
+ input_feature_3 = input_feature[:, 1::2, 1::2, :]
415
+ # [batch_size, height/2 * width/2, 4*num_channels]
416
+ input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1)
417
+ input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # [batch_size, height/2 * width/2, 4*C]
418
+
419
+ input_feature = self.reduction(input_feature)
420
+ input_feature = self.norm(input_feature)
421
+
422
+ return input_feature
423
+
424
+
425
+ class Swinv2SelfAttention(nn.Module):
426
+ def __init__(self, config, dim, num_heads, window_size, pretrained_window_size=[0, 0]):
427
+ super().__init__()
428
+ if dim % num_heads != 0:
429
+ raise ValueError(
430
+ f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
431
+ )
432
+
433
+ self.num_attention_heads = num_heads
434
+ self.attention_head_size = int(dim / num_heads)
435
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
436
+ self.window_size = (
437
+ window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
438
+ )
439
+ self.pretrained_window_size = pretrained_window_size
440
+ self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1))))
441
+ # mlp to generate continuous relative position bias
442
+ self.continuous_position_bias_mlp = nn.Sequential(
443
+ nn.Linear(2, 512, bias=True), nn.ReLU(inplace=True), nn.Linear(512, num_heads, bias=False)
444
+ )
445
+
446
+ # get relative_coords_table
447
+ relative_coords_h = torch.arange(-(self.window_size[0] - 1), self.window_size[0], dtype=torch.float32)
448
+ relative_coords_w = torch.arange(-(self.window_size[1] - 1), self.window_size[1], dtype=torch.float32)
449
+ relative_coords_table = (
450
+ torch.stack(meshgrid([relative_coords_h, relative_coords_w], indexing="ij"))
451
+ .permute(1, 2, 0)
452
+ .contiguous()
453
+ .unsqueeze(0)
454
+ ) # [1, 2*window_height - 1, 2*window_width - 1, 2]
455
+ if pretrained_window_size[0] > 0:
456
+ relative_coords_table[:, :, :, 0] /= pretrained_window_size[0] - 1
457
+ relative_coords_table[:, :, :, 1] /= pretrained_window_size[1] - 1
458
+ else:
459
+ relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1
460
+ relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1
461
+ relative_coords_table *= 8 # normalize to -8, 8
462
+ relative_coords_table = (
463
+ torch.sign(relative_coords_table) * torch.log2(torch.abs(relative_coords_table) + 1.0) / math.log2(8)
464
+ )
465
+ self.register_buffer("relative_coords_table", relative_coords_table, persistent=False)
466
+
467
+ # get pair-wise relative position index for each token inside the window
468
+ coords_h = torch.arange(self.window_size[0])
469
+ coords_w = torch.arange(self.window_size[1])
470
+ coords = torch.stack(meshgrid([coords_h, coords_w], indexing="ij"))
471
+ coords_flatten = torch.flatten(coords, 1)
472
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
473
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous()
474
+ relative_coords[:, :, 0] += self.window_size[0] - 1
475
+ relative_coords[:, :, 1] += self.window_size[1] - 1
476
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
477
+ relative_position_index = relative_coords.sum(-1)
478
+ self.register_buffer("relative_position_index", relative_position_index, persistent=False)
479
+
480
+ self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
481
+ self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=False)
482
+ self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
483
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
484
+
485
+ def transpose_for_scores(self, x):
486
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
487
+ x = x.view(new_x_shape)
488
+ return x.permute(0, 2, 1, 3)
489
+
490
+ def forward(
491
+ self,
492
+ hidden_states: torch.Tensor,
493
+ attention_mask: Optional[torch.FloatTensor] = None,
494
+ head_mask: Optional[torch.FloatTensor] = None,
495
+ output_attentions: Optional[bool] = False,
496
+ ) -> Tuple[torch.Tensor]:
497
+ batch_size, dim, num_channels = hidden_states.shape
498
+ mixed_query_layer = self.query(hidden_states)
499
+
500
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
501
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
502
+ query_layer = self.transpose_for_scores(mixed_query_layer)
503
+
504
+ # cosine attention
505
+ attention_scores = nn.functional.normalize(query_layer, dim=-1) @ nn.functional.normalize(
506
+ key_layer, dim=-1
507
+ ).transpose(-2, -1)
508
+ logit_scale = torch.clamp(self.logit_scale, max=math.log(1.0 / 0.01)).exp()
509
+ attention_scores = attention_scores * logit_scale
510
+ relative_position_bias_table = self.continuous_position_bias_mlp(self.relative_coords_table).view(
511
+ -1, self.num_attention_heads
512
+ )
513
+ # [window_height*window_width,window_height*window_width,num_attention_heads]
514
+ relative_position_bias = relative_position_bias_table[self.relative_position_index.view(-1)].view(
515
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
516
+ )
517
+ # [num_attention_heads,window_height*window_width,window_height*window_width]
518
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
519
+ relative_position_bias = 16 * torch.sigmoid(relative_position_bias)
520
+ attention_scores = attention_scores + relative_position_bias.unsqueeze(0)
521
+
522
+ if attention_mask is not None:
523
+ # Apply the attention mask is (precomputed for all layers in Swinv2Model forward() function)
524
+ mask_shape = attention_mask.shape[0]
525
+ attention_scores = attention_scores.view(
526
+ batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim
527
+ ) + attention_mask.unsqueeze(1).unsqueeze(0)
528
+ attention_scores = attention_scores + attention_mask.unsqueeze(1).unsqueeze(0)
529
+ attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
530
+
531
+ # Normalize the attention scores to probabilities.
532
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
533
+
534
+ # This is actually dropping out entire tokens to attend to, which might
535
+ # seem a bit unusual, but is taken from the original Transformer paper.
536
+ attention_probs = self.dropout(attention_probs)
537
+
538
+ # Mask heads if we want to
539
+ if head_mask is not None:
540
+ attention_probs = attention_probs * head_mask
541
+
542
+ context_layer = torch.matmul(attention_probs, value_layer)
543
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
544
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
545
+ context_layer = context_layer.view(new_context_layer_shape)
546
+
547
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
548
+
549
+ return outputs
550
+
551
+
552
+ # Copied from transformers.models.swin.modeling_swin.SwinSelfOutput with Swin->Swinv2
553
+ class Swinv2SelfOutput(nn.Module):
554
+ def __init__(self, config, dim):
555
+ super().__init__()
556
+ self.dense = nn.Linear(dim, dim)
557
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
558
+
559
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
560
+ hidden_states = self.dense(hidden_states)
561
+ hidden_states = self.dropout(hidden_states)
562
+
563
+ return hidden_states
564
+
565
+
566
+ class Swinv2Attention(nn.Module):
567
+ def __init__(self, config, dim, num_heads, window_size, pretrained_window_size=0):
568
+ super().__init__()
569
+ self.self = Swinv2SelfAttention(
570
+ config=config,
571
+ dim=dim,
572
+ num_heads=num_heads,
573
+ window_size=window_size,
574
+ pretrained_window_size=pretrained_window_size
575
+ if isinstance(pretrained_window_size, collections.abc.Iterable)
576
+ else (pretrained_window_size, pretrained_window_size),
577
+ )
578
+ self.output = Swinv2SelfOutput(config, dim)
579
+ self.pruned_heads = set()
580
+
581
+ def prune_heads(self, heads):
582
+ if len(heads) == 0:
583
+ return
584
+ heads, index = find_pruneable_heads_and_indices(
585
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
586
+ )
587
+
588
+ # Prune linear layers
589
+ self.self.query = prune_linear_layer(self.self.query, index)
590
+ self.self.key = prune_linear_layer(self.self.key, index)
591
+ self.self.value = prune_linear_layer(self.self.value, index)
592
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
593
+
594
+ # Update hyper params and store pruned heads
595
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
596
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
597
+ self.pruned_heads = self.pruned_heads.union(heads)
598
+
599
+ def forward(
600
+ self,
601
+ hidden_states: torch.Tensor,
602
+ attention_mask: Optional[torch.FloatTensor] = None,
603
+ head_mask: Optional[torch.FloatTensor] = None,
604
+ output_attentions: Optional[bool] = False,
605
+ ) -> Tuple[torch.Tensor]:
606
+ self_outputs = self.self(hidden_states, attention_mask, head_mask, output_attentions)
607
+ attention_output = self.output(self_outputs[0], hidden_states)
608
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
609
+ return outputs
610
+
611
+
612
+ # Copied from transformers.models.swin.modeling_swin.SwinIntermediate with Swin->Swinv2
613
+ class Swinv2Intermediate(nn.Module):
614
+ def __init__(self, config, dim):
615
+ super().__init__()
616
+ self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
617
+ if isinstance(config.hidden_act, str):
618
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
619
+ else:
620
+ self.intermediate_act_fn = config.hidden_act
621
+
622
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
623
+ hidden_states = self.dense(hidden_states)
624
+ hidden_states = self.intermediate_act_fn(hidden_states)
625
+ return hidden_states
626
+
627
+
628
+ # Copied from transformers.models.swin.modeling_swin.SwinOutput with Swin->Swinv2
629
+ class Swinv2Output(nn.Module):
630
+ def __init__(self, config, dim):
631
+ super().__init__()
632
+ self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
633
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
634
+
635
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
636
+ hidden_states = self.dense(hidden_states)
637
+ hidden_states = self.dropout(hidden_states)
638
+ return hidden_states
639
+
640
+
641
+ class Swinv2Layer(nn.Module):
642
+ def __init__(self, config, dim, input_resolution, num_heads, shift_size=0, pretrained_window_size=0):
643
+ super().__init__()
644
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
645
+ self.shift_size = shift_size
646
+ self.window_size = config.window_size
647
+ self.input_resolution = input_resolution
648
+ self.set_shift_and_window_size(input_resolution)
649
+ self.attention = Swinv2Attention(
650
+ config=config,
651
+ dim=dim,
652
+ num_heads=num_heads,
653
+ window_size=self.window_size,
654
+ pretrained_window_size=pretrained_window_size
655
+ if isinstance(pretrained_window_size, collections.abc.Iterable)
656
+ else (pretrained_window_size, pretrained_window_size),
657
+ )
658
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
659
+ self.drop_path = Swinv2DropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
660
+ self.intermediate = Swinv2Intermediate(config, dim)
661
+ self.output = Swinv2Output(config, dim)
662
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
663
+
664
+ def set_shift_and_window_size(self, input_resolution):
665
+ target_window_size = (
666
+ self.window_size
667
+ if isinstance(self.window_size, collections.abc.Iterable)
668
+ else (self.window_size, self.window_size)
669
+ )
670
+ target_shift_size = (
671
+ self.shift_size
672
+ if isinstance(self.shift_size, collections.abc.Iterable)
673
+ else (self.shift_size, self.shift_size)
674
+ )
675
+ window_dim = input_resolution[0].item() if torch.is_tensor(input_resolution[0]) else input_resolution[0]
676
+ self.window_size = window_dim if window_dim <= target_window_size[0] else target_window_size[0]
677
+ self.shift_size = (
678
+ 0
679
+ if input_resolution
680
+ <= (
681
+ self.window_size
682
+ if isinstance(self.window_size, collections.abc.Iterable)
683
+ else (self.window_size, self.window_size)
684
+ )
685
+ else target_shift_size[0]
686
+ )
687
+
688
+ def get_attn_mask(self, height, width, dtype):
689
+ if self.shift_size > 0:
690
+ # calculate attention mask for shifted window multihead self attention
691
+ img_mask = torch.zeros((1, height, width, 1), dtype=dtype)
692
+ height_slices = (
693
+ slice(0, -self.window_size),
694
+ slice(-self.window_size, -self.shift_size),
695
+ slice(-self.shift_size, None),
696
+ )
697
+ width_slices = (
698
+ slice(0, -self.window_size),
699
+ slice(-self.window_size, -self.shift_size),
700
+ slice(-self.shift_size, None),
701
+ )
702
+ count = 0
703
+ for height_slice in height_slices:
704
+ for width_slice in width_slices:
705
+ img_mask[:, height_slice, width_slice, :] = count
706
+ count += 1
707
+
708
+ mask_windows = window_partition(img_mask, self.window_size)
709
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
710
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
711
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
712
+ else:
713
+ attn_mask = None
714
+ return attn_mask
715
+
716
+ def maybe_pad(self, hidden_states, height, width):
717
+ pad_right = (self.window_size - width % self.window_size) % self.window_size
718
+ pad_bottom = (self.window_size - height % self.window_size) % self.window_size
719
+ pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
720
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
721
+ return hidden_states, pad_values
722
+
723
+ def forward(
724
+ self,
725
+ hidden_states: torch.Tensor,
726
+ input_dimensions: Tuple[int, int],
727
+ head_mask: Optional[torch.FloatTensor] = None,
728
+ output_attentions: Optional[bool] = False,
729
+ always_partition: Optional[bool] = False,
730
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
731
+ if not always_partition:
732
+ self.set_shift_and_window_size(input_dimensions)
733
+ else:
734
+ pass
735
+ height, width = input_dimensions
736
+ batch_size, _, channels = hidden_states.size()
737
+ shortcut = hidden_states
738
+
739
+ # pad hidden_states to multiples of window size
740
+ hidden_states = hidden_states.view(batch_size, height, width, channels)
741
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
742
+ _, height_pad, width_pad, _ = hidden_states.shape
743
+ # cyclic shift
744
+ if self.shift_size > 0:
745
+ shifted_hidden_states = torch.roll(hidden_states, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
746
+ else:
747
+ shifted_hidden_states = hidden_states
748
+
749
+ # partition windows
750
+ hidden_states_windows = window_partition(shifted_hidden_states, self.window_size)
751
+ hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
752
+ attn_mask = self.get_attn_mask(height_pad, width_pad, dtype=hidden_states.dtype)
753
+ if attn_mask is not None:
754
+ attn_mask = attn_mask.to(hidden_states_windows.device)
755
+
756
+ attention_outputs = self.attention(
757
+ hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions
758
+ )
759
+
760
+ attention_output = attention_outputs[0]
761
+
762
+ attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
763
+ shifted_windows = window_reverse(attention_windows, self.window_size, height_pad, width_pad)
764
+
765
+ # reverse cyclic shift
766
+ if self.shift_size > 0:
767
+ attention_windows = torch.roll(shifted_windows, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
768
+ else:
769
+ attention_windows = shifted_windows
770
+
771
+ was_padded = pad_values[3] > 0 or pad_values[5] > 0
772
+ if was_padded:
773
+ attention_windows = attention_windows[:, :height, :width, :].contiguous()
774
+
775
+ attention_windows = attention_windows.view(batch_size, height * width, channels)
776
+ hidden_states = self.layernorm_before(attention_windows)
777
+ hidden_states = shortcut + self.drop_path(hidden_states)
778
+
779
+ layer_output = self.intermediate(hidden_states)
780
+ layer_output = self.output(layer_output)
781
+ layer_output = hidden_states + self.drop_path(self.layernorm_after(layer_output))
782
+
783
+ layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
784
+ return layer_outputs
785
+
786
+
787
+ class Swinv2Stage(nn.Module):
788
+ def __init__(
789
+ self, config, dim, input_resolution, depth, num_heads, drop_path, downsample, pretrained_window_size=0
790
+ ):
791
+ super().__init__()
792
+ self.config = config
793
+ self.dim = dim
794
+ self.blocks = nn.ModuleList(
795
+ [
796
+ Swinv2Layer(
797
+ config=config,
798
+ dim=dim,
799
+ input_resolution=input_resolution,
800
+ num_heads=num_heads,
801
+ shift_size=0 if (i % 2 == 0) else config.window_size // 2,
802
+ pretrained_window_size=pretrained_window_size,
803
+ )
804
+ for i in range(depth)
805
+ ]
806
+ )
807
+
808
+ # patch merging layer
809
+ if downsample is not None:
810
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=nn.LayerNorm)
811
+ else:
812
+ self.downsample = None
813
+
814
+ self.pointing = False
815
+
816
+ # Copied from transformers.models.swin.modeling_swin.SwinStage.forward
817
+ def forward(
818
+ self,
819
+ hidden_states: torch.Tensor,
820
+ input_dimensions: Tuple[int, int],
821
+ head_mask: Optional[torch.FloatTensor] = None,
822
+ output_attentions: Optional[bool] = False,
823
+ always_partition: Optional[bool] = False,
824
+ ) -> Tuple[torch.Tensor]:
825
+ height, width = input_dimensions
826
+ for i, layer_module in enumerate(self.blocks):
827
+ layer_head_mask = head_mask[i] if head_mask is not None else None
828
+
829
+ layer_outputs = layer_module(
830
+ hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
831
+ )
832
+
833
+ hidden_states = layer_outputs[0]
834
+
835
+ hidden_states_before_downsampling = hidden_states
836
+ if self.downsample is not None:
837
+ height_downsampled, width_downsampled = (height + 1) // 2, (width + 1) // 2
838
+ output_dimensions = (height, width, height_downsampled, width_downsampled)
839
+ hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
840
+ else:
841
+ output_dimensions = (height, width, height, width)
842
+
843
+ stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
844
+
845
+ if output_attentions:
846
+ stage_outputs += layer_outputs[1:]
847
+ return stage_outputs
848
+
849
+
850
+ class Swinv2Encoder(nn.Module):
851
+ def __init__(self, config, grid_size, pretrained_window_sizes=(0, 0, 0, 0)):
852
+ super().__init__()
853
+ self.num_layers = len(config.depths)
854
+ self.config = config
855
+ if self.config.pretrained_window_sizes is not None:
856
+ pretrained_window_sizes = config.pretrained_window_sizes
857
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
858
+ self.layers = nn.ModuleList(
859
+ [
860
+ Swinv2Stage(
861
+ config=config,
862
+ dim=int(config.embed_dim * 2**i_layer),
863
+ input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
864
+ depth=config.depths[i_layer],
865
+ num_heads=config.num_heads[i_layer],
866
+ drop_path=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
867
+ downsample=Swinv2PatchMerging if (i_layer < self.num_layers - 1) else None,
868
+ pretrained_window_size=pretrained_window_sizes[i_layer],
869
+ )
870
+ for i_layer in range(self.num_layers)
871
+ ]
872
+ )
873
+
874
+ self.gradient_checkpointing = False
875
+
876
+ # Copied from transformers.models.swin.modeling_swin.SwinEncoder.forward with SwinEncoderOutput->Swinv2EncoderOutput
877
+ def forward(
878
+ self,
879
+ hidden_states: torch.Tensor,
880
+ input_dimensions: Tuple[int, int],
881
+ head_mask: Optional[torch.FloatTensor] = None,
882
+ output_attentions: Optional[bool] = False,
883
+ output_hidden_states: Optional[bool] = False,
884
+ output_hidden_states_before_downsampling: Optional[bool] = False,
885
+ always_partition: Optional[bool] = False,
886
+ return_dict: Optional[bool] = True,
887
+ ) -> Union[Tuple, Swinv2EncoderOutput]:
888
+ all_hidden_states = () if output_hidden_states else None
889
+ all_reshaped_hidden_states = () if output_hidden_states else None
890
+ all_self_attentions = () if output_attentions else None
891
+
892
+ if output_hidden_states:
893
+ batch_size, _, hidden_size = hidden_states.shape
894
+ # rearrange b (h w) c -> b c h w
895
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
896
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
897
+ all_hidden_states += (hidden_states,)
898
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
899
+
900
+ for i, layer_module in enumerate(self.layers):
901
+ layer_head_mask = head_mask[i] if head_mask is not None else None
902
+
903
+ if self.gradient_checkpointing and self.training:
904
+
905
+ def create_custom_forward(module):
906
+ def custom_forward(*inputs):
907
+ return module(*inputs, output_attentions)
908
+
909
+ return custom_forward
910
+
911
+ layer_outputs = torch.utils.checkpoint.checkpoint(
912
+ create_custom_forward(layer_module), hidden_states, input_dimensions, layer_head_mask
913
+ )
914
+ else:
915
+ layer_outputs = layer_module(
916
+ hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
917
+ )
918
+
919
+ hidden_states = layer_outputs[0]
920
+ hidden_states_before_downsampling = layer_outputs[1]
921
+ output_dimensions = layer_outputs[2]
922
+
923
+ input_dimensions = (output_dimensions[-2], output_dimensions[-1])
924
+
925
+ if output_hidden_states and output_hidden_states_before_downsampling:
926
+ batch_size, _, hidden_size = hidden_states_before_downsampling.shape
927
+ # rearrange b (h w) c -> b c h w
928
+ # here we use the original (not downsampled) height and width
929
+ reshaped_hidden_state = hidden_states_before_downsampling.view(
930
+ batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
931
+ )
932
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
933
+ all_hidden_states += (hidden_states_before_downsampling,)
934
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
935
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
936
+ batch_size, _, hidden_size = hidden_states.shape
937
+ # rearrange b (h w) c -> b c h w
938
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
939
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
940
+ all_hidden_states += (hidden_states,)
941
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
942
+
943
+ if output_attentions:
944
+ all_self_attentions += layer_outputs[3:]
945
+
946
+ if not return_dict:
947
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
948
+
949
+ return Swinv2EncoderOutput(
950
+ last_hidden_state=hidden_states,
951
+ hidden_states=all_hidden_states,
952
+ attentions=all_self_attentions,
953
+ reshaped_hidden_states=all_reshaped_hidden_states,
954
+ )
955
+
956
+
957
+ # Copied from transformers.models.swin.modeling_swin.SwinPreTrainedModel with Swin->Swinv2,swin->swinv2
958
+ class Swinv2PreTrainedModel(PreTrainedModel):
959
+ """
960
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
961
+ models.
962
+ """
963
+
964
+ config_class = Swinv2Config
965
+ base_model_prefix = "swinv2"
966
+ main_input_name = "pixel_values"
967
+ supports_gradient_checkpointing = True
968
+
969
+ def _init_weights(self, module):
970
+ """Initialize the weights"""
971
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
972
+ # Slightly different from the TF version which uses truncated_normal for initialization
973
+ # cf https://github.com/pytorch/pytorch/pull/5617
974
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
975
+ if module.bias is not None:
976
+ module.bias.data.zero_()
977
+ elif isinstance(module, nn.LayerNorm):
978
+ module.bias.data.zero_()
979
+ module.weight.data.fill_(1.0)
980
+
981
+ def _set_gradient_checkpointing(self, module, value=False):
982
+ if isinstance(module, Swinv2Encoder):
983
+ module.gradient_checkpointing = value
984
+
985
+
986
+ SWINV2_START_DOCSTRING = r"""
987
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
988
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
989
+ behavior.
990
+
991
+ Parameters:
992
+ config ([`Swinv2Config`]): Model configuration class with all the parameters of the model.
993
+ Initializing with a config file does not load the weights associated with the model, only the
994
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
995
+ """
996
+
997
+ SWINV2_INPUTS_DOCSTRING = r"""
998
+ Args:
999
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1000
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ViTImageProcessor.__call__`]
1001
+ for details.
1002
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1003
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1004
+
1005
+ - 1 indicates the head is **not masked**,
1006
+ - 0 indicates the head is **masked**.
1007
+
1008
+ output_attentions (`bool`, *optional*):
1009
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1010
+ tensors for more detail.
1011
+ output_hidden_states (`bool`, *optional*):
1012
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1013
+ more detail.
1014
+ return_dict (`bool`, *optional*):
1015
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1016
+ """
1017
+
1018
+
1019
+ @add_start_docstrings(
1020
+ "The bare Swinv2 Model transformer outputting raw hidden-states without any specific head on top.",
1021
+ SWINV2_START_DOCSTRING,
1022
+ )
1023
+ # Copied from transformers.models.swin.modeling_swin.SwinModel with SWIN->SWINV2,Swin->Swinv2
1024
+ class Swinv2Model(Swinv2PreTrainedModel):
1025
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
1026
+ super().__init__(config)
1027
+ self.config = config
1028
+ self.num_layers = len(config.depths)
1029
+ self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
1030
+
1031
+ self.embeddings = Swinv2Embeddings(config, use_mask_token=use_mask_token)
1032
+ self.encoder = Swinv2Encoder(config, self.embeddings.patch_grid)
1033
+
1034
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
1035
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
1036
+
1037
+ # Initialize weights and apply final processing
1038
+ self.post_init()
1039
+
1040
+ def get_input_embeddings(self):
1041
+ return self.embeddings.patch_embeddings
1042
+
1043
+ def _prune_heads(self, heads_to_prune):
1044
+ """
1045
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1046
+ class PreTrainedModel
1047
+ """
1048
+ for layer, heads in heads_to_prune.items():
1049
+ self.encoder.layer[layer].attention.prune_heads(heads)
1050
+
1051
+ @add_start_docstrings_to_model_forward(SWINV2_INPUTS_DOCSTRING)
1052
+ @add_code_sample_docstrings(
1053
+ checkpoint=_CHECKPOINT_FOR_DOC,
1054
+ output_type=Swinv2ModelOutput,
1055
+ config_class=_CONFIG_FOR_DOC,
1056
+ modality="vision",
1057
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
1058
+ )
1059
+ def forward(
1060
+ self,
1061
+ pixel_values: Optional[torch.FloatTensor] = None,
1062
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
1063
+ head_mask: Optional[torch.FloatTensor] = None,
1064
+ output_attentions: Optional[bool] = None,
1065
+ output_hidden_states: Optional[bool] = None,
1066
+ return_dict: Optional[bool] = None,
1067
+ ) -> Union[Tuple, Swinv2ModelOutput]:
1068
+ r"""
1069
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
1070
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
1071
+ """
1072
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1073
+ output_hidden_states = (
1074
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1075
+ )
1076
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1077
+
1078
+ if pixel_values is None:
1079
+ raise ValueError("You have to specify pixel_values")
1080
+
1081
+ # Prepare head mask if needed
1082
+ # 1.0 in head_mask indicate we keep the head
1083
+ # attention_probs has shape bsz x n_heads x N x N
1084
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1085
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1086
+ head_mask = self.get_head_mask(head_mask, len(self.config.depths))
1087
+
1088
+ embedding_output, input_dimensions = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
1089
+
1090
+ encoder_outputs = self.encoder(
1091
+ embedding_output,
1092
+ input_dimensions,
1093
+ head_mask=head_mask,
1094
+ output_attentions=output_attentions,
1095
+ output_hidden_states=output_hidden_states,
1096
+ return_dict=return_dict,
1097
+ )
1098
+
1099
+ sequence_output = encoder_outputs[0]
1100
+ sequence_output = self.layernorm(sequence_output)
1101
+
1102
+ pooled_output = None
1103
+ if self.pooler is not None:
1104
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
1105
+ pooled_output = torch.flatten(pooled_output, 1)
1106
+
1107
+ if not return_dict:
1108
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
1109
+
1110
+ return output
1111
+
1112
+ return Swinv2ModelOutput(
1113
+ last_hidden_state=sequence_output,
1114
+ pooler_output=pooled_output,
1115
+ hidden_states=encoder_outputs.hidden_states,
1116
+ attentions=encoder_outputs.attentions,
1117
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
1118
+ )
1119
+
1120
+
1121
+ @add_start_docstrings(
1122
+ """Swinv2 Model with a decoder on top for masked image modeling, as proposed in
1123
+ [SimMIM](https://arxiv.org/abs/2111.09886).
1124
+
1125
+ <Tip>
1126
+
1127
+ Note that we provide a script to pre-train this model on custom data in our [examples
1128
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
1129
+
1130
+ </Tip>
1131
+ """,
1132
+ SWINV2_START_DOCSTRING,
1133
+ )
1134
+ # Copied from transformers.models.swin.modeling_swin.SwinForMaskedImageModeling with swin->swinv2, base-simmim-window6-192->tiny-patch4-window8-256,SWIN->SWINV2,Swin->Swinv2,192->256
1135
+ class Swinv2ForMaskedImageModeling(Swinv2PreTrainedModel):
1136
+ def __init__(self, config):
1137
+ super().__init__(config)
1138
+
1139
+ self.swinv2 = Swinv2Model(config, add_pooling_layer=False, use_mask_token=True)
1140
+
1141
+ num_features = int(config.embed_dim * 2 ** (config.num_layers - 1))
1142
+ self.decoder = nn.Sequential(
1143
+ nn.Conv2d(
1144
+ in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
1145
+ ),
1146
+ nn.PixelShuffle(config.encoder_stride),
1147
+ )
1148
+
1149
+ # Initialize weights and apply final processing
1150
+ self.post_init()
1151
+
1152
+ @add_start_docstrings_to_model_forward(SWINV2_INPUTS_DOCSTRING)
1153
+ @replace_return_docstrings(output_type=Swinv2MaskedImageModelingOutput, config_class=_CONFIG_FOR_DOC)
1154
+ def forward(
1155
+ self,
1156
+ pixel_values: Optional[torch.FloatTensor] = None,
1157
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
1158
+ head_mask: Optional[torch.FloatTensor] = None,
1159
+ output_attentions: Optional[bool] = None,
1160
+ output_hidden_states: Optional[bool] = None,
1161
+ return_dict: Optional[bool] = None,
1162
+ ) -> Union[Tuple, Swinv2MaskedImageModelingOutput]:
1163
+ r"""
1164
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
1165
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
1166
+
1167
+ Returns:
1168
+
1169
+ Examples:
1170
+ ```python
1171
+ >>> from transformers import AutoImageProcessor, Swinv2ForMaskedImageModeling
1172
+ >>> import torch
1173
+ >>> from PIL import Image
1174
+ >>> import requests
1175
+
1176
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1177
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1178
+
1179
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
1180
+ >>> model = Swinv2ForMaskedImageModeling.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
1181
+
1182
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
1183
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
1184
+ >>> # create random boolean mask of shape (batch_size, num_patches)
1185
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
1186
+
1187
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
1188
+ >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
1189
+ >>> list(reconstructed_pixel_values.shape)
1190
+ [1, 3, 256, 256]
1191
+ ```"""
1192
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1193
+
1194
+ outputs = self.swinv2(
1195
+ pixel_values,
1196
+ bool_masked_pos=bool_masked_pos,
1197
+ head_mask=head_mask,
1198
+ output_attentions=output_attentions,
1199
+ output_hidden_states=output_hidden_states,
1200
+ return_dict=return_dict,
1201
+ )
1202
+
1203
+ sequence_output = outputs[0]
1204
+ # Reshape to (batch_size, num_channels, height, width)
1205
+ sequence_output = sequence_output.transpose(1, 2)
1206
+ batch_size, num_channels, sequence_length = sequence_output.shape
1207
+ height = width = math.floor(sequence_length**0.5)
1208
+ sequence_output = sequence_output.reshape(batch_size, num_channels, height, width)
1209
+
1210
+ # Reconstruct pixel values
1211
+ reconstructed_pixel_values = self.decoder(sequence_output)
1212
+
1213
+ masked_im_loss = None
1214
+ if bool_masked_pos is not None:
1215
+ size = self.config.image_size // self.config.patch_size
1216
+ bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
1217
+ mask = (
1218
+ bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
1219
+ .repeat_interleave(self.config.patch_size, 2)
1220
+ .unsqueeze(1)
1221
+ .contiguous()
1222
+ )
1223
+ reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
1224
+ masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
1225
+
1226
+ if not return_dict:
1227
+ output = (reconstructed_pixel_values,) + outputs[2:]
1228
+ return ((masked_im_loss,) + output) if masked_im_loss is not None else output
1229
+
1230
+ return Swinv2MaskedImageModelingOutput(
1231
+ loss=masked_im_loss,
1232
+ reconstruction=reconstructed_pixel_values,
1233
+ hidden_states=outputs.hidden_states,
1234
+ attentions=outputs.attentions,
1235
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
1236
+ )
1237
+
1238
+
1239
+ @add_start_docstrings(
1240
+ """
1241
+ Swinv2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state
1242
+ of the [CLS] token) e.g. for ImageNet.
1243
+ """,
1244
+ SWINV2_START_DOCSTRING,
1245
+ )
1246
+ # Copied from transformers.models.swin.modeling_swin.SwinForImageClassification with SWIN->SWINV2,Swin->Swinv2,swin->swinv2
1247
+ class Swinv2ForImageClassification(Swinv2PreTrainedModel):
1248
+ def __init__(self, config):
1249
+ super().__init__(config)
1250
+
1251
+ self.num_labels = config.num_labels
1252
+ self.swinv2 = Swinv2Model(config)
1253
+
1254
+ # Classifier head
1255
+ self.classifier = (
1256
+ nn.Linear(self.swinv2.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
1257
+ )
1258
+
1259
+ # Initialize weights and apply final processing
1260
+ self.post_init()
1261
+
1262
+ @add_start_docstrings_to_model_forward(SWINV2_INPUTS_DOCSTRING)
1263
+ @add_code_sample_docstrings(
1264
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
1265
+ output_type=Swinv2ImageClassifierOutput,
1266
+ config_class=_CONFIG_FOR_DOC,
1267
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
1268
+ )
1269
+ def forward(
1270
+ self,
1271
+ pixel_values: Optional[torch.FloatTensor] = None,
1272
+ head_mask: Optional[torch.FloatTensor] = None,
1273
+ labels: Optional[torch.LongTensor] = None,
1274
+ output_attentions: Optional[bool] = None,
1275
+ output_hidden_states: Optional[bool] = None,
1276
+ return_dict: Optional[bool] = None,
1277
+ ) -> Union[Tuple, Swinv2ImageClassifierOutput]:
1278
+ r"""
1279
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1280
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1281
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1282
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1283
+ """
1284
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1285
+
1286
+ outputs = self.swinv2(
1287
+ pixel_values,
1288
+ head_mask=head_mask,
1289
+ output_attentions=output_attentions,
1290
+ output_hidden_states=output_hidden_states,
1291
+ return_dict=return_dict,
1292
+ )
1293
+
1294
+ pooled_output = outputs[1]
1295
+
1296
+ logits = self.classifier(pooled_output)
1297
+
1298
+ loss = None
1299
+ if labels is not None:
1300
+ if self.config.problem_type is None:
1301
+ if self.num_labels == 1:
1302
+ self.config.problem_type = "regression"
1303
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1304
+ self.config.problem_type = "single_label_classification"
1305
+ else:
1306
+ self.config.problem_type = "multi_label_classification"
1307
+
1308
+ if self.config.problem_type == "regression":
1309
+ loss_fct = MSELoss()
1310
+ if self.num_labels == 1:
1311
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1312
+ else:
1313
+ loss = loss_fct(logits, labels)
1314
+ elif self.config.problem_type == "single_label_classification":
1315
+ loss_fct = CrossEntropyLoss()
1316
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1317
+ elif self.config.problem_type == "multi_label_classification":
1318
+ loss_fct = BCEWithLogitsLoss()
1319
+ loss = loss_fct(logits, labels)
1320
+
1321
+ if not return_dict:
1322
+ output = (logits,) + outputs[2:]
1323
+ return ((loss,) + output) if loss is not None else output
1324
+
1325
+ return Swinv2ImageClassifierOutput(
1326
+ loss=loss,
1327
+ logits=logits,
1328
+ hidden_states=outputs.hidden_states,
1329
+ attentions=outputs.attentions,
1330
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
1331
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/switch_transformers/configuration_switch_transformers.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022, Google 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
+ """ Switch Transformers model configuration"""
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ SWITCH_TRANSFORMERS_PRETRAINED_CONFIG_ARCHIVE_MAP = {
23
+ "google/switch-base-8": "https://huggingface.co/google/switch-base-8/blob/main/config.json",
24
+ }
25
+
26
+
27
+ class SwitchTransformersConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`SwitchTransformersModel`]. It is used to
30
+ instantiate a SwitchTransformers model according to the specified arguments, defining the model architecture.
31
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the
32
+ SwitchTransformers [google/switch-base-8](https://huggingface.co/google/switch-base-8) 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 32128):
39
+ Vocabulary size of the SwitchTransformers model. Defines the number of different tokens that can be
40
+ represented by the `inputs_ids` passed when calling [`SwitchTransformersModel`].
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 2048):
47
+ Size of the intermediate feed forward layer in each `SwitchTransformersBlock`.
48
+ expert_capacity (`int`, *optional*, defaults to 64):
49
+ Number of tokens that can be stored in each expert. If set to 1, the model will behave like a regular
50
+ Transformer.
51
+ num_layers (`int`, *optional*, defaults to 12):
52
+ Number of dense hidden layers in the Transformer encoder layer.
53
+ num_sparse_encoder_layers (`int`, *optional*, defaults to 6):
54
+ Number of sparse (MoE) dense hidden layers in the Transformer encoder layer.
55
+ num_decoder_layers (`int`, *optional*, defaults to 12):
56
+ Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
57
+ num_sparse_decoder_layers (`int`, *optional*, defaults to 12):
58
+ Number of sparse (MoE) dense hidden layers in the Transformer decoder layer.
59
+ num_heads (`int`, *optional*, defaults to 8):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ num_experts (`int`, *optional*, defaults to 8):
62
+ Number of experts for each SwitchTransformer layer.
63
+ router_type (`str`, *optional*, defaults to `"tokens_masked"`):
64
+ Router type - choose between `"tokens_masked", `"tokens_scatter"` and `"experts_masked"`.
65
+ router_bias (`bool`, *optional*, defaults to `True`):
66
+ Whether to add a bias to the router.
67
+ router_jitter_noise (`float`, *optional*, defaults to 0.1):
68
+ Amount of noise to add to the router.
69
+ router_dtype (`str`, *optional*, default to `"float32"`):
70
+ The `dtype` used for the routers. It is preferable to keep the `dtype` to `"float32"` as specified in the
71
+ *selective precision* discussion in [the paper](https://arxiv.org/abs/2101.03961).
72
+ router_ignore_padding_tokens (`bool`, *optional*, defaults to `False`):
73
+ Whether to ignore padding tokens when routing.
74
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
75
+ The number of buckets to use for each attention layer.
76
+ relative_attention_max_distance (`int`, *optional*, defaults to 128):
77
+ The maximum distance of the longer sequences for the bucket separation.
78
+ dropout_rate (`float`, *optional*, defaults to 0.1):
79
+ The ratio for all dropout layers.
80
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
81
+ The epsilon used by the layer normalization layers.
82
+ router_z_loss_coef (`float`, *optional*, defaults to 0.001):
83
+ The z loss factor for the total loss.
84
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
85
+ The aux loss factor for the total loss.
86
+ initializer_factor (`float`, *optional*, defaults to 1):
87
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
88
+ testing).
89
+ feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
90
+ Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. SwitchTransformersv1.1
91
+ uses the `"gated-gelu"` feed forward projection. Original SwitchTransformers uses `"relu"`.
92
+ add_router_probs (`bool`, *optional*, defaults to `False`):
93
+ Whether to output router probabilities to compute router auxiliary loss.
94
+ use_cache (`bool`, *optional*, defaults to `True`):
95
+ Whether or not the model should return the last key/values attentions (not used by all models).
96
+ """
97
+ model_type = "switch_transformers"
98
+ keys_to_ignore_at_inference = ["past_key_values"]
99
+ attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
100
+
101
+ def __init__(
102
+ self,
103
+ vocab_size=32128,
104
+ d_model=768,
105
+ d_kv=64,
106
+ d_ff=2048,
107
+ expert_capacity=64,
108
+ num_layers=12,
109
+ num_sparse_encoder_layers=3,
110
+ num_decoder_layers=12,
111
+ num_sparse_decoder_layers=3,
112
+ num_heads=12,
113
+ num_experts=8,
114
+ router_bias=False,
115
+ router_jitter_noise=0.01,
116
+ router_dtype="float32",
117
+ router_ignore_padding_tokens=False,
118
+ relative_attention_num_buckets=32,
119
+ relative_attention_max_distance=128,
120
+ dropout_rate=0.1,
121
+ layer_norm_epsilon=1e-6,
122
+ router_z_loss_coef=0.001,
123
+ router_aux_loss_coef=0.001,
124
+ initializer_factor=1.0,
125
+ feed_forward_proj="relu",
126
+ is_encoder_decoder=True,
127
+ add_router_probs=False,
128
+ use_cache=True,
129
+ pad_token_id=0,
130
+ eos_token_id=1,
131
+ **kwargs,
132
+ ):
133
+ self.vocab_size = vocab_size
134
+ self.d_model = d_model
135
+ self.d_kv = d_kv
136
+ self.d_ff = d_ff
137
+
138
+ self.num_sparse_encoder_layers = num_sparse_encoder_layers
139
+
140
+ self.num_layers = num_layers
141
+ self.num_decoder_layers = (
142
+ num_decoder_layers if num_decoder_layers is not None else self.num_layers
143
+ ) # default = symmetry
144
+ self.num_sparse_decoder_layers = num_sparse_decoder_layers
145
+
146
+ # This tells us, each how many encoder layer we'll have to set a sparse layer.
147
+ if self.num_sparse_encoder_layers > 0:
148
+ self.encoder_sparse_step = self.num_layers // self.num_sparse_encoder_layers
149
+ else:
150
+ self.encoder_sparse_step = self.num_layers # HACK: this will create 0 sparse layers
151
+
152
+ # This tells us, each how many encoder layer we'll have to set a sparse layer.
153
+ if self.num_sparse_decoder_layers > 0:
154
+ self.decoder_sparse_step = self.num_decoder_layers // self.num_sparse_decoder_layers
155
+ else:
156
+ self.decoder_sparse_step = self.num_decoder_layers # HACK: this will create 0 sparse layers
157
+
158
+ self.num_heads = num_heads
159
+ self.num_experts = num_experts
160
+ self.expert_capacity = expert_capacity
161
+ self.router_bias = router_bias
162
+ self.router_jitter_noise = router_jitter_noise
163
+ if router_dtype not in ["float32", "float16", "bfloat16"]:
164
+ raise ValueError(f"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}")
165
+ self.router_dtype = router_dtype
166
+
167
+ self.router_ignore_padding_tokens = router_ignore_padding_tokens
168
+ self.relative_attention_num_buckets = relative_attention_num_buckets
169
+ self.relative_attention_max_distance = relative_attention_max_distance
170
+
171
+ self.dropout_rate = dropout_rate
172
+ self.layer_norm_epsilon = layer_norm_epsilon
173
+ self.initializer_factor = initializer_factor
174
+ self.feed_forward_proj = feed_forward_proj
175
+ self.use_cache = use_cache
176
+ self.add_router_probs = add_router_probs
177
+
178
+ self.router_z_loss_coef = router_z_loss_coef
179
+ self.router_aux_loss_coef = router_aux_loss_coef
180
+
181
+ act_info = self.feed_forward_proj.split("-")
182
+ self.dense_act_fn = act_info[-1]
183
+ self.is_gated_act = act_info[0] == "gated"
184
+
185
+ if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
186
+ raise ValueError(
187
+ f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
188
+ "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
189
+ "'gated-gelu' or 'relu'"
190
+ )
191
+
192
+ # for backwards compatibility
193
+ if feed_forward_proj == "gated-gelu":
194
+ self.dense_act_fn = "gelu_new"
195
+
196
+ super().__init__(
197
+ pad_token_id=pad_token_id,
198
+ eos_token_id=eos_token_id,
199
+ is_encoder_decoder=is_encoder_decoder,
200
+ **kwargs,
201
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/__init__.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 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
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_flax_available,
21
+ is_sentencepiece_available,
22
+ is_tf_available,
23
+ is_tokenizers_available,
24
+ is_torch_available,
25
+ )
26
+
27
+
28
+ _import_structure = {"configuration_t5": ["T5_PRETRAINED_CONFIG_ARCHIVE_MAP", "T5Config", "T5OnnxConfig"]}
29
+
30
+ try:
31
+ if not is_sentencepiece_available():
32
+ raise OptionalDependencyNotAvailable()
33
+ except OptionalDependencyNotAvailable:
34
+ pass
35
+ else:
36
+ _import_structure["tokenization_t5"] = ["T5Tokenizer"]
37
+
38
+ try:
39
+ if not is_tokenizers_available():
40
+ raise OptionalDependencyNotAvailable()
41
+ except OptionalDependencyNotAvailable:
42
+ pass
43
+ else:
44
+ _import_structure["tokenization_t5_fast"] = ["T5TokenizerFast"]
45
+
46
+ try:
47
+ if not is_torch_available():
48
+ raise OptionalDependencyNotAvailable()
49
+ except OptionalDependencyNotAvailable:
50
+ pass
51
+ else:
52
+ _import_structure["modeling_t5"] = [
53
+ "T5_PRETRAINED_MODEL_ARCHIVE_LIST",
54
+ "T5EncoderModel",
55
+ "T5ForConditionalGeneration",
56
+ "T5Model",
57
+ "T5PreTrainedModel",
58
+ "load_tf_weights_in_t5",
59
+ ]
60
+
61
+ try:
62
+ if not is_tf_available():
63
+ raise OptionalDependencyNotAvailable()
64
+ except OptionalDependencyNotAvailable:
65
+ pass
66
+ else:
67
+ _import_structure["modeling_tf_t5"] = [
68
+ "TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST",
69
+ "TFT5EncoderModel",
70
+ "TFT5ForConditionalGeneration",
71
+ "TFT5Model",
72
+ "TFT5PreTrainedModel",
73
+ ]
74
+
75
+ try:
76
+ if not is_flax_available():
77
+ raise OptionalDependencyNotAvailable()
78
+ except OptionalDependencyNotAvailable:
79
+ pass
80
+ else:
81
+ _import_structure["modeling_flax_t5"] = [
82
+ "FlaxT5EncoderModel",
83
+ "FlaxT5ForConditionalGeneration",
84
+ "FlaxT5Model",
85
+ "FlaxT5PreTrainedModel",
86
+ ]
87
+
88
+
89
+ if TYPE_CHECKING:
90
+ from .configuration_t5 import T5_PRETRAINED_CONFIG_ARCHIVE_MAP, T5Config, T5OnnxConfig
91
+
92
+ try:
93
+ if not is_sentencepiece_available():
94
+ raise OptionalDependencyNotAvailable()
95
+ except OptionalDependencyNotAvailable:
96
+ pass
97
+ else:
98
+ from .tokenization_t5 import T5Tokenizer
99
+
100
+ try:
101
+ if not is_tokenizers_available():
102
+ raise OptionalDependencyNotAvailable()
103
+ except OptionalDependencyNotAvailable:
104
+ pass
105
+ else:
106
+ from .tokenization_t5_fast import T5TokenizerFast
107
+
108
+ try:
109
+ if not is_torch_available():
110
+ raise OptionalDependencyNotAvailable()
111
+ except OptionalDependencyNotAvailable:
112
+ pass
113
+ else:
114
+ from .modeling_t5 import (
115
+ T5_PRETRAINED_MODEL_ARCHIVE_LIST,
116
+ T5EncoderModel,
117
+ T5ForConditionalGeneration,
118
+ T5Model,
119
+ T5PreTrainedModel,
120
+ load_tf_weights_in_t5,
121
+ )
122
+
123
+ try:
124
+ if not is_tf_available():
125
+ raise OptionalDependencyNotAvailable()
126
+ except OptionalDependencyNotAvailable:
127
+ pass
128
+ else:
129
+ from .modeling_tf_t5 import (
130
+ TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST,
131
+ TFT5EncoderModel,
132
+ TFT5ForConditionalGeneration,
133
+ TFT5Model,
134
+ TFT5PreTrainedModel,
135
+ )
136
+
137
+ try:
138
+ if not is_flax_available():
139
+ raise OptionalDependencyNotAvailable()
140
+ except OptionalDependencyNotAvailable:
141
+ pass
142
+ else:
143
+ from .modeling_flax_t5 import (
144
+ FlaxT5EncoderModel,
145
+ FlaxT5ForConditionalGeneration,
146
+ FlaxT5Model,
147
+ FlaxT5PreTrainedModel,
148
+ )
149
+
150
+
151
+ else:
152
+ import sys
153
+
154
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/configuration_t5.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, 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
+ """ T5 model configuration"""
16
+ from typing import Mapping
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...onnx import OnnxSeq2SeqConfigWithPast
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ T5_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json",
27
+ "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json",
28
+ "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json",
29
+ "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json",
30
+ "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json",
31
+ }
32
+
33
+
34
+ class T5Config(PretrainedConfig):
35
+ r"""
36
+ This is the configuration class to store the configuration of a [`T5Model`] or a [`TFT5Model`]. It is used to
37
+ instantiate a T5 model according to the specified arguments, defining the model architecture. Instantiating a
38
+ configuration with the defaults will yield a similar configuration to that of the T5
39
+ [t5-small](https://huggingface.co/t5-small) architecture.
40
+
41
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
42
+ documentation from [`PretrainedConfig`] for more information.
43
+
44
+ Arguments:
45
+ vocab_size (`int`, *optional*, defaults to 32128):
46
+ Vocabulary size of the T5 model. Defines the number of different tokens that can be represented by the
47
+ `inputs_ids` passed when calling [`T5Model`] or [`TFT5Model`].
48
+ d_model (`int`, *optional*, defaults to 512):
49
+ Size of the encoder layers and the pooler layer.
50
+ d_kv (`int`, *optional*, defaults to 64):
51
+ Size of the key, query, value projections per attention head. The `inner_dim` of the projection layer will
52
+ be defined as `num_heads * d_kv`.
53
+ d_ff (`int`, *optional*, defaults to 2048):
54
+ Size of the intermediate feed forward layer in each `T5Block`.
55
+ num_layers (`int`, *optional*, defaults to 6):
56
+ Number of hidden layers in the Transformer encoder.
57
+ num_decoder_layers (`int`, *optional*):
58
+ Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
59
+ num_heads (`int`, *optional*, defaults to 8):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
62
+ The number of buckets to use for each attention layer.
63
+ relative_attention_max_distance (`int`, *optional*, defaults to 128):
64
+ The maximum distance of the longer sequences for the bucket separation.
65
+ dropout_rate (`float`, *optional*, defaults to 0.1):
66
+ The ratio for all dropout layers.
67
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
68
+ The epsilon used by the layer normalization layers.
69
+ initializer_factor (`float`, *optional*, defaults to 1):
70
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
71
+ testing).
72
+ feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
73
+ Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. T5v1.1 uses the
74
+ `"gated-gelu"` feed forward projection. Original T5 uses `"relu"`.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models).
77
+ """
78
+ model_type = "t5"
79
+ keys_to_ignore_at_inference = ["past_key_values"]
80
+ attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
81
+
82
+ def __init__(
83
+ self,
84
+ vocab_size=32128,
85
+ d_model=512,
86
+ d_kv=64,
87
+ d_ff=2048,
88
+ num_layers=6,
89
+ num_decoder_layers=None,
90
+ num_heads=8,
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="relu",
97
+ is_encoder_decoder=True,
98
+ use_cache=True,
99
+ pad_token_id=0,
100
+ eos_token_id=1,
101
+ **kwargs,
102
+ ):
103
+ self.vocab_size = vocab_size
104
+ self.d_model = d_model
105
+ self.d_kv = d_kv
106
+ self.d_ff = d_ff
107
+ self.num_layers = num_layers
108
+ self.num_decoder_layers = (
109
+ num_decoder_layers if num_decoder_layers is not None else self.num_layers
110
+ ) # default = symmetry
111
+ self.num_heads = num_heads
112
+ self.relative_attention_num_buckets = relative_attention_num_buckets
113
+ self.relative_attention_max_distance = relative_attention_max_distance
114
+ self.dropout_rate = dropout_rate
115
+ self.layer_norm_epsilon = layer_norm_epsilon
116
+ self.initializer_factor = initializer_factor
117
+ self.feed_forward_proj = feed_forward_proj
118
+ self.use_cache = use_cache
119
+
120
+ act_info = self.feed_forward_proj.split("-")
121
+ self.dense_act_fn = act_info[-1]
122
+ self.is_gated_act = act_info[0] == "gated"
123
+
124
+ if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
125
+ raise ValueError(
126
+ f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
127
+ "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
128
+ "'gated-gelu' or 'relu'"
129
+ )
130
+
131
+ # for backwards compatibility
132
+ if feed_forward_proj == "gated-gelu":
133
+ self.dense_act_fn = "gelu_new"
134
+
135
+ super().__init__(
136
+ pad_token_id=pad_token_id,
137
+ eos_token_id=eos_token_id,
138
+ is_encoder_decoder=is_encoder_decoder,
139
+ **kwargs,
140
+ )
141
+
142
+
143
+ class T5OnnxConfig(OnnxSeq2SeqConfigWithPast):
144
+ @property
145
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
146
+ common_inputs = {
147
+ "input_ids": {0: "batch", 1: "encoder_sequence"},
148
+ "attention_mask": {0: "batch", 1: "encoder_sequence"},
149
+ }
150
+ if self.use_past:
151
+ common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence"
152
+ common_inputs["decoder_input_ids"] = {0: "batch"}
153
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
154
+ else:
155
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
156
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
157
+
158
+ if self.use_past:
159
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
160
+
161
+ return common_inputs
162
+
163
+ @property
164
+ def default_onnx_opset(self) -> int:
165
+ return 13
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The 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
+ """Convert T5 checkpoint."""
16
+
17
+
18
+ import argparse
19
+
20
+ from transformers import T5Config, T5ForConditionalGeneration, load_tf_weights_in_t5
21
+ from transformers.utils import logging
22
+
23
+
24
+ logging.set_verbosity_info()
25
+
26
+
27
+ def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path):
28
+ # Initialise PyTorch model
29
+ config = T5Config.from_json_file(config_file)
30
+ print(f"Building PyTorch model from configuration: {config}")
31
+ model = T5ForConditionalGeneration(config)
32
+
33
+ # Load weights from tf checkpoint
34
+ load_tf_weights_in_t5(model, config, tf_checkpoint_path)
35
+
36
+ # Save pytorch-model
37
+ print(f"Save PyTorch model to {pytorch_dump_path}")
38
+ model.save_pretrained(pytorch_dump_path)
39
+
40
+
41
+ if __name__ == "__main__":
42
+ parser = argparse.ArgumentParser()
43
+ # Required parameters
44
+ parser.add_argument(
45
+ "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
46
+ )
47
+ parser.add_argument(
48
+ "--config_file",
49
+ default=None,
50
+ type=str,
51
+ required=True,
52
+ help=(
53
+ "The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture."
54
+ ),
55
+ )
56
+ parser.add_argument(
57
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
58
+ )
59
+ args = parser.parse_args()
60
+ convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ """Convert T5X checkpoints from the original repository to JAX/FLAX model."""
17
+
18
+ import argparse
19
+
20
+ from t5x import checkpoints
21
+
22
+ from transformers import FlaxT5ForConditionalGeneration, T5Config
23
+
24
+
25
+ def convert_t5x_checkpoint_to_flax(t5x_checkpoint_path, config_name, flax_dump_folder_path):
26
+ config = T5Config.from_pretrained(config_name)
27
+ flax_model = FlaxT5ForConditionalGeneration(config=config)
28
+ t5x_model = checkpoints.load_t5x_checkpoint(t5x_checkpoint_path)
29
+
30
+ split_mlp_wi = "wi_0" in t5x_model["target"]["encoder"]["layers_0"]["mlp"]
31
+
32
+ # Encoder
33
+ for layer_index in range(config.num_layers):
34
+ layer_name = f"layers_{str(layer_index)}"
35
+
36
+ # Self-Attention
37
+ t5x_attention_key = t5x_model["target"]["encoder"][layer_name]["attention"]["key"]["kernel"]
38
+ t5x_attention_out = t5x_model["target"]["encoder"][layer_name]["attention"]["out"]["kernel"]
39
+ t5x_attention_query = t5x_model["target"]["encoder"][layer_name]["attention"]["query"]["kernel"]
40
+ t5x_attention_value = t5x_model["target"]["encoder"][layer_name]["attention"]["value"]["kernel"]
41
+
42
+ # Layer Normalization
43
+ t5x_attention_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_attention_layer_norm"]["scale"]
44
+
45
+ if split_mlp_wi:
46
+ t5x_mlp_wi_0 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_0"]["kernel"]
47
+ t5x_mlp_wi_1 = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi_1"]["kernel"]
48
+ else:
49
+ t5x_mlp_wi = t5x_model["target"]["encoder"][layer_name]["mlp"]["wi"]["kernel"]
50
+
51
+ t5x_mlp_wo = t5x_model["target"]["encoder"][layer_name]["mlp"]["wo"]["kernel"]
52
+
53
+ # Layer Normalization
54
+ t5x_mlp_layer_norm = t5x_model["target"]["encoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
55
+
56
+ # Assigning
57
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["k"][
58
+ "kernel"
59
+ ] = t5x_attention_key
60
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["o"][
61
+ "kernel"
62
+ ] = t5x_attention_out
63
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["q"][
64
+ "kernel"
65
+ ] = t5x_attention_query
66
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["v"][
67
+ "kernel"
68
+ ] = t5x_attention_value
69
+
70
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["0"]["layer_norm"][
71
+ "weight"
72
+ ] = t5x_attention_layer_norm
73
+
74
+ if split_mlp_wi:
75
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wi_0"][
76
+ "kernel"
77
+ ] = t5x_mlp_wi_0
78
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wi_1"][
79
+ "kernel"
80
+ ] = t5x_mlp_wi_1
81
+ else:
82
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wi"][
83
+ "kernel"
84
+ ] = t5x_mlp_wi
85
+
86
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["DenseReluDense"]["wo"][
87
+ "kernel"
88
+ ] = t5x_mlp_wo
89
+ flax_model.params["encoder"]["block"][str(layer_index)]["layer"]["1"]["layer_norm"][
90
+ "weight"
91
+ ] = t5x_mlp_layer_norm
92
+
93
+ # Only for layer 0:
94
+ t5x_encoder_rel_embedding = t5x_model["target"]["encoder"]["relpos_bias"]["rel_embedding"].T
95
+ flax_model.params["encoder"]["block"]["0"]["layer"]["0"]["SelfAttention"]["relative_attention_bias"][
96
+ "embedding"
97
+ ] = t5x_encoder_rel_embedding
98
+
99
+ # Assigning
100
+ t5x_encoder_norm = t5x_model["target"]["encoder"]["encoder_norm"]["scale"]
101
+ flax_model.params["encoder"]["final_layer_norm"]["weight"] = t5x_encoder_norm
102
+
103
+ # Decoder
104
+ for layer_index in range(config.num_decoder_layers):
105
+ layer_name = f"layers_{str(layer_index)}"
106
+
107
+ # Self-Attention
108
+ t5x_attention_key = t5x_model["target"]["decoder"][layer_name]["self_attention"]["key"]["kernel"]
109
+ t5x_attention_out = t5x_model["target"]["decoder"][layer_name]["self_attention"]["out"]["kernel"]
110
+ t5x_attention_query = t5x_model["target"]["decoder"][layer_name]["self_attention"]["query"]["kernel"]
111
+ t5x_attention_value = t5x_model["target"]["decoder"][layer_name]["self_attention"]["value"]["kernel"]
112
+
113
+ # Layer Normalization
114
+ t5x_pre_attention_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_self_attention_layer_norm"][
115
+ "scale"
116
+ ]
117
+
118
+ # Encoder-Decoder-Attention
119
+ t5x_enc_dec_attention_key = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["key"][
120
+ "kernel"
121
+ ]
122
+ t5x_enc_dec_attention_out = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["out"][
123
+ "kernel"
124
+ ]
125
+ t5x_enc_dec_attention_query = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["query"][
126
+ "kernel"
127
+ ]
128
+ t5x_enc_dec_attention_value = t5x_model["target"]["decoder"][layer_name]["encoder_decoder_attention"]["value"][
129
+ "kernel"
130
+ ]
131
+
132
+ # Layer Normalization
133
+ t5x_cross_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_cross_attention_layer_norm"]["scale"]
134
+
135
+ # MLP
136
+ if split_mlp_wi:
137
+ t5x_mlp_wi_0 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_0"]["kernel"]
138
+ t5x_mlp_wi_1 = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi_1"]["kernel"]
139
+ else:
140
+ t5x_mlp_wi = t5x_model["target"]["decoder"][layer_name]["mlp"]["wi"]["kernel"]
141
+
142
+ t5x_mlp_wo = t5x_model["target"]["decoder"][layer_name]["mlp"]["wo"]["kernel"]
143
+
144
+ # Layer Normalization
145
+ tx5_mlp_layer_norm = t5x_model["target"]["decoder"][layer_name]["pre_mlp_layer_norm"]["scale"]
146
+
147
+ # Assigning
148
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["k"][
149
+ "kernel"
150
+ ] = t5x_attention_key
151
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["o"][
152
+ "kernel"
153
+ ] = t5x_attention_out
154
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["q"][
155
+ "kernel"
156
+ ] = t5x_attention_query
157
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["SelfAttention"]["v"][
158
+ "kernel"
159
+ ] = t5x_attention_value
160
+
161
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["0"]["layer_norm"][
162
+ "weight"
163
+ ] = t5x_pre_attention_layer_norm
164
+
165
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["k"][
166
+ "kernel"
167
+ ] = t5x_enc_dec_attention_key
168
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["o"][
169
+ "kernel"
170
+ ] = t5x_enc_dec_attention_out
171
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["q"][
172
+ "kernel"
173
+ ] = t5x_enc_dec_attention_query
174
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["EncDecAttention"]["v"][
175
+ "kernel"
176
+ ] = t5x_enc_dec_attention_value
177
+
178
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["1"]["layer_norm"][
179
+ "weight"
180
+ ] = t5x_cross_layer_norm
181
+
182
+ if split_mlp_wi:
183
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wi_0"][
184
+ "kernel"
185
+ ] = t5x_mlp_wi_0
186
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wi_1"][
187
+ "kernel"
188
+ ] = t5x_mlp_wi_1
189
+ else:
190
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wi"][
191
+ "kernel"
192
+ ] = t5x_mlp_wi
193
+
194
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["DenseReluDense"]["wo"][
195
+ "kernel"
196
+ ] = t5x_mlp_wo
197
+
198
+ flax_model.params["decoder"]["block"][str(layer_index)]["layer"]["2"]["layer_norm"][
199
+ "weight"
200
+ ] = tx5_mlp_layer_norm
201
+
202
+ # Decoder Normalization
203
+ tx5_decoder_norm = t5x_model["target"]["decoder"]["decoder_norm"]["scale"]
204
+ flax_model.params["decoder"]["final_layer_norm"]["weight"] = tx5_decoder_norm
205
+
206
+ # Only for layer 0:
207
+ t5x_decoder_rel_embedding = t5x_model["target"]["decoder"]["relpos_bias"]["rel_embedding"].T
208
+ flax_model.params["decoder"]["block"]["0"]["layer"]["0"]["SelfAttention"]["relative_attention_bias"][
209
+ "embedding"
210
+ ] = t5x_decoder_rel_embedding
211
+
212
+ # Token Embeddings
213
+ tx5_token_embeddings = t5x_model["target"]["token_embedder"]["embedding"]
214
+ flax_model.params["shared"]["embedding"] = tx5_token_embeddings
215
+
216
+ # LM Head (only in v1.1 checkpoints)
217
+ if "logits_dense" in t5x_model["target"]["decoder"]:
218
+ flax_model.params["lm_head"]["kernel"] = t5x_model["target"]["decoder"]["logits_dense"]["kernel"]
219
+
220
+ flax_model.save_pretrained(flax_dump_folder_path)
221
+ print("T5X Model was sucessfully converted!")
222
+
223
+
224
+ if __name__ == "__main__":
225
+ parser = argparse.ArgumentParser()
226
+ # Required parameters
227
+ parser.add_argument(
228
+ "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path the TX5 checkpoint."
229
+ )
230
+ parser.add_argument("--config_name", default=None, type=str, required=True, help="Config name of T5 model.")
231
+ parser.add_argument(
232
+ "--flax_dump_folder_path", default=None, type=str, required=True, help="Path to the output FLAX model."
233
+ )
234
+ args = parser.parse_args()
235
+ convert_t5x_checkpoint_to_flax(args.t5x_checkpoint_path, args.config_name, args.flax_dump_folder_path)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/modeling_flax_t5.py ADDED
@@ -0,0 +1,1799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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
+ """ Flax T5 model."""
16
+
17
+
18
+ import copy
19
+ from typing import Callable, Optional, Tuple
20
+
21
+ import flax.linen as nn
22
+ import jax
23
+ import jax.numpy as jnp
24
+ import numpy as np
25
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
26
+ from flax.linen import combine_masks, make_causal_mask
27
+ from flax.linen import partitioning as nn_partitioning
28
+ from flax.linen.attention import dot_product_attention_weights
29
+ from flax.traverse_util import flatten_dict, unflatten_dict
30
+ from jax.random import PRNGKey
31
+
32
+ from ...modeling_flax_outputs import (
33
+ FlaxBaseModelOutput,
34
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
35
+ FlaxCausalLMOutputWithCrossAttentions,
36
+ FlaxSeq2SeqLMOutput,
37
+ FlaxSeq2SeqModelOutput,
38
+ )
39
+ from ...modeling_flax_utils import (
40
+ ACT2FN,
41
+ FlaxPreTrainedModel,
42
+ append_call_sample_docstring,
43
+ append_replace_return_docstrings,
44
+ overwrite_call_docstring,
45
+ )
46
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
47
+ from .configuration_t5 import T5Config
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CHECKPOINT_FOR_DOC = "t5-small"
53
+ _CONFIG_FOR_DOC = "T5Config"
54
+
55
+ remat = nn_partitioning.remat
56
+
57
+
58
+ # Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right
59
+ def shift_tokens_right(input_ids: np.array, pad_token_id: int, decoder_start_token_id: int) -> np.ndarray:
60
+ """
61
+ Shift input ids one token to the right.
62
+ """
63
+ shifted_input_ids = np.zeros_like(input_ids)
64
+ shifted_input_ids[:, 1:] = input_ids[:, :-1]
65
+ shifted_input_ids[:, 0] = decoder_start_token_id
66
+
67
+ shifted_input_ids = np.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
68
+ return shifted_input_ids
69
+
70
+
71
+ class FlaxT5LayerNorm(nn.Module):
72
+ hidden_size: int
73
+ dtype: jnp.dtype = jnp.float32
74
+ eps: float = 1e-6
75
+ weight_init: Callable[..., np.ndarray] = jax.nn.initializers.ones
76
+
77
+ def setup(self):
78
+ self.weight = self.param("weight", self.weight_init, (self.hidden_size,))
79
+
80
+ def __call__(self, hidden_states):
81
+ """
82
+ Construct a layernorm module in the T5 style; No bias and no subtraction of mean.
83
+ """
84
+ # layer norm should always be calculated in float32
85
+ variance = jnp.power(hidden_states.astype("f4"), 2).mean(axis=-1, keepdims=True)
86
+ hidden_states = hidden_states / jnp.sqrt(variance + self.eps)
87
+
88
+ return self.weight * hidden_states
89
+
90
+
91
+ class FlaxT5DenseActDense(nn.Module):
92
+ config: T5Config
93
+ dtype: jnp.dtype = jnp.float32
94
+
95
+ def setup(self):
96
+ wi_init_std = self.config.initializer_factor * (self.config.d_model**-0.5)
97
+ wo_init_std = self.config.initializer_factor * (self.config.d_ff**-0.5)
98
+
99
+ self.wi = nn.Dense(
100
+ self.config.d_ff,
101
+ use_bias=False,
102
+ kernel_init=jax.nn.initializers.normal(wi_init_std),
103
+ dtype=self.dtype,
104
+ )
105
+ self.wo = nn.Dense(
106
+ self.config.d_model,
107
+ use_bias=False,
108
+ kernel_init=jax.nn.initializers.normal(wo_init_std),
109
+ dtype=self.dtype,
110
+ )
111
+ self.dropout = nn.Dropout(self.config.dropout_rate)
112
+ self.act = ACT2FN[self.config.dense_act_fn]
113
+
114
+ def __call__(self, hidden_states, deterministic=True):
115
+ hidden_states = self.wi(hidden_states)
116
+ hidden_states = self.act(hidden_states)
117
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
118
+ hidden_states = self.wo(hidden_states)
119
+ return hidden_states
120
+
121
+
122
+ class FlaxT5DenseGatedActDense(nn.Module):
123
+ config: T5Config
124
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
125
+
126
+ def setup(self):
127
+ wi_init_std = self.config.initializer_factor * (self.config.d_model**-0.5)
128
+ wo_init_std = self.config.initializer_factor * (self.config.d_ff**-0.5)
129
+
130
+ self.wi_0 = nn.Dense(
131
+ self.config.d_ff,
132
+ use_bias=False,
133
+ kernel_init=jax.nn.initializers.normal(wi_init_std),
134
+ dtype=self.dtype,
135
+ )
136
+ self.wi_1 = nn.Dense(
137
+ self.config.d_ff,
138
+ use_bias=False,
139
+ kernel_init=jax.nn.initializers.normal(wi_init_std),
140
+ dtype=self.dtype,
141
+ )
142
+ self.wo = nn.Dense(
143
+ self.config.d_model,
144
+ use_bias=False,
145
+ kernel_init=jax.nn.initializers.normal(wo_init_std),
146
+ dtype=self.dtype,
147
+ )
148
+ self.dropout = nn.Dropout(self.config.dropout_rate)
149
+ self.act = ACT2FN[self.config.dense_act_fn]
150
+
151
+ def __call__(self, hidden_states, deterministic):
152
+ hidden_gelu = self.act(self.wi_0(hidden_states))
153
+ hidden_linear = self.wi_1(hidden_states)
154
+ hidden_states = hidden_gelu * hidden_linear
155
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
156
+ hidden_states = self.wo(hidden_states)
157
+ return hidden_states
158
+
159
+
160
+ class FlaxT5LayerFF(nn.Module):
161
+ config: T5Config
162
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
163
+
164
+ def setup(self):
165
+ if self.config.is_gated_act:
166
+ self.DenseReluDense = FlaxT5DenseGatedActDense(self.config, dtype=self.dtype)
167
+ else:
168
+ self.DenseReluDense = FlaxT5DenseActDense(self.config, dtype=self.dtype)
169
+
170
+ self.layer_norm = FlaxT5LayerNorm(self.config.d_model, eps=self.config.layer_norm_epsilon, dtype=self.dtype)
171
+ self.dropout = nn.Dropout(self.config.dropout_rate)
172
+
173
+ def __call__(self, hidden_states, deterministic=True):
174
+ forwarded_states = self.layer_norm(hidden_states)
175
+ forwarded_states = self.DenseReluDense(forwarded_states, deterministic=deterministic)
176
+ hidden_states = hidden_states + self.dropout(forwarded_states, deterministic=deterministic)
177
+ return hidden_states
178
+
179
+
180
+ class FlaxT5Attention(nn.Module):
181
+ config: T5Config
182
+ has_relative_attention_bias: bool = False
183
+ causal: bool = False
184
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
185
+
186
+ def setup(self):
187
+ self.relative_attention_num_buckets = self.config.relative_attention_num_buckets
188
+ self.relative_attention_max_distance = self.config.relative_attention_max_distance
189
+ self.d_model = self.config.d_model
190
+ self.key_value_proj_dim = self.config.d_kv
191
+ self.n_heads = self.config.num_heads
192
+ self.dropout = self.config.dropout_rate
193
+ self.inner_dim = self.n_heads * self.key_value_proj_dim
194
+
195
+ q_init_std = self.config.initializer_factor * ((self.inner_dim * self.key_value_proj_dim) ** -0.5)
196
+ kv_init_std = self.config.initializer_factor * (self.inner_dim**-0.5)
197
+ o_init_std = self.config.initializer_factor * (self.inner_dim**-0.5)
198
+
199
+ self.q = nn.Dense(
200
+ self.inner_dim,
201
+ use_bias=False,
202
+ kernel_init=jax.nn.initializers.normal(q_init_std),
203
+ dtype=self.dtype,
204
+ )
205
+ self.k = nn.Dense(
206
+ self.inner_dim,
207
+ use_bias=False,
208
+ kernel_init=jax.nn.initializers.normal(kv_init_std),
209
+ dtype=self.dtype,
210
+ )
211
+ self.v = nn.Dense(
212
+ self.inner_dim,
213
+ use_bias=False,
214
+ kernel_init=jax.nn.initializers.normal(kv_init_std),
215
+ dtype=self.dtype,
216
+ )
217
+ self.o = nn.Dense(
218
+ self.d_model,
219
+ use_bias=False,
220
+ kernel_init=jax.nn.initializers.normal(o_init_std),
221
+ dtype=self.dtype,
222
+ )
223
+
224
+ if self.has_relative_attention_bias:
225
+ self.relative_attention_bias = nn.Embed(
226
+ self.relative_attention_num_buckets,
227
+ self.n_heads,
228
+ embedding_init=jax.nn.initializers.normal(kv_init_std),
229
+ dtype=self.dtype,
230
+ )
231
+
232
+ @staticmethod
233
+ def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
234
+ """
235
+ Adapted from Mesh Tensorflow:
236
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
237
+
238
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
239
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
240
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
241
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
242
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
243
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
244
+ """
245
+ relative_buckets = 0
246
+ if bidirectional:
247
+ num_buckets //= 2
248
+ relative_buckets += (relative_position > 0) * num_buckets
249
+ relative_position = jnp.abs(relative_position)
250
+ else:
251
+ relative_position = -jnp.clip(relative_position, a_max=0)
252
+ # now relative_position is in the range [0, inf)
253
+
254
+ # half of the buckets are for exact increments in positions
255
+ max_exact = num_buckets // 2
256
+ is_small = relative_position < max_exact
257
+
258
+ # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
259
+ relative_position_if_large = max_exact + (
260
+ jnp.log(relative_position / max_exact) / jnp.log(max_distance / max_exact) * (num_buckets - max_exact)
261
+ )
262
+ relative_position_if_large = jnp.clip(relative_position_if_large, a_max=num_buckets - 1)
263
+
264
+ relative_buckets += jnp.where(is_small, relative_position, relative_position_if_large)
265
+
266
+ return relative_buckets.astype("i4")
267
+
268
+ def compute_bias(self, query_length, key_length):
269
+ """Compute binned relative position bias"""
270
+ context_position = jnp.arange(query_length, dtype="i4")[:, None]
271
+ memory_position = jnp.arange(key_length, dtype="i4")[None, :]
272
+
273
+ relative_position = memory_position - context_position
274
+ relative_position_bucket = self._relative_position_bucket(
275
+ relative_position,
276
+ bidirectional=(not self.causal),
277
+ num_buckets=self.relative_attention_num_buckets,
278
+ max_distance=self.relative_attention_max_distance,
279
+ )
280
+
281
+ values = self.relative_attention_bias(relative_position_bucket)
282
+ values = values.transpose((2, 0, 1))[None, :, :, :]
283
+ return values
284
+
285
+ def _split_heads(self, hidden_states):
286
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.n_heads, self.key_value_proj_dim))
287
+
288
+ def _merge_heads(self, hidden_states):
289
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.inner_dim,))
290
+
291
+ @nn.compact
292
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
293
+ """
294
+ This function takes projected key, value states from a single input token and concatenates the states to cached
295
+ states from previous steps. This function is slighly adapted from the official Flax repository:
296
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
297
+ """
298
+ # detect if we're initializing by absence of existing cache data.
299
+ is_initialized = self.has_variable("cache", "cached_key")
300
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
301
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
302
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
303
+
304
+ if is_initialized:
305
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
306
+ # update key, value caches with our new 1d spatial slices
307
+ cur_index = cache_index.value
308
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
309
+ key = jax.lax.dynamic_update_slice(cached_key.value, key, indices)
310
+ value = jax.lax.dynamic_update_slice(cached_value.value, value, indices)
311
+ cached_key.value = key
312
+ cached_value.value = value
313
+ num_updated_cache_vectors = query.shape[1]
314
+ cache_index.value = cache_index.value + num_updated_cache_vectors
315
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions
316
+ # that have already been generated and cached, not the remaining zero elements.
317
+ pad_mask = jnp.broadcast_to(
318
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
319
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
320
+ )
321
+ attention_mask = combine_masks(pad_mask, attention_mask)
322
+ return key, value, attention_mask
323
+
324
+ def _create_position_bias(
325
+ self, key_states, query_states, attention_mask, init_cache, seq_length, causal_attention_mask_shift
326
+ ):
327
+ cache_is_filled = self.causal and self.has_variable("cache", "cached_key") and (not init_cache)
328
+ key_length = key_states.shape[1]
329
+ query_length = key_length if cache_is_filled else query_states.shape[1]
330
+
331
+ if self.has_relative_attention_bias:
332
+ position_bias = self.compute_bias(query_length, key_length)
333
+ elif attention_mask is not None:
334
+ position_bias = jnp.zeros_like(attention_mask)
335
+ else:
336
+ position_bias = jnp.zeros((1, self.n_heads, query_length, key_length), dtype=self.dtype)
337
+
338
+ # if key and values are already calculated, only the last query position bias should be taken
339
+ if cache_is_filled:
340
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
341
+ position_bias = jax.lax.dynamic_slice(
342
+ position_bias,
343
+ (0, 0, causal_attention_mask_shift, 0),
344
+ (1, self.n_heads, seq_length, max_decoder_length),
345
+ )
346
+ return position_bias
347
+
348
+ def __call__(
349
+ self,
350
+ hidden_states,
351
+ attention_mask=None,
352
+ key_value_states=None,
353
+ position_bias=None,
354
+ use_cache=False,
355
+ output_attentions=False,
356
+ deterministic=True,
357
+ init_cache=False,
358
+ ):
359
+ """
360
+ Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
361
+ """
362
+ batch_size, seq_length = hidden_states.shape[:2]
363
+
364
+ # q, k, v projections
365
+ query_states = self.q(hidden_states) # (batch_size, n_heads, seq_length, dim_per_head)
366
+ key_states = self.k(hidden_states) if key_value_states is None else self.k(key_value_states)
367
+ value_states = self.v(hidden_states) if key_value_states is None else self.v(key_value_states)
368
+
369
+ # reshape to (batch_size, seq_length, n_heads, head_dim)
370
+ query_states = self._split_heads(query_states)
371
+ key_states = self._split_heads(key_states)
372
+ value_states = self._split_heads(value_states)
373
+
374
+ # counter-act scaling in dot_product_attention_weights function
375
+ query_states *= jnp.sqrt(query_states.shape[-1])
376
+
377
+ # for fast decoding causal attention mask should be shifted
378
+ causal_attention_mask_shift = (
379
+ self.variables["cache"]["cache_index"] if (self.has_variable("cache", "cached_key") and self.causal) else 0
380
+ )
381
+ # create causal attention_mask; attention_mask has to be defined when model is causal
382
+ if self.causal:
383
+ causal_attention_mask = make_causal_mask(attention_mask, dtype="bool")
384
+
385
+ # fast decoding for generate requires special attention_mask
386
+ if self.has_variable("cache", "cached_key"):
387
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
388
+ causal_attention_mask = jax.lax.dynamic_slice(
389
+ causal_attention_mask,
390
+ (0, 0, causal_attention_mask_shift, 0),
391
+ (1, 1, seq_length, max_decoder_length),
392
+ )
393
+
394
+ # broadcast causal attention mask & attention mask to fit for merge
395
+ causal_attention_mask = jnp.broadcast_to(
396
+ causal_attention_mask, (batch_size,) + causal_attention_mask.shape[1:]
397
+ )
398
+ attention_mask = jnp.broadcast_to(
399
+ jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_attention_mask.shape
400
+ )
401
+ attention_mask = combine_masks(attention_mask, causal_attention_mask)
402
+ elif attention_mask is not None:
403
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
404
+
405
+ # During fast autoregressive decoding, we feed one position at a time,
406
+ # and cache the keys and values step by step.
407
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
408
+ key_states, value_states, attention_attention_mask = self._concatenate_to_cache(
409
+ key_states, value_states, query_states, attention_mask
410
+ )
411
+
412
+ # replace masked positions with -10_000
413
+ if attention_mask is not None:
414
+ mask_value = jnp.finfo(self.dtype).min
415
+ attention_mask = jax.lax.select(
416
+ attention_mask > 0,
417
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
418
+ jnp.full(attention_mask.shape, mask_value).astype(self.dtype),
419
+ )
420
+
421
+ if position_bias is None:
422
+ # compute position bias (only for first layer)
423
+ position_bias = self._create_position_bias(
424
+ key_states, query_states, attention_mask, init_cache, seq_length, causal_attention_mask_shift
425
+ )
426
+
427
+ if attention_mask is not None:
428
+ position_bias = position_bias + attention_mask
429
+
430
+ # create dropout rng
431
+ dropout_rng = None
432
+ if not deterministic and self.dropout > 0.0:
433
+ dropout_rng = self.make_rng("dropout")
434
+
435
+ # Softmax(QK^T)
436
+ attn_weights = dot_product_attention_weights(
437
+ query_states,
438
+ key_states,
439
+ bias=position_bias,
440
+ dropout_rng=dropout_rng,
441
+ dropout_rate=self.dropout,
442
+ broadcast_dropout=True,
443
+ deterministic=deterministic,
444
+ dtype=self.dtype,
445
+ )
446
+
447
+ # multiply with value states
448
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
449
+
450
+ # bring back to (batch_size, seq_length, d_model)
451
+ attn_output = self._merge_heads(attn_output)
452
+
453
+ # apply output matrix
454
+ attn_output = self.o(attn_output)
455
+
456
+ outputs = (attn_output, position_bias)
457
+
458
+ if output_attentions:
459
+ outputs = outputs + (attn_weights,)
460
+
461
+ return outputs
462
+
463
+
464
+ class FlaxT5LayerSelfAttention(nn.Module):
465
+ config: T5Config
466
+ has_relative_attention_bias: bool = False
467
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
468
+
469
+ def setup(self):
470
+ self.SelfAttention = FlaxT5Attention(
471
+ self.config,
472
+ has_relative_attention_bias=self.has_relative_attention_bias,
473
+ causal=self.config.causal,
474
+ dtype=self.dtype,
475
+ )
476
+ self.layer_norm = FlaxT5LayerNorm(self.config.d_model, eps=self.config.layer_norm_epsilon, dtype=self.dtype)
477
+ self.dropout = nn.Dropout(self.config.dropout_rate)
478
+
479
+ def __call__(
480
+ self,
481
+ hidden_states,
482
+ attention_mask=None,
483
+ position_bias=None,
484
+ output_attentions=False,
485
+ deterministic=True,
486
+ init_cache=False,
487
+ ):
488
+ normed_hidden_states = self.layer_norm(hidden_states)
489
+ attention_output = self.SelfAttention(
490
+ normed_hidden_states,
491
+ attention_mask=attention_mask,
492
+ position_bias=position_bias,
493
+ output_attentions=output_attentions,
494
+ deterministic=deterministic,
495
+ init_cache=init_cache,
496
+ )
497
+ hidden_states = hidden_states + self.dropout(attention_output[0], deterministic=deterministic)
498
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
499
+ return outputs
500
+
501
+
502
+ class FlaxT5LayerCrossAttention(nn.Module):
503
+ config: T5Config
504
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
505
+
506
+ def setup(self):
507
+ self.EncDecAttention = FlaxT5Attention(
508
+ self.config, has_relative_attention_bias=False, causal=False, dtype=self.dtype
509
+ )
510
+ self.layer_norm = FlaxT5LayerNorm(self.config.d_model, eps=self.config.layer_norm_epsilon, dtype=self.dtype)
511
+ self.dropout = nn.Dropout(self.config.dropout_rate)
512
+
513
+ def __call__(
514
+ self,
515
+ hidden_states,
516
+ key_value_states,
517
+ attention_mask=None,
518
+ position_bias=None,
519
+ output_attentions=False,
520
+ deterministic=True,
521
+ ):
522
+ normed_hidden_states = self.layer_norm(hidden_states)
523
+ attention_output = self.EncDecAttention(
524
+ normed_hidden_states,
525
+ attention_mask=attention_mask,
526
+ key_value_states=key_value_states,
527
+ position_bias=position_bias,
528
+ output_attentions=output_attentions,
529
+ )
530
+ hidden_states = hidden_states + self.dropout(attention_output[0], deterministic=deterministic)
531
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
532
+ return outputs
533
+
534
+
535
+ class FlaxT5Block(nn.Module):
536
+ config: T5Config
537
+ has_relative_attention_bias: bool = False
538
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
539
+
540
+ def setup(self):
541
+ self.causal = self.config.causal
542
+ self.layer = (
543
+ FlaxT5LayerSelfAttention(
544
+ self.config,
545
+ has_relative_attention_bias=self.has_relative_attention_bias,
546
+ name=str(0),
547
+ dtype=self.dtype,
548
+ ),
549
+ )
550
+ feed_forward_index = 1
551
+ if self.causal:
552
+ self.layer += (FlaxT5LayerCrossAttention(self.config, name=str(1), dtype=self.dtype),)
553
+ feed_forward_index += 1
554
+
555
+ self.layer += (FlaxT5LayerFF(self.config, name=str(feed_forward_index), dtype=self.dtype),)
556
+
557
+ def __call__(
558
+ self,
559
+ hidden_states,
560
+ attention_mask=None,
561
+ position_bias=None,
562
+ encoder_hidden_states=None,
563
+ encoder_attention_mask=None,
564
+ encoder_decoder_position_bias=None,
565
+ output_attentions=False,
566
+ return_dict=True,
567
+ deterministic=True,
568
+ init_cache=False,
569
+ ):
570
+ self_attention_outputs = self.layer[0](
571
+ hidden_states,
572
+ attention_mask=attention_mask,
573
+ position_bias=position_bias,
574
+ output_attentions=output_attentions,
575
+ deterministic=deterministic,
576
+ init_cache=init_cache,
577
+ )
578
+ hidden_states = self_attention_outputs[0]
579
+ attention_outputs = self_attention_outputs[1:] # Keep self-attention outputs and relative position weights
580
+
581
+ do_cross_attention = self.causal and encoder_hidden_states is not None
582
+ if do_cross_attention:
583
+ cross_attention_outputs = self.layer[1](
584
+ hidden_states,
585
+ key_value_states=encoder_hidden_states,
586
+ attention_mask=encoder_attention_mask,
587
+ position_bias=encoder_decoder_position_bias,
588
+ output_attentions=output_attentions,
589
+ deterministic=deterministic,
590
+ )
591
+ hidden_states = cross_attention_outputs[0]
592
+
593
+ # Keep cross-attention outputs and relative position weights
594
+ attention_outputs = attention_outputs + cross_attention_outputs[1:]
595
+
596
+ # Apply Feed Forward layer
597
+ hidden_states = self.layer[-1](hidden_states, deterministic=deterministic)
598
+
599
+ outputs = (hidden_states,)
600
+
601
+ outputs = outputs + attention_outputs
602
+
603
+ # returns hidden-states, present_key_value_states, (self-attention position bias), (self-attention weights),
604
+ # (cross-attention position bias), (cross-attention weights)
605
+ return outputs
606
+
607
+
608
+ class FlaxT5LayerCollection(nn.Module):
609
+ config: T5Config
610
+ has_relative_attention_bias: bool
611
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
612
+
613
+ def setup(self):
614
+ self.layer = FlaxT5Block(
615
+ self.config, has_relative_attention_bias=self.has_relative_attention_bias, dtype=self.dtype
616
+ )
617
+
618
+ def __call__(
619
+ self,
620
+ hidden_states,
621
+ attention_mask=None,
622
+ position_bias=None,
623
+ encoder_hidden_states=None,
624
+ encoder_attention_mask=None,
625
+ encoder_decoder_position_bias=None,
626
+ output_attentions=False,
627
+ deterministic=True,
628
+ init_cache=False,
629
+ ):
630
+ return self.layer(
631
+ hidden_states,
632
+ attention_mask=attention_mask,
633
+ position_bias=position_bias,
634
+ encoder_hidden_states=encoder_hidden_states,
635
+ encoder_attention_mask=encoder_attention_mask,
636
+ encoder_decoder_position_bias=encoder_decoder_position_bias,
637
+ output_attentions=output_attentions,
638
+ deterministic=deterministic,
639
+ init_cache=init_cache,
640
+ )
641
+
642
+
643
+ class FlaxT5BlockCollection(nn.Module):
644
+ config: T5Config
645
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
646
+ gradient_checkpointing: bool = False
647
+
648
+ def setup(self):
649
+ self.causal = self.config.causal
650
+ if self.gradient_checkpointing:
651
+ FlaxT5CheckpointLayer = remat(FlaxT5LayerCollection, static_argnums=(6, 7, 8))
652
+ self.blocks = [
653
+ FlaxT5CheckpointLayer(
654
+ self.config,
655
+ has_relative_attention_bias=(i == 0),
656
+ dtype=self.dtype,
657
+ name=str(i),
658
+ )
659
+ for i in range(self.config.num_layers)
660
+ ]
661
+ else:
662
+ self.blocks = [
663
+ FlaxT5LayerCollection(
664
+ self.config,
665
+ has_relative_attention_bias=(i == 0),
666
+ dtype=self.dtype,
667
+ name=str(i),
668
+ )
669
+ for i in range(self.config.num_layers)
670
+ ]
671
+
672
+ def __call__(
673
+ self,
674
+ hidden_states=None,
675
+ attention_mask=None,
676
+ encoder_hidden_states=None,
677
+ encoder_attention_mask=None,
678
+ output_attentions: bool = False,
679
+ output_hidden_states: bool = False,
680
+ deterministic: bool = True,
681
+ init_cache: bool = False,
682
+ ):
683
+ # Prepare head mask if needed
684
+ all_hidden_states = () if output_hidden_states else None
685
+ all_attentions = () if output_attentions else None
686
+ all_cross_attentions = () if (output_attentions and self.causal) else None
687
+ position_bias = None
688
+ encoder_decoder_position_bias = None
689
+
690
+ for i, layer_module in enumerate(self.blocks):
691
+ if output_hidden_states:
692
+ all_hidden_states = all_hidden_states + (hidden_states,)
693
+
694
+ layer_outputs = layer_module(
695
+ hidden_states,
696
+ attention_mask,
697
+ position_bias,
698
+ encoder_hidden_states,
699
+ encoder_attention_mask,
700
+ encoder_decoder_position_bias,
701
+ output_attentions,
702
+ deterministic,
703
+ init_cache,
704
+ )
705
+
706
+ hidden_states = layer_outputs[0]
707
+
708
+ # We share the position biases between the layers - the first layer store them
709
+ # layer_outputs = hidden-states, key-value-states (self-attention position bias), (self-attention weights),
710
+ # (cross-attention position bias), (cross-attention weights)
711
+ position_bias = layer_outputs[1]
712
+
713
+ if self.causal and encoder_hidden_states is not None:
714
+ encoder_decoder_position_bias = layer_outputs[3 if output_attentions else 2]
715
+
716
+ if output_attentions:
717
+ all_attentions = all_attentions + (layer_outputs[2],)
718
+ if self.causal:
719
+ all_cross_attentions = all_cross_attentions + (layer_outputs[4],)
720
+
721
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
722
+ last_hidden_state=hidden_states,
723
+ hidden_states=all_hidden_states,
724
+ attentions=all_attentions,
725
+ cross_attentions=all_cross_attentions,
726
+ )
727
+
728
+
729
+ class FlaxT5Stack(nn.Module):
730
+ config: T5Config
731
+ embed_tokens: nn.Embed
732
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
733
+ gradient_checkpointing: bool = False
734
+
735
+ def setup(self):
736
+ self.causal = self.config.causal
737
+
738
+ self.block = FlaxT5BlockCollection(
739
+ self.config, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
740
+ )
741
+ self.final_layer_norm = FlaxT5LayerNorm(
742
+ self.config.d_model, eps=self.config.layer_norm_epsilon, dtype=self.dtype
743
+ )
744
+ self.dropout = nn.Dropout(self.config.dropout_rate)
745
+
746
+ def __call__(
747
+ self,
748
+ input_ids=None,
749
+ attention_mask=None,
750
+ encoder_hidden_states=None,
751
+ encoder_attention_mask=None,
752
+ output_attentions: bool = False,
753
+ output_hidden_states: bool = False,
754
+ return_dict: bool = True,
755
+ deterministic: bool = True,
756
+ init_cache: bool = False,
757
+ ):
758
+ hidden_states = self.embed_tokens(input_ids)
759
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
760
+
761
+ outputs = self.block(
762
+ hidden_states,
763
+ attention_mask=attention_mask,
764
+ encoder_hidden_states=encoder_hidden_states,
765
+ encoder_attention_mask=encoder_attention_mask,
766
+ output_attentions=output_attentions,
767
+ output_hidden_states=output_hidden_states,
768
+ deterministic=deterministic,
769
+ init_cache=init_cache,
770
+ )
771
+
772
+ hidden_states = outputs[0]
773
+
774
+ hidden_states = self.final_layer_norm(hidden_states)
775
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
776
+
777
+ # Add last layer
778
+ all_hidden_states = None
779
+
780
+ if output_hidden_states:
781
+ all_hidden_states = outputs.hidden_states
782
+ all_hidden_states = all_hidden_states + (hidden_states,)
783
+
784
+ if not return_dict:
785
+ if output_hidden_states:
786
+ return (
787
+ hidden_states,
788
+ all_hidden_states,
789
+ ) + outputs[2:]
790
+ return (hidden_states,) + outputs[1:]
791
+
792
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
793
+ last_hidden_state=hidden_states,
794
+ hidden_states=all_hidden_states,
795
+ attentions=outputs.attentions,
796
+ cross_attentions=outputs.cross_attentions,
797
+ )
798
+
799
+
800
+ T5_ENCODE_INPUTS_DOCSTRING = r"""
801
+ Args:
802
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
803
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
804
+ should be able to pad the inputs on both the right and the left.
805
+
806
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
807
+ [`PreTrainedTokenizer.__call__`] for detail.
808
+
809
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
810
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
811
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
812
+
813
+ - 1 for tokens that are **not masked**,
814
+ - 0 for tokens that are **masked**.
815
+
816
+ [What are attention masks?](../glossary#attention-mask)
817
+ output_attentions (`bool`, *optional*):
818
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
819
+ tensors for more detail.
820
+ output_hidden_states (`bool`, *optional*):
821
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
822
+ more detail.
823
+ return_dict (`bool`, *optional*):
824
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
825
+ """
826
+
827
+ T5_DECODE_INPUTS_DOCSTRING = r"""
828
+ Args:
829
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
830
+ Indices of decoder input sequence tokens in the vocabulary.
831
+
832
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
833
+ [`PreTrainedTokenizer.__call__`] for details.
834
+
835
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
836
+
837
+ For training, `decoder_input_ids` should be provided.
838
+ encoder_outputs (`tuple(tuple(jnp.ndarray)`):
839
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
840
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
841
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
842
+ encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
843
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
844
+
845
+ - 1 for tokens that are **not masked**,
846
+ - 0 for tokens that are **masked**.
847
+
848
+ [What are attention masks?](../glossary#attention-mask)
849
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
850
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
851
+ be used by default.
852
+
853
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
854
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
855
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
856
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
857
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
858
+ output_attentions (`bool`, *optional*):
859
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
860
+ tensors for more detail.
861
+ output_hidden_states (`bool`, *optional*):
862
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
863
+ more detail.
864
+ return_dict (`bool`, *optional*):
865
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
866
+ """
867
+
868
+
869
+ T5_INPUTS_DOCSTRING = r"""
870
+ Args:
871
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
872
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
873
+ should be able to pad the inputs on both the right and the left.
874
+
875
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
876
+ [`PreTrainedTokenizer.__call__`] for detail.
877
+
878
+ [What are input IDs?](../glossary#input-ids)
879
+
880
+ To know more on how to prepare `input_ids` for pretraining take a look a [T5 Training](./t5#training).
881
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
882
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
883
+
884
+ - 1 for tokens that are **not masked**,
885
+ - 0 for tokens that are **masked**.
886
+
887
+ [What are attention masks?](../glossary#attention-mask)
888
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
889
+ Indices of decoder input sequence tokens in the vocabulary.
890
+
891
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
892
+ [`PreTrainedTokenizer.__call__`] for details.
893
+
894
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
895
+
896
+ T5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
897
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
898
+
899
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
900
+ Training](./t5#training).
901
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
902
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
903
+ be used by default.
904
+ encoder_outputs (`tuple(tuple(jnp.ndarray)`, *optional*):
905
+ Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
906
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
907
+ the output of the last layer of the encoder. Used in the cross-attention of the decoder.
908
+ past_key_values (`tuple(tuple(jnp.ndarray))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
909
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
910
+
911
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
912
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
913
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
914
+
915
+
916
+ output_attentions (`bool`, *optional*):
917
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
918
+ tensors for more detail.
919
+ output_hidden_states (`bool`, *optional*):
920
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
921
+ more detail.
922
+ return_dict (`bool`, *optional*):
923
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
924
+ """
925
+
926
+
927
+ class FlaxT5PreTrainedModel(FlaxPreTrainedModel):
928
+ """
929
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
930
+ models.
931
+ """
932
+
933
+ config_class = T5Config
934
+ base_model_prefix = "transformer"
935
+ module_class: nn.Module = None
936
+
937
+ def __init__(
938
+ self,
939
+ config: T5Config,
940
+ input_shape: Tuple[int] = (1, 1),
941
+ seed: int = 0,
942
+ dtype: jnp.dtype = jnp.float32,
943
+ _do_init: bool = True,
944
+ gradient_checkpointing: bool = False,
945
+ **kwargs,
946
+ ):
947
+ module = self.module_class(config=config, dtype=dtype, gradient_checkpointing=gradient_checkpointing, **kwargs)
948
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
949
+
950
+ def enable_gradient_checkpointing(self):
951
+ self._module = self.module_class(
952
+ config=self.config,
953
+ dtype=self.dtype,
954
+ gradient_checkpointing=True,
955
+ )
956
+
957
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
958
+ # init input tensors
959
+ input_ids = jnp.zeros(input_shape, dtype="i4")
960
+
961
+ attention_mask = jnp.ones_like(input_ids)
962
+ args = [input_ids, attention_mask]
963
+ if self.module_class not in [FlaxT5EncoderModule]:
964
+ decoder_input_ids = jnp.ones_like(input_ids)
965
+ decoder_attention_mask = jnp.ones_like(input_ids)
966
+ args.extend([decoder_input_ids, decoder_attention_mask])
967
+
968
+ params_rng, dropout_rng = jax.random.split(rng)
969
+ rngs = {"params": params_rng, "dropout": dropout_rng}
970
+
971
+ random_params = self.module.init(
972
+ rngs,
973
+ *args,
974
+ )["params"]
975
+
976
+ if params is not None:
977
+ random_params = flatten_dict(unfreeze(random_params))
978
+ params = flatten_dict(unfreeze(params))
979
+ for missing_key in self._missing_keys:
980
+ params[missing_key] = random_params[missing_key]
981
+ self._missing_keys = set()
982
+ return freeze(unflatten_dict(params))
983
+ else:
984
+ return random_params
985
+
986
+ @add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)
987
+ def __call__(
988
+ self,
989
+ input_ids: jnp.ndarray,
990
+ attention_mask: Optional[jnp.ndarray] = None,
991
+ decoder_input_ids: jnp.ndarray = None,
992
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
993
+ output_attentions: Optional[bool] = None,
994
+ output_hidden_states: Optional[bool] = None,
995
+ return_dict: Optional[bool] = None,
996
+ train: bool = False,
997
+ params: dict = None,
998
+ dropout_rng: PRNGKey = None,
999
+ ):
1000
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1001
+ output_hidden_states = (
1002
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1003
+ )
1004
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1005
+
1006
+ if decoder_input_ids is None:
1007
+ raise ValueError(
1008
+ "Make sure to provide both `input_ids` and `decoder_input_ids`. `decoder_input_ids` is not passed"
1009
+ " here."
1010
+ )
1011
+
1012
+ # prepare encoder inputs
1013
+ if attention_mask is None:
1014
+ attention_mask = jnp.ones_like(input_ids)
1015
+
1016
+ # prepare decoder inputs
1017
+ if decoder_attention_mask is None:
1018
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
1019
+
1020
+ # Handle any PRNG if needed
1021
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1022
+
1023
+ return self.module.apply(
1024
+ {"params": params or self.params},
1025
+ input_ids=jnp.array(input_ids, dtype="i4"),
1026
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1027
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1028
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1029
+ output_attentions=output_attentions,
1030
+ output_hidden_states=output_hidden_states,
1031
+ return_dict=return_dict,
1032
+ deterministic=not train,
1033
+ rngs=rngs,
1034
+ )
1035
+
1036
+ def init_cache(self, batch_size, max_length, encoder_outputs):
1037
+ r"""
1038
+ Args:
1039
+ batch_size (`int`):
1040
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
1041
+ max_length (`int`):
1042
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
1043
+ cache.
1044
+ encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
1045
+ `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
1046
+ `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
1047
+ is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
1048
+ cross-attention of the decoder.
1049
+ """
1050
+ # init input variables to retrieve cache
1051
+ decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
1052
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
1053
+
1054
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, **kwargs):
1055
+ decoder_module = module._get_decoder_module()
1056
+ return decoder_module(
1057
+ decoder_input_ids,
1058
+ decoder_attention_mask,
1059
+ **kwargs,
1060
+ )
1061
+
1062
+ init_variables = self.module.init(
1063
+ jax.random.PRNGKey(0),
1064
+ decoder_input_ids=decoder_input_ids,
1065
+ decoder_attention_mask=decoder_attention_mask,
1066
+ encoder_hidden_states=encoder_outputs[0],
1067
+ init_cache=True,
1068
+ method=_decoder_forward, # we only need to call the decoder to init the cache
1069
+ )
1070
+ return unfreeze(init_variables["cache"])
1071
+
1072
+ @add_start_docstrings(T5_ENCODE_INPUTS_DOCSTRING)
1073
+ @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=T5Config)
1074
+ def encode(
1075
+ self,
1076
+ input_ids: jnp.ndarray,
1077
+ attention_mask: Optional[jnp.ndarray] = None,
1078
+ output_attentions: Optional[bool] = None,
1079
+ output_hidden_states: Optional[bool] = None,
1080
+ return_dict: Optional[bool] = None,
1081
+ train: bool = False,
1082
+ params: dict = None,
1083
+ dropout_rng: PRNGKey = None,
1084
+ ):
1085
+ r"""
1086
+ Returns:
1087
+
1088
+ Example:
1089
+
1090
+ ```python
1091
+ >>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration
1092
+
1093
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1094
+ >>> model = FlaxT5ForConditionalGeneration.from_pretrained("t5-small")
1095
+
1096
+ >>> text = "My friends are cool but they eat too many carbs."
1097
+ >>> inputs = tokenizer(text, return_tensors="np")
1098
+ >>> encoder_outputs = model.encode(**inputs)
1099
+ ```"""
1100
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1101
+ output_hidden_states = (
1102
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1103
+ )
1104
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1105
+
1106
+ if attention_mask is None:
1107
+ attention_mask = jnp.ones_like(input_ids)
1108
+
1109
+ # Handle any PRNG if needed
1110
+ rngs = {}
1111
+ if dropout_rng is not None:
1112
+ rngs["dropout"] = dropout_rng
1113
+
1114
+ def _encoder_forward(module, input_ids, attention_mask, **kwargs):
1115
+ encode_module = module._get_encoder_module()
1116
+ return encode_module(input_ids, attention_mask, **kwargs)
1117
+
1118
+ return self.module.apply(
1119
+ {"params": params or self.params},
1120
+ input_ids=jnp.array(input_ids, dtype="i4"),
1121
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1122
+ output_attentions=output_attentions,
1123
+ output_hidden_states=output_hidden_states,
1124
+ return_dict=return_dict,
1125
+ deterministic=not train,
1126
+ rngs=rngs,
1127
+ method=_encoder_forward,
1128
+ )
1129
+
1130
+ @add_start_docstrings(T5_DECODE_INPUTS_DOCSTRING)
1131
+ @replace_return_docstrings(output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=T5Config)
1132
+ def decode(
1133
+ self,
1134
+ decoder_input_ids,
1135
+ encoder_outputs,
1136
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1137
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1138
+ past_key_values: dict = None,
1139
+ output_attentions: Optional[bool] = None,
1140
+ output_hidden_states: Optional[bool] = None,
1141
+ return_dict: Optional[bool] = None,
1142
+ train: bool = False,
1143
+ params: dict = None,
1144
+ dropout_rng: PRNGKey = None,
1145
+ ):
1146
+ r"""
1147
+ Returns:
1148
+
1149
+ Example:
1150
+
1151
+ ```python
1152
+ >>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration
1153
+ >>> import jax.numpy as jnp
1154
+
1155
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1156
+ >>> model = FlaxT5ForConditionalGeneration.from_pretrained("t5-small")
1157
+
1158
+ >>> text = "My friends are cool but they eat too many carbs."
1159
+ >>> inputs = tokenizer(text, return_tensors="np")
1160
+ >>> encoder_outputs = model.encode(**inputs)
1161
+
1162
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1163
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1164
+
1165
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1166
+ >>> logits = outputs.logits
1167
+ ```"""
1168
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1169
+ output_hidden_states = (
1170
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1171
+ )
1172
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1173
+
1174
+ encoder_hidden_states = encoder_outputs[0]
1175
+ if encoder_attention_mask is None:
1176
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1177
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1178
+
1179
+ batch_size, sequence_length = decoder_input_ids.shape
1180
+ if decoder_attention_mask is None:
1181
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1182
+
1183
+ # Handle any PRNG if needed
1184
+ rngs = {}
1185
+ if dropout_rng is not None:
1186
+ rngs["dropout"] = dropout_rng
1187
+
1188
+ inputs = {"params": params or self.params}
1189
+
1190
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1191
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1192
+ # it can be changed by FlaxT5Attention module
1193
+ if past_key_values:
1194
+ inputs["cache"] = past_key_values
1195
+ mutable = ["cache"]
1196
+ else:
1197
+ mutable = False
1198
+
1199
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, **kwargs):
1200
+ decoder_module = module._get_decoder_module()
1201
+ return decoder_module(
1202
+ decoder_input_ids,
1203
+ decoder_attention_mask,
1204
+ **kwargs,
1205
+ )
1206
+
1207
+ outputs = self.module.apply(
1208
+ inputs,
1209
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1210
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1211
+ encoder_hidden_states=encoder_hidden_states,
1212
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1213
+ output_attentions=output_attentions,
1214
+ output_hidden_states=output_hidden_states,
1215
+ return_dict=return_dict,
1216
+ deterministic=not train,
1217
+ rngs=rngs,
1218
+ mutable=mutable,
1219
+ method=_decoder_forward,
1220
+ )
1221
+
1222
+ # add updated cache to model output
1223
+ if past_key_values is not None and return_dict:
1224
+ outputs, past = outputs
1225
+ outputs["past_key_values"] = unfreeze(past["cache"])
1226
+ return outputs
1227
+ elif past_key_values is not None and not return_dict:
1228
+ outputs, past = outputs
1229
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1230
+
1231
+ return outputs
1232
+
1233
+
1234
+ T5_START_DOCSTRING = r"""
1235
+ The T5 model was proposed in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text
1236
+ Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan
1237
+ Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu. It's an encoder decoder transformer pre-trained in a
1238
+ text-to-text denoising generative setting.
1239
+
1240
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
1241
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1242
+ etc.)
1243
+
1244
+ This model is also a Flax Linen
1245
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
1246
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
1247
+
1248
+ Finally, this model supports inherent JAX features such as:
1249
+
1250
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
1251
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
1252
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
1253
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
1254
+
1255
+ Parameters:
1256
+ config ([`T5Config`]): Model configuration class with all the parameters of the model.
1257
+ Initializing with a config file does not load the weights associated with the model, only the
1258
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
1259
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
1260
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
1261
+ `jax.numpy.bfloat16` (on TPUs).
1262
+
1263
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
1264
+ specified all the computation will be performed with the given `dtype`.
1265
+
1266
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
1267
+ parameters.**
1268
+
1269
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
1270
+ [`~FlaxPreTrainedModel.to_bf16`].
1271
+ """
1272
+
1273
+
1274
+ @add_start_docstrings(
1275
+ "The bare T5 Model transformer outputting raw hidden-stateswithout any specific head on top.",
1276
+ T5_START_DOCSTRING,
1277
+ )
1278
+ class FlaxT5Module(nn.Module):
1279
+ config: T5Config
1280
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1281
+ gradient_checkpointing: bool = False
1282
+
1283
+ def _get_encoder_module(self):
1284
+ return self.encoder
1285
+
1286
+ def _get_decoder_module(self):
1287
+ return self.decoder
1288
+
1289
+ def setup(self):
1290
+ self.shared = nn.Embed(
1291
+ self.config.vocab_size,
1292
+ self.config.d_model,
1293
+ embedding_init=jax.nn.initializers.normal(self.config.initializer_factor * 1.0),
1294
+ dtype=self.dtype,
1295
+ )
1296
+
1297
+ encoder_config = copy.deepcopy(self.config)
1298
+ encoder_config.causal = False
1299
+ self.encoder = FlaxT5Stack(
1300
+ encoder_config,
1301
+ embed_tokens=self.shared,
1302
+ dtype=self.dtype,
1303
+ gradient_checkpointing=self.gradient_checkpointing,
1304
+ )
1305
+
1306
+ decoder_config = copy.deepcopy(self.config)
1307
+ decoder_config.causal = True
1308
+ decoder_config.num_layers = self.config.num_decoder_layers
1309
+ self.decoder = FlaxT5Stack(
1310
+ decoder_config,
1311
+ embed_tokens=self.shared,
1312
+ dtype=self.dtype,
1313
+ gradient_checkpointing=self.gradient_checkpointing,
1314
+ )
1315
+
1316
+ def __call__(
1317
+ self,
1318
+ input_ids=None,
1319
+ attention_mask=None,
1320
+ decoder_input_ids=None,
1321
+ decoder_attention_mask=None,
1322
+ encoder_outputs=None,
1323
+ output_attentions=None,
1324
+ output_hidden_states=None,
1325
+ return_dict=None,
1326
+ deterministic: bool = True,
1327
+ ):
1328
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1329
+
1330
+ # Encode if needed (training, first prediction pass)
1331
+ encoder_outputs = self.encoder(
1332
+ input_ids=input_ids,
1333
+ attention_mask=attention_mask,
1334
+ output_attentions=output_attentions,
1335
+ output_hidden_states=output_hidden_states,
1336
+ return_dict=return_dict,
1337
+ deterministic=deterministic,
1338
+ )
1339
+
1340
+ # Decode
1341
+ decoder_outputs = self.decoder(
1342
+ input_ids=decoder_input_ids,
1343
+ attention_mask=decoder_attention_mask,
1344
+ encoder_hidden_states=encoder_outputs[0],
1345
+ encoder_attention_mask=attention_mask,
1346
+ output_attentions=output_attentions,
1347
+ output_hidden_states=output_hidden_states,
1348
+ return_dict=return_dict,
1349
+ deterministic=deterministic,
1350
+ )
1351
+
1352
+ if not return_dict:
1353
+ return decoder_outputs + encoder_outputs
1354
+
1355
+ return FlaxSeq2SeqModelOutput(
1356
+ last_hidden_state=decoder_outputs.last_hidden_state,
1357
+ past_key_values=decoder_outputs.past_key_values,
1358
+ decoder_hidden_states=decoder_outputs.hidden_states,
1359
+ decoder_attentions=decoder_outputs.attentions,
1360
+ cross_attentions=decoder_outputs.cross_attentions,
1361
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1362
+ encoder_hidden_states=encoder_outputs.hidden_states,
1363
+ encoder_attentions=encoder_outputs.attentions,
1364
+ )
1365
+
1366
+
1367
+ class FlaxT5Model(FlaxT5PreTrainedModel):
1368
+ module_class = FlaxT5Module
1369
+
1370
+
1371
+ append_call_sample_docstring(FlaxT5Model, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
1372
+
1373
+ FLAX_T5_MODEL_DOCSTRING = """
1374
+ Returns:
1375
+
1376
+ Example:
1377
+
1378
+ ```python
1379
+ >>> from transformers import AutoTokenizer, FlaxT5Model
1380
+
1381
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1382
+ >>> model = FlaxT5Model.from_pretrained("t5-small")
1383
+
1384
+ >>> input_ids = tokenizer(
1385
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="np"
1386
+ ... ).input_ids
1387
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="np").input_ids
1388
+
1389
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.
1390
+ >>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.
1391
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
1392
+
1393
+ >>> # forward pass
1394
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
1395
+ >>> last_hidden_states = outputs.last_hidden_state
1396
+ ```
1397
+ """
1398
+
1399
+
1400
+ overwrite_call_docstring(FlaxT5Model, T5_INPUTS_DOCSTRING + FLAX_T5_MODEL_DOCSTRING)
1401
+ append_replace_return_docstrings(FlaxT5Model, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1402
+
1403
+
1404
+ @add_start_docstrings(
1405
+ "The bare T5 Model transformer outputting encoder's raw hidden-states without any specific head on top.",
1406
+ T5_START_DOCSTRING,
1407
+ )
1408
+ class FlaxT5EncoderModule(nn.Module):
1409
+ config: T5Config
1410
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1411
+ gradient_checkpointing: bool = False
1412
+
1413
+ def setup(self):
1414
+ self.shared = nn.Embed(
1415
+ self.config.vocab_size,
1416
+ self.config.d_model,
1417
+ embedding_init=jax.nn.initializers.normal(self.config.initializer_factor * 1.0),
1418
+ dtype=self.dtype,
1419
+ )
1420
+
1421
+ encoder_config = copy.deepcopy(self.config)
1422
+ encoder_config.is_decoder = False
1423
+ encoder_config.is_encoder_decoder = False
1424
+ encoder_config.causal = False
1425
+ self.encoder = FlaxT5Stack(
1426
+ encoder_config,
1427
+ embed_tokens=self.shared,
1428
+ dtype=self.dtype,
1429
+ gradient_checkpointing=self.gradient_checkpointing,
1430
+ )
1431
+
1432
+ def __call__(
1433
+ self,
1434
+ input_ids=None,
1435
+ attention_mask=None,
1436
+ output_attentions=False,
1437
+ output_hidden_states=False,
1438
+ return_dict: bool = True,
1439
+ deterministic: bool = True,
1440
+ ):
1441
+ # Encode if needed (training, first prediction pass)
1442
+ encoder_outputs = self.encoder(
1443
+ input_ids=input_ids,
1444
+ attention_mask=attention_mask,
1445
+ output_attentions=output_attentions,
1446
+ output_hidden_states=output_hidden_states,
1447
+ return_dict=return_dict,
1448
+ deterministic=deterministic,
1449
+ )
1450
+
1451
+ return encoder_outputs
1452
+
1453
+
1454
+ class FlaxT5EncoderModel(FlaxT5PreTrainedModel):
1455
+ module_class = FlaxT5EncoderModule
1456
+
1457
+ @add_start_docstrings_to_model_forward(T5_ENCODE_INPUTS_DOCSTRING)
1458
+ def __call__(
1459
+ self,
1460
+ input_ids: jnp.ndarray,
1461
+ attention_mask: Optional[jnp.ndarray] = None,
1462
+ output_attentions: Optional[bool] = None,
1463
+ output_hidden_states: Optional[bool] = None,
1464
+ return_dict: Optional[bool] = None,
1465
+ train: bool = False,
1466
+ params: dict = None,
1467
+ dropout_rng: PRNGKey = None,
1468
+ ):
1469
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1470
+ output_hidden_states = (
1471
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1472
+ )
1473
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1474
+
1475
+ # prepare encoder inputs
1476
+ if attention_mask is None:
1477
+ attention_mask = jnp.ones_like(input_ids)
1478
+
1479
+ # Handle any PRNG if needed
1480
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1481
+
1482
+ return self.module.apply(
1483
+ {"params": params or self.params},
1484
+ input_ids=jnp.array(input_ids, dtype="i4"),
1485
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1486
+ output_attentions=output_attentions,
1487
+ output_hidden_states=output_hidden_states,
1488
+ return_dict=return_dict,
1489
+ deterministic=not train,
1490
+ rngs=rngs,
1491
+ )
1492
+
1493
+
1494
+ @add_start_docstrings("""T5 Model with a `language modeling` head on top.""", T5_START_DOCSTRING)
1495
+ class FlaxT5ForConditionalGenerationModule(nn.Module):
1496
+ config: T5Config
1497
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1498
+ gradient_checkpointing: bool = False
1499
+
1500
+ def _get_encoder_module(self):
1501
+ return self.encoder
1502
+
1503
+ def _get_decoder_module(self):
1504
+ return self.decoder
1505
+
1506
+ def setup(self):
1507
+ self.model_dim = self.config.d_model
1508
+
1509
+ self.shared = nn.Embed(
1510
+ self.config.vocab_size,
1511
+ self.config.d_model,
1512
+ embedding_init=jax.nn.initializers.normal(self.config.initializer_factor),
1513
+ dtype=self.dtype,
1514
+ )
1515
+
1516
+ encoder_config = copy.deepcopy(self.config)
1517
+ encoder_config.causal = False
1518
+ encoder_config.use_cache = False
1519
+ encoder_config.is_encoder_decoder = False
1520
+ self.encoder = FlaxT5Stack(
1521
+ encoder_config, self.shared, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1522
+ )
1523
+
1524
+ decoder_config = copy.deepcopy(self.config)
1525
+ decoder_config.causal = True
1526
+ decoder_config.is_encoder_decoder = False
1527
+ decoder_config.num_layers = self.config.num_decoder_layers
1528
+ self.decoder = FlaxT5Stack(
1529
+ decoder_config, self.shared, dtype=self.dtype, gradient_checkpointing=self.gradient_checkpointing
1530
+ )
1531
+
1532
+ self.lm_head = nn.Dense(
1533
+ self.config.vocab_size,
1534
+ use_bias=False,
1535
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_factor),
1536
+ dtype=self.dtype,
1537
+ )
1538
+
1539
+ def __call__(
1540
+ self,
1541
+ input_ids=None,
1542
+ attention_mask=None,
1543
+ decoder_input_ids=None,
1544
+ decoder_attention_mask=None,
1545
+ encoder_outputs=None,
1546
+ output_attentions=None,
1547
+ output_hidden_states=None,
1548
+ return_dict=None,
1549
+ deterministic: bool = True,
1550
+ ):
1551
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1552
+
1553
+ # Encode
1554
+ encoder_outputs = self.encoder(
1555
+ input_ids=input_ids,
1556
+ attention_mask=attention_mask,
1557
+ output_attentions=output_attentions,
1558
+ output_hidden_states=output_hidden_states,
1559
+ return_dict=return_dict,
1560
+ deterministic=deterministic,
1561
+ )
1562
+
1563
+ hidden_states = encoder_outputs[0]
1564
+
1565
+ # Decode
1566
+ decoder_outputs = self.decoder(
1567
+ input_ids=decoder_input_ids,
1568
+ attention_mask=decoder_attention_mask,
1569
+ encoder_hidden_states=hidden_states,
1570
+ encoder_attention_mask=attention_mask,
1571
+ output_attentions=output_attentions,
1572
+ output_hidden_states=output_hidden_states,
1573
+ return_dict=return_dict,
1574
+ deterministic=deterministic,
1575
+ )
1576
+
1577
+ sequence_output = decoder_outputs[0]
1578
+
1579
+ if self.config.tie_word_embeddings:
1580
+ # Rescale output before projecting on vocab
1581
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
1582
+ sequence_output = sequence_output * (self.model_dim**-0.5)
1583
+
1584
+ if self.config.tie_word_embeddings:
1585
+ shared_embedding = self.shared.variables["params"]["embedding"]
1586
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, sequence_output)
1587
+ else:
1588
+ lm_logits = self.lm_head(sequence_output)
1589
+
1590
+ if not return_dict:
1591
+ return (lm_logits,) + decoder_outputs[1:] + encoder_outputs
1592
+
1593
+ return FlaxSeq2SeqLMOutput(
1594
+ logits=lm_logits,
1595
+ past_key_values=decoder_outputs.past_key_values,
1596
+ decoder_hidden_states=decoder_outputs.hidden_states,
1597
+ decoder_attentions=decoder_outputs.attentions,
1598
+ cross_attentions=decoder_outputs.cross_attentions,
1599
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1600
+ encoder_hidden_states=encoder_outputs.hidden_states,
1601
+ encoder_attentions=encoder_outputs.attentions,
1602
+ )
1603
+
1604
+
1605
+ class FlaxT5ForConditionalGeneration(FlaxT5PreTrainedModel):
1606
+ module_class = FlaxT5ForConditionalGenerationModule
1607
+
1608
+ @add_start_docstrings(T5_DECODE_INPUTS_DOCSTRING)
1609
+ @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=T5Config)
1610
+ def decode(
1611
+ self,
1612
+ decoder_input_ids,
1613
+ encoder_outputs,
1614
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1615
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1616
+ past_key_values: dict = None,
1617
+ output_attentions: Optional[bool] = None,
1618
+ output_hidden_states: Optional[bool] = None,
1619
+ return_dict: Optional[bool] = None,
1620
+ train: bool = False,
1621
+ params: dict = None,
1622
+ dropout_rng: PRNGKey = None,
1623
+ ):
1624
+ r"""
1625
+ Returns:
1626
+
1627
+ Example:
1628
+
1629
+ ```python
1630
+ >>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration
1631
+ >>> import jax.numpy as jnp
1632
+
1633
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1634
+ >>> model = FlaxT5ForConditionalGeneration.from_pretrained("t5-small")
1635
+
1636
+ >>> text = "summarize: My friends are cool but they eat too many carbs."
1637
+ >>> inputs = tokenizer(text, return_tensors="np")
1638
+ >>> encoder_outputs = model.encode(**inputs)
1639
+
1640
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1641
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1642
+
1643
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1644
+ >>> logits = outputs.logits
1645
+ ```"""
1646
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1647
+ output_hidden_states = (
1648
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1649
+ )
1650
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1651
+
1652
+ encoder_hidden_states = encoder_outputs[0]
1653
+ if encoder_attention_mask is None:
1654
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1655
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1656
+
1657
+ batch_size, sequence_length = decoder_input_ids.shape
1658
+ if decoder_attention_mask is None:
1659
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1660
+
1661
+ # Handle any PRNG if needed
1662
+ rngs = {}
1663
+ if dropout_rng is not None:
1664
+ rngs["dropout"] = dropout_rng
1665
+
1666
+ inputs = {"params": params or self.params}
1667
+
1668
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1669
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1670
+ # it can be changed by FlaxT5Attention module
1671
+ if past_key_values:
1672
+ inputs["cache"] = past_key_values
1673
+ mutable = ["cache"]
1674
+ else:
1675
+ mutable = False
1676
+
1677
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, **kwargs):
1678
+ decoder_module = module._get_decoder_module()
1679
+ decoder_outputs = decoder_module(
1680
+ decoder_input_ids,
1681
+ decoder_attention_mask,
1682
+ **kwargs,
1683
+ )
1684
+
1685
+ sequence_output = decoder_outputs[0]
1686
+
1687
+ if self.config.tie_word_embeddings:
1688
+ # Rescale output before projecting on vocab
1689
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
1690
+ sequence_output = sequence_output * (self.config.d_model**-0.5)
1691
+
1692
+ if self.config.tie_word_embeddings:
1693
+ shared_embedding = module.shared.variables["params"]["embedding"]
1694
+ lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, sequence_output)
1695
+ else:
1696
+ lm_logits = module.lm_head(sequence_output)
1697
+
1698
+ return lm_logits, decoder_outputs
1699
+
1700
+ outputs = self.module.apply(
1701
+ inputs,
1702
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1703
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1704
+ encoder_hidden_states=encoder_hidden_states,
1705
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1706
+ output_attentions=output_attentions,
1707
+ output_hidden_states=output_hidden_states,
1708
+ return_dict=return_dict,
1709
+ deterministic=not train,
1710
+ rngs=rngs,
1711
+ mutable=mutable,
1712
+ method=_decoder_forward,
1713
+ )
1714
+
1715
+ if past_key_values is None:
1716
+ lm_logits, decoder_outputs = outputs
1717
+ else:
1718
+ (lm_logits, decoder_outputs), past = outputs
1719
+
1720
+ if return_dict:
1721
+ outputs = FlaxCausalLMOutputWithCrossAttentions(
1722
+ logits=lm_logits,
1723
+ hidden_states=decoder_outputs.hidden_states,
1724
+ attentions=decoder_outputs.attentions,
1725
+ cross_attentions=decoder_outputs.cross_attentions,
1726
+ )
1727
+ else:
1728
+ outputs = (lm_logits,) + decoder_outputs[1:]
1729
+
1730
+ # add updated cache to model output
1731
+ if past_key_values is not None and return_dict:
1732
+ outputs["past_key_values"] = unfreeze(past["cache"])
1733
+ return outputs
1734
+ elif past_key_values is not None and not return_dict:
1735
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1736
+
1737
+ return outputs
1738
+
1739
+ def prepare_inputs_for_generation(
1740
+ self,
1741
+ decoder_input_ids,
1742
+ max_length,
1743
+ attention_mask: Optional[jnp.DeviceArray] = None,
1744
+ decoder_attention_mask: Optional[jnp.DeviceArray] = None,
1745
+ encoder_outputs=None,
1746
+ **kwargs,
1747
+ ):
1748
+ # initializing the cache
1749
+ batch_size, seq_length = decoder_input_ids.shape
1750
+
1751
+ past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
1752
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1753
+ # But since the decoder uses a causal mask, those positions are masked anyways.
1754
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
1755
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1756
+ if decoder_attention_mask is not None:
1757
+ extended_attention_mask = jax.lax.dynamic_update_slice(
1758
+ extended_attention_mask, decoder_attention_mask, (0, 0)
1759
+ )
1760
+
1761
+ return {
1762
+ "past_key_values": past_key_values,
1763
+ "encoder_outputs": encoder_outputs,
1764
+ "encoder_attention_mask": attention_mask,
1765
+ "decoder_attention_mask": extended_attention_mask,
1766
+ }
1767
+
1768
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1769
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1770
+ return model_kwargs
1771
+
1772
+
1773
+ FLAX_T5_CONDITIONAL_GENERATION_DOCSTRING = """
1774
+ Returns:
1775
+
1776
+ Example:
1777
+
1778
+ ```python
1779
+ >>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration
1780
+
1781
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1782
+ >>> model = FlaxT5ForConditionalGeneration.from_pretrained("t5-small")
1783
+
1784
+ >>> ARTICLE_TO_SUMMARIZE = "summarize: My friends are cool but they eat too many carbs."
1785
+ >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], return_tensors="np")
1786
+
1787
+ >>> # Generate Summary
1788
+ >>> summary_ids = model.generate(inputs["input_ids"]).sequences
1789
+ >>> print(tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=False))
1790
+ ```
1791
+ """
1792
+
1793
+
1794
+ overwrite_call_docstring(
1795
+ FlaxT5ForConditionalGeneration, T5_INPUTS_DOCSTRING + FLAX_T5_CONDITIONAL_GENERATION_DOCSTRING
1796
+ )
1797
+ append_replace_return_docstrings(
1798
+ FlaxT5ForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC
1799
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/modeling_tf_t5.py ADDED
@@ -0,0 +1,1628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 T5 Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. 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
+ """ TF 2.0 T5 model."""
17
+
18
+ import copy
19
+ import itertools
20
+ import math
21
+ import warnings
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import tensorflow as tf
26
+ from tensorflow.compiler.tf2xla.python.xla import dynamic_slice
27
+
28
+ from ...activations_tf import get_tf_activation
29
+ from ...modeling_tf_outputs import (
30
+ TFBaseModelOutput,
31
+ TFBaseModelOutputWithPastAndCrossAttentions,
32
+ TFSeq2SeqLMOutput,
33
+ TFSeq2SeqModelOutput,
34
+ )
35
+ from ...modeling_tf_utils import (
36
+ TFCausalLanguageModelingLoss,
37
+ TFModelInputType,
38
+ TFPreTrainedModel,
39
+ get_initializer,
40
+ keras_serializable,
41
+ unpack_inputs,
42
+ )
43
+ from ...tf_utils import shape_list, stable_softmax
44
+ from ...utils import (
45
+ DUMMY_INPUTS,
46
+ DUMMY_MASK,
47
+ ContextManagers,
48
+ add_start_docstrings,
49
+ add_start_docstrings_to_model_forward,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from .configuration_t5 import T5Config
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CONFIG_FOR_DOC = "T5Config"
59
+
60
+ TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST = [
61
+ "t5-small",
62
+ "t5-base",
63
+ "t5-large",
64
+ "t5-3b",
65
+ "t5-11b",
66
+ # See all T5 models at https://huggingface.co/models?filter=t5
67
+ ]
68
+
69
+ ####################################################
70
+ # TF 2.0 Models are constructed using Keras imperative API by sub-classing
71
+ # - tf.keras.layers.Layer for the layers and
72
+ # - TFPreTrainedModel for the models (it-self a sub-class of tf.keras.Model)
73
+ ####################################################
74
+
75
+
76
+ class TFT5LayerNorm(tf.keras.layers.Layer):
77
+ def __init__(self, epsilon=1e-6, **kwargs):
78
+ """
79
+ Construct a layernorm module in the T5 style No bias and no subtraction of mean.
80
+ """
81
+ super().__init__(**kwargs)
82
+ self.variance_epsilon = epsilon
83
+
84
+ def build(self, input_shape):
85
+ """Build shared word embedding layer"""
86
+ self.weight = self.add_weight("weight", shape=(input_shape[-1],), initializer="ones")
87
+ super().build(input_shape)
88
+
89
+ def call(self, hidden_states):
90
+ variance = tf.math.reduce_mean(tf.math.square(hidden_states), axis=-1, keepdims=True)
91
+ hidden_states = hidden_states * tf.math.rsqrt(variance + self.variance_epsilon)
92
+ return self.weight * hidden_states
93
+
94
+
95
+ class TFT5DenseActDense(tf.keras.layers.Layer):
96
+ def __init__(self, config, **kwargs):
97
+ super().__init__(**kwargs)
98
+ wi_initializer = tf.keras.initializers.RandomNormal(
99
+ mean=0, stddev=config.initializer_factor * (config.d_model**-0.5)
100
+ )
101
+ wo_initializer = tf.keras.initializers.RandomNormal(
102
+ mean=0, stddev=config.initializer_factor * (config.d_ff**-0.5)
103
+ )
104
+ self.wi = tf.keras.layers.Dense(
105
+ config.d_ff, use_bias=False, name="wi", kernel_initializer=wi_initializer
106
+ ) # Update init weights as in flax
107
+ self.wo = tf.keras.layers.Dense(
108
+ config.d_model, use_bias=False, name="wo", kernel_initializer=wo_initializer
109
+ ) # Update init weights as in flax
110
+ self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
111
+ self.act = get_tf_activation(config.dense_act_fn)
112
+
113
+ def call(self, hidden_states, training=False):
114
+ hidden_states = self.wi(hidden_states)
115
+ hidden_states = self.act(hidden_states)
116
+ hidden_states = self.dropout(hidden_states, training=training)
117
+ hidden_states = self.wo(hidden_states)
118
+ return hidden_states
119
+
120
+
121
+ class TFT5DenseGatedActDense(tf.keras.layers.Layer):
122
+ def __init__(self, config, **kwargs):
123
+ super().__init__(**kwargs)
124
+ wi_initializer = tf.keras.initializers.RandomNormal(
125
+ mean=0, stddev=config.initializer_factor * (config.d_model**-0.5)
126
+ )
127
+ wo_initializer = tf.keras.initializers.RandomNormal(
128
+ mean=0, stddev=config.initializer_factor * (config.d_ff**-0.5)
129
+ )
130
+ self.wi_0 = tf.keras.layers.Dense(
131
+ config.d_ff, use_bias=False, name="wi_0", kernel_initializer=wi_initializer
132
+ ) # Update init weights as in flax
133
+ self.wi_1 = tf.keras.layers.Dense(
134
+ config.d_ff, use_bias=False, name="wi_1", kernel_initializer=wi_initializer
135
+ ) # Update init weights as in flax
136
+ self.wo = tf.keras.layers.Dense(
137
+ config.d_model, use_bias=False, name="wo", kernel_initializer=wo_initializer
138
+ ) # Update init weights as in flax
139
+ self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
140
+ self.act = get_tf_activation(config.dense_act_fn)
141
+
142
+ def call(self, hidden_states, training=False):
143
+ hidden_gelu = self.act(self.wi_0(hidden_states))
144
+ hidden_linear = self.wi_1(hidden_states)
145
+ hidden_states = hidden_gelu * hidden_linear
146
+ hidden_states = self.dropout(hidden_states, training=training)
147
+ hidden_states = self.wo(hidden_states)
148
+ return hidden_states
149
+
150
+
151
+ class TFT5LayerFF(tf.keras.layers.Layer):
152
+ def __init__(self, config, **kwargs):
153
+ super().__init__(**kwargs)
154
+ if config.is_gated_act:
155
+ self.DenseReluDense = TFT5DenseGatedActDense(config, name="DenseReluDense")
156
+ else:
157
+ self.DenseReluDense = TFT5DenseActDense(config, name="DenseReluDense")
158
+
159
+ self.layer_norm = TFT5LayerNorm(epsilon=config.layer_norm_epsilon, name="layer_norm")
160
+ self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
161
+
162
+ def call(self, hidden_states, training=False):
163
+ normed_hidden_states = self.layer_norm(hidden_states)
164
+ dense_output = self.DenseReluDense(normed_hidden_states, training=training)
165
+ hidden_states = hidden_states + self.dropout(dense_output, training=training)
166
+ return hidden_states
167
+
168
+
169
+ class TFT5Attention(tf.keras.layers.Layer):
170
+ NEW_ID = itertools.count()
171
+
172
+ def __init__(self, config, has_relative_attention_bias=False, **kwargs):
173
+ super().__init__(**kwargs)
174
+ self.layer_id = next(TFT5Attention.NEW_ID)
175
+ self.is_decoder = config.is_decoder
176
+ self.use_cache = config.use_cache
177
+ self.has_relative_attention_bias = has_relative_attention_bias
178
+ self.output_attentions = config.output_attentions
179
+
180
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
181
+ self.relative_attention_max_distance = config.relative_attention_max_distance
182
+ self.d_model = config.d_model
183
+ self.key_value_proj_dim = config.d_kv
184
+ self.n_heads = config.num_heads
185
+ self.inner_dim = self.n_heads * self.key_value_proj_dim
186
+
187
+ # Mesh TensorFlow initialization to avoid scaling before softmax
188
+ q_initializer = tf.keras.initializers.RandomNormal(
189
+ mean=0, stddev=config.initializer_factor * ((self.inner_dim * self.key_value_proj_dim) ** -0.5)
190
+ )
191
+ k_initializer = tf.keras.initializers.RandomNormal(
192
+ mean=0, stddev=config.initializer_factor * (self.inner_dim**-0.5)
193
+ )
194
+ v_initializer = tf.keras.initializers.RandomNormal(
195
+ mean=0, stddev=config.initializer_factor * (self.inner_dim**-0.5)
196
+ )
197
+ o_initializer = tf.keras.initializers.RandomNormal(
198
+ mean=0, stddev=config.initializer_factor * (self.inner_dim**-0.5)
199
+ )
200
+ self.relative_attention_bias_initializer = tf.keras.initializers.RandomNormal(
201
+ mean=0, stddev=config.initializer_factor * (self.inner_dim**-0.5)
202
+ )
203
+
204
+ self.q = tf.keras.layers.Dense(
205
+ self.inner_dim, use_bias=False, name="q", kernel_initializer=q_initializer
206
+ ) # Update init weights as in flax
207
+ self.k = tf.keras.layers.Dense(
208
+ self.inner_dim, use_bias=False, name="k", kernel_initializer=k_initializer
209
+ ) # Update init weights as in flax
210
+ self.v = tf.keras.layers.Dense(
211
+ self.inner_dim, use_bias=False, name="v", kernel_initializer=v_initializer
212
+ ) # Update init weights as in flax
213
+ self.o = tf.keras.layers.Dense(
214
+ self.d_model, use_bias=False, name="o", kernel_initializer=o_initializer
215
+ ) # Update init weights as in flax
216
+ self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
217
+
218
+ self.pruned_heads = set()
219
+
220
+ def build(self, input_shape):
221
+ if self.has_relative_attention_bias:
222
+ with tf.name_scope("relative_attention_bias"):
223
+ self.relative_attention_bias = self.add_weight(
224
+ name="embeddings",
225
+ shape=[self.relative_attention_num_buckets, self.n_heads],
226
+ initializer=self.relative_attention_bias_initializer, # Add initializer
227
+ )
228
+
229
+ return super().build(input_shape)
230
+
231
+ def prune_heads(self, heads):
232
+ raise NotImplementedError
233
+
234
+ @staticmethod
235
+ def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
236
+ """
237
+ Adapted from Mesh Tensorflow:
238
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
239
+
240
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
241
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
242
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
243
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
244
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
245
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
246
+
247
+ Args:
248
+ relative_position: an int32 Tensor
249
+ bidirectional: a boolean - whether the attention is bidirectional
250
+ num_buckets: an integer
251
+ max_distance: an integer
252
+
253
+ Returns:
254
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
255
+ """
256
+ relative_buckets = 0
257
+ # n = -relative_position
258
+ if bidirectional:
259
+ num_buckets //= 2
260
+ relative_buckets += (
261
+ tf.cast(tf.math.greater(relative_position, 0), dtype=relative_position.dtype) * num_buckets
262
+ )
263
+ relative_position = tf.math.abs(relative_position)
264
+ else:
265
+ relative_position = -tf.math.minimum(relative_position, 0)
266
+ # now n is in the range [0, inf)
267
+ max_exact = num_buckets // 2
268
+ is_small = tf.math.less(relative_position, max_exact)
269
+ relative_position_if_large = max_exact + tf.cast(
270
+ tf.math.log(tf.cast(relative_position, tf.float32) / tf.cast(max_exact, tf.float32))
271
+ / math.log(max_distance / max_exact)
272
+ * (num_buckets - max_exact),
273
+ dtype=relative_position.dtype,
274
+ )
275
+ relative_position_if_large = tf.math.minimum(relative_position_if_large, num_buckets - 1)
276
+ relative_buckets += tf.where(is_small, relative_position, relative_position_if_large)
277
+ return relative_buckets
278
+
279
+ def compute_bias(self, query_length, key_length):
280
+ """Compute binned relative position bias"""
281
+ context_position = tf.range(query_length)[:, None]
282
+ memory_position = tf.range(key_length)[None, :]
283
+ relative_position = memory_position - context_position # shape (query_length, key_length)
284
+ relative_position_bucket = self._relative_position_bucket(
285
+ relative_position,
286
+ bidirectional=(not self.is_decoder),
287
+ num_buckets=self.relative_attention_num_buckets,
288
+ max_distance=self.relative_attention_max_distance,
289
+ )
290
+ values = tf.gather(
291
+ self.relative_attention_bias, relative_position_bucket
292
+ ) # shape (query_length, key_length, num_heads)
293
+ values = tf.expand_dims(
294
+ tf.transpose(values, [2, 0, 1]), axis=0
295
+ ) # shape (1, num_heads, query_length, key_length)
296
+ return values
297
+
298
+ def call(
299
+ self,
300
+ hidden_states,
301
+ mask=None,
302
+ key_value_states=None,
303
+ position_bias=None,
304
+ past_key_value=None,
305
+ layer_head_mask=None,
306
+ query_length=None,
307
+ use_cache=False,
308
+ training=False,
309
+ output_attentions=False,
310
+ ):
311
+ """
312
+ Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
313
+ """
314
+ # Input is (batch_size, query_length, dim)
315
+ # Mask is (batch_size, key_length) (non-causal) or (batch_size, key_length, key_length)
316
+ # past_key_value[0] is (batch_size, n_heads, q_len - 1, dim_per_head)
317
+ batch_size, seq_length = shape_list(hidden_states)[:2]
318
+
319
+ real_seq_length = seq_length
320
+
321
+ if past_key_value is not None:
322
+ assert (
323
+ len(past_key_value) == 2
324
+ ), f"past_key_value should have 2 past states: keys and values. Got {len(past_key_value)} past states"
325
+ real_seq_length += shape_list(past_key_value[0])[2] if query_length is None else query_length
326
+
327
+ key_length = real_seq_length if key_value_states is None else shape_list(key_value_states)[1]
328
+
329
+ def shape(hidden_states):
330
+ """projection"""
331
+ return tf.transpose(
332
+ tf.reshape(hidden_states, (batch_size, -1, self.n_heads, self.key_value_proj_dim)), perm=(0, 2, 1, 3)
333
+ )
334
+
335
+ def unshape(hidden_states):
336
+ """compute context"""
337
+ return tf.reshape(tf.transpose(hidden_states, perm=(0, 2, 1, 3)), (batch_size, -1, self.inner_dim))
338
+
339
+ def project(hidden_states, proj_layer, key_value_states, past_key_value):
340
+ """projects hidden states correctly to key/query states"""
341
+ if key_value_states is None:
342
+ # self-attn
343
+ # (batch_size, n_heads, seq_length, dim_per_head)
344
+ hidden_states = shape(proj_layer(hidden_states))
345
+ elif past_key_value is None:
346
+ # cross-attn
347
+ # (batch_size, n_heads, seq_length, dim_per_head)
348
+ hidden_states = shape(proj_layer(key_value_states))
349
+
350
+ if past_key_value is not None:
351
+ if key_value_states is None:
352
+ # self-attn
353
+ # (batch_size, n_heads, key_length, dim_per_head)
354
+ hidden_states = tf.concat([past_key_value, hidden_states], axis=2)
355
+ else:
356
+ # cross-attn
357
+ hidden_states = past_key_value
358
+ return hidden_states
359
+
360
+ # get query
361
+ query_states = shape(self.q(hidden_states)) # (batch_size, n_heads, query_length, dim_per_head)
362
+
363
+ # get key/value
364
+ key_states = project(
365
+ hidden_states, self.k, key_value_states, past_key_value[0] if past_key_value is not None else None
366
+ )
367
+ value_states = project(
368
+ hidden_states, self.v, key_value_states, past_key_value[1] if past_key_value is not None else None
369
+ )
370
+
371
+ # to cope with keras serialization
372
+ if self.is_decoder and use_cache:
373
+ present_key_value_state = (key_states, value_states)
374
+ else:
375
+ present_key_value_state = None
376
+
377
+ scores = tf.einsum(
378
+ "bnqd,bnkd->bnqk", query_states, key_states
379
+ ) # (batch_size, n_heads, query_length, key_length)
380
+
381
+ if position_bias is None:
382
+ if not self.has_relative_attention_bias:
383
+ position_bias = tf.zeros((1, self.n_heads, real_seq_length, key_length))
384
+ else:
385
+ position_bias = self.compute_bias(real_seq_length, key_length)
386
+
387
+ # if key and values are already calculated we want only the last query position bias
388
+ if past_key_value is not None:
389
+ if not self.has_relative_attention_bias:
390
+ position_bias = position_bias[:, :, -seq_length:, :]
391
+ else:
392
+ # we might have a padded past structure, in which case we want to fetch the position bias slice
393
+ # right after the most recently filled past index
394
+ most_recently_filled_past_index = tf.reduce_max(tf.where(past_key_value[0][0, 0, :, 0] != 0.0))
395
+ position_bias = dynamic_slice(
396
+ position_bias,
397
+ (0, 0, most_recently_filled_past_index + 1, 0),
398
+ (1, self.n_heads, seq_length, real_seq_length),
399
+ )
400
+
401
+ if mask is not None:
402
+ position_bias = tf.cast(position_bias, dtype=mask.dtype)
403
+ position_bias = position_bias + mask # (batch_size, n_heads, query_length, key_length)
404
+
405
+ scores += position_bias
406
+ weights = stable_softmax(scores, axis=-1) # (batch_size, n_heads, query_length, key_length)
407
+ weights = self.dropout(weights, training=training) # (batch_size, n_heads, query_length, key_length)
408
+
409
+ # Mask heads if we want to
410
+ if layer_head_mask is not None:
411
+ tf.debugging.assert_equal(
412
+ shape_list(layer_head_mask),
413
+ [self.n_heads],
414
+ message=(
415
+ f"Head mask for a single layer should be of size {(self.n_heads)}, but is"
416
+ f" {shape_list(layer_head_mask)}"
417
+ ),
418
+ )
419
+ weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * weights
420
+
421
+ attn_output = tf.matmul(weights, value_states) # (batch_size, n_heads, query_length, dim_per_head)
422
+
423
+ attn_output = self.o(unshape(attn_output))
424
+
425
+ outputs = (attn_output,) + (present_key_value_state,) + (position_bias,)
426
+
427
+ if output_attentions:
428
+ outputs = outputs + (weights,)
429
+
430
+ return outputs
431
+
432
+
433
+ class TFT5LayerSelfAttention(tf.keras.layers.Layer):
434
+ def __init__(self, config, has_relative_attention_bias=False, **kwargs):
435
+ super().__init__(**kwargs)
436
+ self.SelfAttention = TFT5Attention(
437
+ config,
438
+ has_relative_attention_bias=has_relative_attention_bias,
439
+ name="SelfAttention",
440
+ )
441
+ self.layer_norm = TFT5LayerNorm(epsilon=config.layer_norm_epsilon, name="layer_norm")
442
+ self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
443
+
444
+ def call(
445
+ self,
446
+ hidden_states,
447
+ attention_mask=None,
448
+ position_bias=None,
449
+ layer_head_mask=None,
450
+ past_key_value=None,
451
+ use_cache=False,
452
+ output_attentions=False,
453
+ training=False,
454
+ ):
455
+ normed_hidden_states = self.layer_norm(hidden_states)
456
+ attention_output = self.SelfAttention(
457
+ normed_hidden_states,
458
+ mask=attention_mask,
459
+ position_bias=position_bias,
460
+ layer_head_mask=layer_head_mask,
461
+ past_key_value=past_key_value,
462
+ use_cache=use_cache,
463
+ output_attentions=output_attentions,
464
+ training=training,
465
+ )
466
+ hidden_states = hidden_states + self.dropout(attention_output[0], training=training)
467
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
468
+ return outputs
469
+
470
+
471
+ class TFT5LayerCrossAttention(tf.keras.layers.Layer):
472
+ def __init__(self, config, **kwargs):
473
+ super().__init__(**kwargs)
474
+ self.EncDecAttention = TFT5Attention(
475
+ config,
476
+ has_relative_attention_bias=False,
477
+ name="EncDecAttention",
478
+ )
479
+ self.layer_norm = TFT5LayerNorm(epsilon=config.layer_norm_epsilon, name="layer_norm")
480
+ self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
481
+
482
+ def call(
483
+ self,
484
+ hidden_states,
485
+ key_value_states,
486
+ attention_mask=None,
487
+ position_bias=None,
488
+ layer_head_mask=None,
489
+ past_key_value=None,
490
+ query_length=None,
491
+ use_cache=False,
492
+ output_attentions=False,
493
+ training=False,
494
+ ):
495
+ normed_hidden_states = self.layer_norm(hidden_states)
496
+ attention_output = self.EncDecAttention(
497
+ normed_hidden_states,
498
+ mask=attention_mask,
499
+ key_value_states=key_value_states,
500
+ position_bias=position_bias,
501
+ layer_head_mask=layer_head_mask,
502
+ past_key_value=past_key_value,
503
+ query_length=query_length,
504
+ use_cache=use_cache,
505
+ output_attentions=output_attentions,
506
+ training=training,
507
+ )
508
+ hidden_states = hidden_states + self.dropout(attention_output[0], training=training)
509
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
510
+ return outputs
511
+
512
+
513
+ class TFT5Block(tf.keras.layers.Layer):
514
+ def __init__(self, config, has_relative_attention_bias=False, **kwargs):
515
+ super().__init__(**kwargs)
516
+ self.is_decoder = config.is_decoder
517
+ self.layer = []
518
+ self.layer.append(
519
+ TFT5LayerSelfAttention(
520
+ config,
521
+ has_relative_attention_bias=has_relative_attention_bias,
522
+ name="layer_._0",
523
+ )
524
+ )
525
+ if self.is_decoder:
526
+ self.layer.append(
527
+ TFT5LayerCrossAttention(
528
+ config,
529
+ name="layer_._1",
530
+ )
531
+ )
532
+
533
+ self.layer.append(TFT5LayerFF(config, name=f"layer_._{len(self.layer)}"))
534
+
535
+ def call(
536
+ self,
537
+ hidden_states,
538
+ attention_mask=None,
539
+ position_bias=None,
540
+ encoder_hidden_states=None,
541
+ encoder_attention_mask=None,
542
+ encoder_decoder_position_bias=None,
543
+ layer_head_mask=None,
544
+ encoder_layer_head_mask=None,
545
+ past_key_value=None,
546
+ use_cache=False,
547
+ output_attentions=False,
548
+ training=False,
549
+ ):
550
+ if past_key_value is not None:
551
+ assert self.is_decoder, "Only decoder can use `past_key_values`"
552
+ expected_num_past_key_values = 2 if encoder_hidden_states is None else 4
553
+
554
+ if len(past_key_value) != expected_num_past_key_values:
555
+ raise ValueError(
556
+ f"There should be {expected_num_past_key_values} past states. "
557
+ f"{'2 (past / key) for cross attention' if expected_num_past_key_values == 4 else ''}."
558
+ f"Got {len(past_key_value)} past key / value states"
559
+ )
560
+
561
+ self_attn_past_key_value = past_key_value[:2]
562
+ cross_attn_past_key_value = past_key_value[2:]
563
+ else:
564
+ self_attn_past_key_value, cross_attn_past_key_value = None, None
565
+
566
+ self_attention_outputs = self.layer[0](
567
+ hidden_states,
568
+ attention_mask=attention_mask,
569
+ position_bias=position_bias,
570
+ layer_head_mask=layer_head_mask,
571
+ past_key_value=self_attn_past_key_value,
572
+ use_cache=use_cache,
573
+ output_attentions=output_attentions,
574
+ training=training,
575
+ )
576
+ hidden_states, present_key_value_state = self_attention_outputs[:2]
577
+ attention_outputs = self_attention_outputs[2:] # Keep self-attention outputs and relative position weights
578
+
579
+ if self.is_decoder and encoder_hidden_states is not None:
580
+ # the actual query length is unknown for cross attention
581
+ # if using past key value states. Need to inject it here
582
+ if present_key_value_state is not None:
583
+ query_length = shape_list(present_key_value_state[0])[2]
584
+ else:
585
+ query_length = None
586
+
587
+ cross_attention_outputs = self.layer[1](
588
+ hidden_states,
589
+ key_value_states=encoder_hidden_states,
590
+ attention_mask=encoder_attention_mask,
591
+ position_bias=encoder_decoder_position_bias,
592
+ layer_head_mask=encoder_layer_head_mask,
593
+ past_key_value=cross_attn_past_key_value,
594
+ query_length=query_length,
595
+ use_cache=use_cache,
596
+ output_attentions=output_attentions,
597
+ training=training,
598
+ )
599
+ hidden_states = cross_attention_outputs[0]
600
+ # Combine self attn and cross attn key value states
601
+ if present_key_value_state is not None:
602
+ present_key_value_state = present_key_value_state + cross_attention_outputs[1]
603
+
604
+ # Keep cross-attention outputs and relative position weights
605
+ attention_outputs = attention_outputs + cross_attention_outputs[2:]
606
+
607
+ # Apply Feed Forward layer
608
+ hidden_states = self.layer[-1](hidden_states, training=training)
609
+ outputs = (hidden_states,)
610
+
611
+ # Add attentions if we output them
612
+ outputs = outputs + (present_key_value_state,) + attention_outputs
613
+ return outputs # hidden-states, present_key_value_states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
614
+
615
+
616
+ ####################################################
617
+ # The full model without a specific pretrained or finetuning head is
618
+ # provided as a tf.keras.layers.Layer usually called "TFT5MainLayer"
619
+ ####################################################
620
+ @keras_serializable
621
+ class TFT5MainLayer(tf.keras.layers.Layer):
622
+ config_class = T5Config
623
+
624
+ def __init__(self, config, embed_tokens=None, **kwargs):
625
+ super().__init__(**kwargs)
626
+
627
+ self.config = config
628
+ self.output_hidden_states = config.output_hidden_states
629
+ self.output_attentions = config.output_attentions
630
+ self.use_cache = config.use_cache
631
+
632
+ self.embed_tokens = embed_tokens
633
+ self.is_decoder = config.is_decoder
634
+
635
+ self.config = config
636
+ self.num_hidden_layers = config.num_layers
637
+
638
+ self.block = [
639
+ TFT5Block(config, has_relative_attention_bias=bool(i == 0), name=f"block_._{i}")
640
+ for i in range(config.num_layers)
641
+ ]
642
+ self.final_layer_norm = TFT5LayerNorm(epsilon=config.layer_norm_epsilon, name="final_layer_norm")
643
+ self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
644
+
645
+ def _prune_heads(self, heads_to_prune):
646
+ raise NotImplementedError # Not implemented yet in the library fr TF 2.0 models
647
+
648
+ @unpack_inputs
649
+ def call(
650
+ self,
651
+ input_ids=None,
652
+ attention_mask=None,
653
+ encoder_hidden_states=None,
654
+ encoder_attention_mask=None,
655
+ inputs_embeds=None,
656
+ head_mask=None,
657
+ encoder_head_mask=None,
658
+ past_key_values=None,
659
+ use_cache=None,
660
+ output_attentions=None,
661
+ output_hidden_states=None,
662
+ return_dict=None,
663
+ training=False,
664
+ ) -> Tuple:
665
+ if input_ids is not None and inputs_embeds is not None:
666
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
667
+ raise ValueError(
668
+ f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
669
+ )
670
+ elif input_ids is not None:
671
+ input_shape = shape_list(input_ids)
672
+ input_ids = tf.reshape(input_ids, (-1, input_shape[-1]))
673
+ elif inputs_embeds is not None:
674
+ input_shape = shape_list(inputs_embeds)[:-1]
675
+ else:
676
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
677
+ raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
678
+
679
+ if inputs_embeds is None:
680
+ assert self.embed_tokens is not None, "You have to initialize the model with valid token embeddings"
681
+ # if `self.embed_tokens.load_weight_prefix` is set, runs the embedding operation with the correct name
682
+ # scope, so that its weights are registered with the desired name for loading/storing. When `tf.name_scope`
683
+ # is used with a name ending in `/`, that name replaces the current name scope.
684
+ # (embeddings with tf.name_scope: self.embed_tokens.load_weight_prefix/self.embed_tokens.name/embeddings:0)
685
+ context = []
686
+ if hasattr(self.embed_tokens, "load_weight_prefix"):
687
+ context.append(tf.name_scope(self.embed_tokens.load_weight_prefix + "/"))
688
+ with ContextManagers(context):
689
+ # Note: tf.gather, on which the embedding layer is based, won't check positive out of bound
690
+ # indices on GPU, returning zeros instead. This is a dangerous silent behavior.
691
+ tf.debugging.assert_less(
692
+ input_ids,
693
+ tf.cast(self.embed_tokens.input_dim, dtype=input_ids.dtype),
694
+ message=(
695
+ "input_ids must be smaller than the embedding layer's input dimension (got"
696
+ f" {tf.math.reduce_max(input_ids)} >= {self.embed_tokens.input_dim})"
697
+ ),
698
+ )
699
+ inputs_embeds = self.embed_tokens(input_ids)
700
+
701
+ batch_size, seq_length = input_shape
702
+
703
+ # required mask seq length can be calculated via length of past
704
+ mask_seq_length = (
705
+ shape_list(past_key_values[0][0])[2] + seq_length if past_key_values is not None else seq_length
706
+ )
707
+
708
+ if attention_mask is None:
709
+ attention_mask = tf.fill((batch_size, mask_seq_length), 1)
710
+ if self.is_decoder and encoder_attention_mask is None and encoder_hidden_states is not None:
711
+ encoder_seq_length = shape_list(encoder_hidden_states)[1]
712
+ encoder_attention_mask = tf.fill((batch_size, encoder_seq_length), 1)
713
+
714
+ # initialize past_key_values with `None` if past does not exist
715
+ if past_key_values is None:
716
+ past_key_values = [None] * len(self.block)
717
+
718
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
719
+ # ourselves in which case we just need to make it broadcastable to all heads.
720
+ attention_mask = tf.cast(attention_mask, dtype=inputs_embeds.dtype)
721
+ num_dims_attention_mask = len(shape_list(attention_mask))
722
+ if num_dims_attention_mask == 3:
723
+ extended_attention_mask = attention_mask[:, None, :, :]
724
+ elif num_dims_attention_mask == 2:
725
+ # Provided a padding mask of dimensions [batch_size, mask_seq_length]
726
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
727
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
728
+ if self.is_decoder:
729
+ seq_ids = tf.range(mask_seq_length)
730
+ causal_mask = tf.less_equal(
731
+ tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
732
+ seq_ids[None, :, None],
733
+ )
734
+ causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
735
+ extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
736
+ if past_key_values[0] is not None:
737
+ extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
738
+ else:
739
+ extended_attention_mask = attention_mask[:, None, None, :]
740
+
741
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
742
+ # masked positions, this operation will create a tensor which is 0.0 for
743
+ # positions we want to attend and -1e9 for masked positions.
744
+ # Since we are adding it to the raw scores before the softmax, this is
745
+ # effectively the same as removing these entirely.
746
+
747
+ # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
748
+ # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
749
+ # extended_attention_mask = tf.math.equal(extended_attention_mask,
750
+ # tf.transpose(extended_attention_mask, perm=(-1, -2)))
751
+
752
+ extended_attention_mask = (1.0 - extended_attention_mask) * -1e9
753
+
754
+ if self.is_decoder and encoder_attention_mask is not None:
755
+ # If a 2D ou 3D attention mask is provided for the cross-attention
756
+ # we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
757
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
758
+ encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
759
+ num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
760
+ if num_dims_encoder_attention_mask == 3:
761
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
762
+ if num_dims_encoder_attention_mask == 2:
763
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
764
+
765
+ # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
766
+ # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
767
+ # encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
768
+ # tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
769
+
770
+ encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -1e9
771
+ else:
772
+ encoder_extended_attention_mask = None
773
+
774
+ present_key_value_states = () if use_cache and self.is_decoder else None
775
+ all_hidden_states = () if output_hidden_states else None
776
+ all_attentions = () if output_attentions else None
777
+ all_cross_attentions = () if (output_attentions and self.is_decoder) else None
778
+ position_bias = None
779
+ encoder_decoder_position_bias = None
780
+
781
+ hidden_states = self.dropout(inputs_embeds, training=training)
782
+
783
+ for idx, (layer_module, past_key_value) in enumerate(zip(self.block, past_key_values)):
784
+ if output_hidden_states:
785
+ all_hidden_states = all_hidden_states + (hidden_states,)
786
+ layer_outputs = layer_module(
787
+ hidden_states,
788
+ attention_mask=extended_attention_mask,
789
+ position_bias=position_bias,
790
+ encoder_hidden_states=encoder_hidden_states,
791
+ encoder_attention_mask=encoder_extended_attention_mask,
792
+ encoder_decoder_position_bias=encoder_decoder_position_bias,
793
+ layer_head_mask=head_mask[idx] if head_mask is not None else None,
794
+ encoder_layer_head_mask=encoder_head_mask[idx] if encoder_head_mask is not None else None,
795
+ past_key_value=past_key_value,
796
+ use_cache=use_cache,
797
+ output_attentions=output_attentions,
798
+ training=training,
799
+ )
800
+
801
+ # layer_outputs is a tuple with:
802
+ # hidden-states, key-value-states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
803
+ hidden_states, present_key_value_state = layer_outputs[:2]
804
+
805
+ # We share the position biases between the layers - the first layer store them
806
+ # layer_outputs = hidden-states, past_key_values, (self-attention weights),
807
+ # (self-attention position bias), (cross-attention position bias), (cross-attention weights),
808
+ position_bias = layer_outputs[2]
809
+
810
+ if self.is_decoder and encoder_hidden_states is not None:
811
+ encoder_decoder_position_bias = layer_outputs[4 if output_attentions else 3]
812
+
813
+ # append next layer key value states
814
+ if present_key_value_state is not None and use_cache and self.is_decoder:
815
+ present_key_value_states = present_key_value_states + (present_key_value_state,)
816
+
817
+ if output_attentions:
818
+ all_attentions = all_attentions + (layer_outputs[3],)
819
+ if self.is_decoder:
820
+ all_cross_attentions = all_cross_attentions + (layer_outputs[5],)
821
+
822
+ hidden_states = self.final_layer_norm(hidden_states)
823
+ hidden_states = self.dropout(hidden_states, training=training)
824
+
825
+ # Add last layer
826
+ if output_hidden_states:
827
+ all_hidden_states = all_hidden_states + (hidden_states,)
828
+
829
+ if not return_dict:
830
+ outputs = (hidden_states,)
831
+ # need to check if is decoder here as well for special cases when using keras compile
832
+ if use_cache and self.is_decoder:
833
+ outputs = outputs + (present_key_value_states,)
834
+ if output_hidden_states:
835
+ outputs = outputs + (all_hidden_states,)
836
+ if output_attentions:
837
+ outputs = outputs + (all_attentions,)
838
+ if self.is_decoder:
839
+ outputs + (all_cross_attentions,)
840
+ return outputs # last-layer hidden state, (past_key_values), (all hidden states), (all attentions), (all_cross_attentions)
841
+
842
+ if self.is_decoder:
843
+ return TFBaseModelOutputWithPastAndCrossAttentions(
844
+ last_hidden_state=hidden_states,
845
+ past_key_values=present_key_value_states,
846
+ hidden_states=all_hidden_states,
847
+ attentions=all_attentions,
848
+ cross_attentions=all_cross_attentions,
849
+ )
850
+ else:
851
+ return TFBaseModelOutput(
852
+ last_hidden_state=hidden_states,
853
+ hidden_states=all_hidden_states,
854
+ attentions=all_attentions,
855
+ )
856
+
857
+
858
+ ####################################################
859
+ # TFT5PreTrainedModel is a sub-class of tf.keras.Model
860
+ # which take care of loading and saving pretrained weights
861
+ # and various common utilities.
862
+ # Here you just need to specify a few (self-explanatory)
863
+ # pointers for your model.
864
+ ####################################################
865
+ class TFT5PreTrainedModel(TFPreTrainedModel):
866
+ """
867
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
868
+ models.
869
+ """
870
+
871
+ config_class = T5Config
872
+ base_model_prefix = "transformer"
873
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
874
+ _keys_to_ignore_on_load_unexpected = [r"decoder\Wblock[\W_0]+layer[\W_1]+EncDecAttention\Wrelative_attention_bias"]
875
+
876
+ @property
877
+ def dummy_inputs(self):
878
+ inputs = tf.constant(DUMMY_INPUTS, dtype=tf.int32)
879
+ input_mask = tf.constant(DUMMY_MASK, dtype=tf.int32)
880
+ dummy_inputs = {
881
+ "input_ids": inputs,
882
+ "decoder_input_ids": inputs,
883
+ "decoder_attention_mask": input_mask,
884
+ }
885
+ return dummy_inputs
886
+
887
+ @tf.function(
888
+ input_signature=[
889
+ {
890
+ "input_ids": tf.TensorSpec((None, None), tf.int32, name="input_ids"),
891
+ "attention_mask": tf.TensorSpec((None, None), tf.int32, name="attention_mask"),
892
+ "decoder_input_ids": tf.TensorSpec((None, None), tf.int32, name="decoder_input_ids"),
893
+ "decoder_attention_mask": tf.TensorSpec((None, None), tf.int32, name="decoder_attention_mask"),
894
+ }
895
+ ]
896
+ )
897
+ def serving(self, inputs):
898
+ output = self.call(inputs)
899
+
900
+ return self.serving_output(output)
901
+
902
+ def get_input_embeddings(self):
903
+ return self.shared
904
+
905
+ def set_input_embeddings(self, value):
906
+ self.shared = value
907
+ self.encoder.embed_tokens = self.shared
908
+ if hasattr(self, "decoder"):
909
+ self.decoder.embed_tokens = self.shared
910
+
911
+ def _shift_right(self, input_ids):
912
+ decoder_start_token_id = self.config.decoder_start_token_id
913
+ pad_token_id = self.config.pad_token_id
914
+
915
+ assert decoder_start_token_id is not None, (
916
+ "self.model.config.decoder_start_token_id has to be defined. In TF T5 it is usually set to the"
917
+ " pad_token_id. See T5 docs for more information"
918
+ )
919
+
920
+ start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id)
921
+ start_tokens = tf.cast(start_tokens, input_ids.dtype) # Ensure compatible dtypes for concatenation
922
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
923
+
924
+ assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined."
925
+ # replace possible -100 values in labels by `pad_token_id`
926
+ shifted_input_ids = tf.where(
927
+ shifted_input_ids == -100,
928
+ tf.cast(tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids.dtype),
929
+ shifted_input_ids,
930
+ )
931
+
932
+ # "Verify that `labels` has only positive values and -100"
933
+ assert_gte0 = tf.debugging.assert_greater_equal(
934
+ shifted_input_ids, tf.constant(0, dtype=shifted_input_ids.dtype)
935
+ )
936
+
937
+ # Make sure the assertion op is called by wrapping the result in an identity no-op
938
+ with tf.control_dependencies([assert_gte0]):
939
+ shifted_input_ids = tf.identity(shifted_input_ids)
940
+
941
+ return shifted_input_ids
942
+
943
+
944
+ T5_START_DOCSTRING = r"""
945
+
946
+ The T5 model was proposed in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text
947
+ Transformer](https://arxiv.org/abs/1910.10683) by Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan
948
+ Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu. It's an encoder decoder transformer pre-trained in a
949
+ text-to-text denoising generative setting.
950
+
951
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
952
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
953
+ etc.)
954
+
955
+ This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
956
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
957
+ behavior.
958
+
959
+ <Tip>
960
+
961
+ TensorFlow models and layers in `transformers` accept two formats as input:
962
+
963
+ - having all inputs as keyword arguments (like PyTorch models), or
964
+ - having all inputs as a list, tuple or dict in the first positional argument.
965
+
966
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
967
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
968
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
969
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
970
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
971
+ positional argument:
972
+
973
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
974
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
975
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
976
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
977
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
978
+
979
+ Note that when creating models and layers with
980
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
981
+ about any of this, as you can just pass inputs like you would to any other Python function!
982
+
983
+ </Tip>
984
+
985
+ Parameters:
986
+ config ([`T5Config`]): Model configuration class with all the parameters of the model.
987
+ Initializing with a config file does not load the weights associated with the model, only the
988
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
989
+ """
990
+
991
+ T5_INPUTS_DOCSTRING = r"""
992
+ Args:
993
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
994
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
995
+ should be able to pad the inputs on the right or the left.
996
+
997
+ Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
998
+ [`PreTrainedTokenizer.encode`] for details.
999
+
1000
+ [What are input IDs?](../glossary#input-ids)
1001
+
1002
+ To know more on how to prepare `inputs` for pretraining take a look at [T5 Training](./t5#training).
1003
+ decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1004
+ Provide for sequence to sequence training. T5 uses the `pad_token_id` as the starting token for
1005
+ `decoder_input_ids` generation. If `past_key_values` is used, optionally only the last `decoder_input_ids`
1006
+ have to be input (see `past_key_values`).
1007
+
1008
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [T5
1009
+ Training](./t5#training).
1010
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1011
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1012
+
1013
+ - 1 for tokens that are **not masked**,
1014
+ - 0 for tokens that are **masked**.
1015
+
1016
+ [What are attention masks?](../glossary#attention-mask)
1017
+ decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1018
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1019
+ be used by default.
1020
+ head_mask (`tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1021
+ Mask to nullify selected heads of the self-attention modules in the encoder. Mask values selected in `[0,
1022
+ 1]`:
1023
+
1024
+ - 1 indicates the head is **not masked**,
1025
+ - 0 indicates the head is **masked**.
1026
+
1027
+ decoder_head_mask (`tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1028
+ Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
1029
+ 1]`:
1030
+
1031
+ - 1 indicates the head is **not masked**,
1032
+ - 0 indicates the head is **masked**.
1033
+
1034
+ encoder_outputs (`tuple(tuple(tf.FloatTensor)`, *optional*):
1035
+ Tuple consists of (`last_hidden_state`, `optional`: *hidden_states*, `optional`: *attentions*)
1036
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at
1037
+ the output of the last layer of the encoder. Used in the cross-attention of the decoder.
1038
+ past_key_values (`tuple(tuple(tf.Tensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1039
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1040
+
1041
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1042
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1043
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1044
+ inputs_embeds (`tf.Tensor` 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. This
1046
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1047
+ model's internal embedding lookup matrix.
1048
+ decoder_inputs_embeds (`tf.Tensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
1049
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
1050
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
1051
+ input (see `past_key_values`). This is useful if you want more control over how to convert
1052
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
1053
+
1054
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
1055
+ of `inputs_embeds`.
1056
+ use_cache (`bool`, *optional*, defaults to `True`):
1057
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1058
+ `past_key_values`).
1059
+ output_attentions (`bool`, *optional*):
1060
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1061
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1062
+ config will be used instead.
1063
+ output_hidden_states (`bool`, *optional*):
1064
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1065
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1066
+ used instead.
1067
+ return_dict (`bool`, *optional*):
1068
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1069
+ eager mode, in graph mode the value will always be set to True.
1070
+ training (`bool`, *optional*, defaults to `False`):
1071
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1072
+ behaviors between training and evaluation).
1073
+ """
1074
+
1075
+ T5_ENCODER_INPUTS_DOCSTRING = r"""
1076
+ Args:
1077
+ inputs (`tf.Tensor` of shape `(batch_size, sequence_length)`):
1078
+ Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you
1079
+ should be able to pad the inputs on the right or the left.
1080
+
1081
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
1082
+ [`PreTrainedTokenizer.encode`] for details.
1083
+
1084
+ To know more on how to prepare `inputs` for pre-training take a look at [T5 Training](./t5#training).
1085
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1086
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1087
+
1088
+ - 1 for tokens that are **not masked**,
1089
+ - 0 for tokens that are **masked**.
1090
+
1091
+ [What are attention masks?](../glossary#attention-mask)
1092
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1093
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1094
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1095
+ model's internal embedding lookup matrix.
1096
+ head_mask (`tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1097
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
1098
+
1099
+ - 1 indicates the head is **not masked**,
1100
+ - 0 indicates the head is **masked**.
1101
+
1102
+ output_attentions (`bool`, *optional*):
1103
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1104
+ tensors for more detail.
1105
+ output_hidden_states (`bool`, *optional*):
1106
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1107
+ more detail.
1108
+ return_dict (`bool`, *optional*):
1109
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1110
+ training (`bool`, *optional*, defaults to `False`):
1111
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1112
+ behaviors between training and evaluation).
1113
+ """
1114
+
1115
+ _HEAD_MASK_WARNING_MSG = """
1116
+ The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
1117
+ `decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
1118
+ If you do not want to use any `decoder_head_mask` now, please set `decoder_head_mask = tf.ones((num_layers,
1119
+ num_heads))`.
1120
+ """
1121
+
1122
+
1123
+ @add_start_docstrings(
1124
+ "The bare T5 Model transformer outputting raw hidden-stateswithout any specific head on top.",
1125
+ T5_START_DOCSTRING,
1126
+ )
1127
+ class TFT5Model(TFT5PreTrainedModel):
1128
+ def __init__(self, config, *inputs, **kwargs):
1129
+ super().__init__(config, *inputs, **kwargs)
1130
+
1131
+ self.shared = tf.keras.layers.Embedding(
1132
+ input_dim=config.vocab_size,
1133
+ output_dim=config.d_model,
1134
+ embeddings_initializer=tf.keras.initializers.TruncatedNormal(self.config.initializer_factor),
1135
+ name="shared",
1136
+ )
1137
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1138
+ self.shared.load_weight_prefix = "shared"
1139
+
1140
+ encoder_config = copy.deepcopy(config)
1141
+ encoder_config.use_cache = False
1142
+ self.encoder = TFT5MainLayer(encoder_config, self.shared, name="encoder")
1143
+
1144
+ decoder_config = copy.deepcopy(config)
1145
+ decoder_config.is_decoder = True
1146
+ decoder_config.num_layers = config.num_decoder_layers
1147
+ self.decoder = TFT5MainLayer(decoder_config, self.shared, name="decoder")
1148
+
1149
+ def get_encoder(self):
1150
+ return self.encoder
1151
+
1152
+ def get_decoder(self):
1153
+ return self.decoder
1154
+
1155
+ @unpack_inputs
1156
+ @add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)
1157
+ @replace_return_docstrings(output_type=TFSeq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
1158
+ def call(
1159
+ self,
1160
+ input_ids: Optional[TFModelInputType] = None,
1161
+ attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1162
+ decoder_input_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
1163
+ decoder_attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1164
+ head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1165
+ decoder_head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1166
+ encoder_outputs: Optional[Union[np.ndarray, tf.Tensor]] = None,
1167
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1168
+ inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
1169
+ decoder_inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
1170
+ use_cache: Optional[bool] = None,
1171
+ output_attentions: Optional[bool] = None,
1172
+ output_hidden_states: Optional[bool] = None,
1173
+ return_dict: Optional[bool] = None,
1174
+ training: Optional[bool] = False,
1175
+ ) -> Union[Tuple, TFSeq2SeqModelOutput]:
1176
+ r"""
1177
+ Returns:
1178
+
1179
+ Examples:
1180
+
1181
+ ```python
1182
+ >>> from transformers import AutoTokenizer, TFT5Model
1183
+
1184
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1185
+ >>> model = TFT5Model.from_pretrained("t5-small")
1186
+
1187
+ >>> input_ids = tokenizer(
1188
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="tf"
1189
+ ... ).input_ids # Batch size 1
1190
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="tf").input_ids # Batch size 1
1191
+
1192
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.
1193
+ >>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.
1194
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
1195
+
1196
+ >>> # forward pass
1197
+ >>> outputs = model(input_ids, decoder_input_ids=decoder_input_ids)
1198
+ >>> last_hidden_states = outputs.last_hidden_state
1199
+ ```"""
1200
+ # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
1201
+ if head_mask is not None and decoder_head_mask is None:
1202
+ warnings.warn(_HEAD_MASK_WARNING_MSG, FutureWarning)
1203
+ decoder_head_mask = head_mask
1204
+
1205
+ # Encode if needed (training, first prediction pass)
1206
+ if encoder_outputs is None:
1207
+ encoder_outputs = self.encoder(
1208
+ input_ids,
1209
+ attention_mask=attention_mask,
1210
+ encoder_hidden_states=None,
1211
+ encoder_attention_mask=None,
1212
+ inputs_embeds=inputs_embeds,
1213
+ head_mask=head_mask,
1214
+ past_key_values=None,
1215
+ use_cache=False,
1216
+ output_attentions=output_attentions,
1217
+ output_hidden_states=output_hidden_states,
1218
+ return_dict=return_dict,
1219
+ training=training,
1220
+ )
1221
+
1222
+ hidden_states = encoder_outputs[0]
1223
+
1224
+ # Decode
1225
+ decoder_outputs = self.decoder(
1226
+ decoder_input_ids,
1227
+ attention_mask=decoder_attention_mask,
1228
+ encoder_hidden_states=hidden_states,
1229
+ encoder_attention_mask=attention_mask,
1230
+ inputs_embeds=decoder_inputs_embeds,
1231
+ head_mask=decoder_head_mask,
1232
+ encoder_head_mask=head_mask,
1233
+ past_key_values=past_key_values,
1234
+ use_cache=use_cache,
1235
+ output_attentions=output_attentions,
1236
+ output_hidden_states=output_hidden_states,
1237
+ return_dict=return_dict,
1238
+ training=training,
1239
+ )
1240
+ past = decoder_outputs[1] if use_cache else None
1241
+
1242
+ if not return_dict:
1243
+ if past_key_values is not None:
1244
+ decoder_outputs = decoder_outputs[:1] + (past,) + decoder_outputs[2:]
1245
+ return decoder_outputs + encoder_outputs
1246
+
1247
+ return TFSeq2SeqModelOutput(
1248
+ last_hidden_state=decoder_outputs.last_hidden_state,
1249
+ past_key_values=past,
1250
+ decoder_hidden_states=decoder_outputs.hidden_states,
1251
+ decoder_attentions=decoder_outputs.attentions,
1252
+ cross_attentions=decoder_outputs.cross_attentions,
1253
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1254
+ encoder_hidden_states=encoder_outputs.hidden_states,
1255
+ encoder_attentions=encoder_outputs.attentions,
1256
+ )
1257
+
1258
+ def serving_output(self, output):
1259
+ pkv = tf.convert_to_tensor(output.past_key_values[1:]) if self.config.use_cache else None
1260
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1261
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1262
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1263
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1264
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1265
+
1266
+ return TFSeq2SeqModelOutput(
1267
+ last_hidden_state=output.last_hidden_state,
1268
+ past_key_values=pkv,
1269
+ decoder_hidden_states=dec_hs,
1270
+ decoder_attentions=dec_attns,
1271
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1272
+ cross_attentions=cross_attns,
1273
+ encoder_hidden_states=enc_hs,
1274
+ encoder_attentions=enc_attns,
1275
+ )
1276
+
1277
+
1278
+ @add_start_docstrings("""T5 Model with a `language modeling` head on top.""", T5_START_DOCSTRING)
1279
+ class TFT5ForConditionalGeneration(TFT5PreTrainedModel, TFCausalLanguageModelingLoss):
1280
+ def __init__(self, config, *inputs, **kwargs):
1281
+ super().__init__(config, *inputs, **kwargs)
1282
+ self.model_dim = config.d_model
1283
+ self.shared = tf.keras.layers.Embedding(
1284
+ config.vocab_size,
1285
+ config.d_model,
1286
+ name="shared",
1287
+ embeddings_initializer=get_initializer(self.config.initializer_factor),
1288
+ )
1289
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1290
+ self.shared.load_weight_prefix = "shared"
1291
+
1292
+ encoder_config = copy.deepcopy(config)
1293
+ encoder_config.use_cache = False
1294
+ self.encoder = TFT5MainLayer(encoder_config, self.shared, name="encoder")
1295
+
1296
+ decoder_config = copy.deepcopy(config)
1297
+ decoder_config.is_decoder = True
1298
+ decoder_config.num_layers = config.num_decoder_layers
1299
+ self.decoder = TFT5MainLayer(decoder_config, self.shared, name="decoder")
1300
+
1301
+ if not config.tie_word_embeddings:
1302
+ lm_head_initializer = tf.keras.initializers.RandomNormal(mean=0, stddev=config.initializer_factor)
1303
+ self.lm_head = tf.keras.layers.Dense(
1304
+ config.vocab_size, use_bias=False, name="lm_head", kernel_initializer=lm_head_initializer
1305
+ ) # Update init weights as in flax
1306
+
1307
+ def get_output_embeddings(self):
1308
+ if self.config.tie_word_embeddings:
1309
+ return self.get_input_embeddings()
1310
+ else:
1311
+ # in a dense layer the kernel has a shape (last_dim, units), for us (dim, num_tokens)
1312
+ # value has a shape (num_tokens, dim) then needs to be transposed
1313
+ return tf.transpose(self.lm_head.kernel)
1314
+
1315
+ def set_output_embeddings(self, value):
1316
+ if self.config.tie_word_embeddings:
1317
+ self.set_input_embeddings(value)
1318
+ else:
1319
+ lm_head_initializer = tf.keras.initializers.RandomNormal(mean=0, stddev=self.config.initializer_factor)
1320
+ self.lm_head = tf.keras.layers.Dense(
1321
+ shape_list(value)[0], use_bias=False, name="lm_head", kernel_initializer=lm_head_initializer
1322
+ ) # Update init weights as in flax
1323
+ # in a dense layer the kernel has a shape (last_dim, units), for us (dim, num_tokens)
1324
+ # value has a shape (num_tokens, dim) then needs to be transposed
1325
+ transposed_value = tf.transpose(value)
1326
+ self.lm_head.kernel = transposed_value
1327
+
1328
+ def get_encoder(self):
1329
+ return self.encoder
1330
+
1331
+ def get_decoder(self):
1332
+ return self.decoder
1333
+
1334
+ @unpack_inputs
1335
+ @add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)
1336
+ @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1337
+ def call(
1338
+ self,
1339
+ input_ids: Optional[TFModelInputType] = None,
1340
+ attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1341
+ decoder_input_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
1342
+ decoder_attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1343
+ head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1344
+ decoder_head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1345
+ encoder_outputs: Optional[Union[np.ndarray, tf.Tensor]] = None,
1346
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1347
+ inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
1348
+ decoder_inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
1349
+ labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
1350
+ use_cache: Optional[bool] = None,
1351
+ output_attentions: Optional[bool] = None,
1352
+ output_hidden_states: Optional[bool] = None,
1353
+ return_dict: Optional[bool] = None,
1354
+ training: Optional[bool] = False,
1355
+ ) -> Union[Tuple, TFSeq2SeqLMOutput]:
1356
+ r"""
1357
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1358
+ Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
1359
+ config.vocab_size - 1]`.
1360
+
1361
+ Returns:
1362
+
1363
+ Examples:
1364
+
1365
+ ```python
1366
+ >>> from transformers import AutoTokenizer, TFT5ForConditionalGeneration
1367
+
1368
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1369
+ >>> model = TFT5ForConditionalGeneration.from_pretrained("t5-small")
1370
+
1371
+ >>> # training
1372
+ >>> inputs = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="tf").input_ids
1373
+ >>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="tf").input_ids
1374
+ >>> outputs = model(inputs, labels=labels)
1375
+ >>> loss = outputs.loss
1376
+ >>> logits = outputs.logits
1377
+
1378
+ >>> # inference
1379
+ >>> inputs = tokenizer(
1380
+ ... "summarize: studies have shown that owning a dog is good for you", return_tensors="tf"
1381
+ ... ).input_ids # Batch size 1
1382
+ >>> outputs = model.generate(inputs)
1383
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
1384
+ >>> # studies have shown that owning a dog is good for you
1385
+ ```"""
1386
+ # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
1387
+ if head_mask is not None and decoder_head_mask is None:
1388
+ warnings.warn(_HEAD_MASK_WARNING_MSG, FutureWarning)
1389
+ decoder_head_mask = head_mask
1390
+
1391
+ # Encode if needed (training, first prediction pass)
1392
+ if encoder_outputs is None:
1393
+ encoder_outputs = self.encoder(
1394
+ input_ids,
1395
+ attention_mask=attention_mask,
1396
+ inputs_embeds=inputs_embeds,
1397
+ head_mask=head_mask,
1398
+ output_attentions=output_attentions,
1399
+ output_hidden_states=output_hidden_states,
1400
+ return_dict=return_dict,
1401
+ training=training,
1402
+ )
1403
+
1404
+ hidden_states = encoder_outputs[0]
1405
+
1406
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
1407
+ # get decoder inputs from shifting lm labels to the right
1408
+ decoder_input_ids = self._shift_right(labels)
1409
+
1410
+ # Decode
1411
+ decoder_outputs = self.decoder(
1412
+ decoder_input_ids,
1413
+ attention_mask=decoder_attention_mask,
1414
+ encoder_hidden_states=hidden_states,
1415
+ encoder_attention_mask=attention_mask,
1416
+ inputs_embeds=decoder_inputs_embeds,
1417
+ head_mask=decoder_head_mask,
1418
+ past_key_values=past_key_values,
1419
+ use_cache=use_cache,
1420
+ output_attentions=output_attentions,
1421
+ output_hidden_states=output_hidden_states,
1422
+ return_dict=return_dict,
1423
+ training=training,
1424
+ )
1425
+
1426
+ sequence_output = decoder_outputs[0]
1427
+
1428
+ # T5v1.1 does not tie output word embeddings and thus does not require downscaling
1429
+ if self.config.tie_word_embeddings:
1430
+ sequence_output = sequence_output * (self.model_dim**-0.5)
1431
+ logits = tf.matmul(sequence_output, self.shared.weights, transpose_b=True)
1432
+ else:
1433
+ logits = self.lm_head(sequence_output)
1434
+
1435
+ logits = tf.cast(logits, tf.float32)
1436
+
1437
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1438
+
1439
+ past = decoder_outputs[1] if use_cache else None
1440
+ if not return_dict:
1441
+ if past_key_values is not None:
1442
+ decoder_outputs = decoder_outputs[:1] + (past,) + decoder_outputs[2:]
1443
+ output = (logits,) + decoder_outputs[1:] + encoder_outputs
1444
+ return ((loss,) + output) if loss is not None else output
1445
+
1446
+ # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
1447
+ elif isinstance(encoder_outputs, tuple):
1448
+ last_hidden_state = encoder_outputs[0]
1449
+ hidden_states = None
1450
+ attentions = None
1451
+ idx = 0
1452
+ if output_hidden_states:
1453
+ idx += 1
1454
+ hidden_states = encoder_outputs[idx]
1455
+ if output_attentions:
1456
+ idx += 1
1457
+ attentions = encoder_outputs[idx]
1458
+
1459
+ encoder_outputs = TFBaseModelOutput(
1460
+ last_hidden_state=last_hidden_state,
1461
+ hidden_states=hidden_states,
1462
+ attentions=attentions,
1463
+ )
1464
+
1465
+ return TFSeq2SeqLMOutput(
1466
+ loss=loss,
1467
+ logits=logits,
1468
+ past_key_values=past,
1469
+ decoder_hidden_states=decoder_outputs.hidden_states,
1470
+ decoder_attentions=decoder_outputs.attentions,
1471
+ cross_attentions=decoder_outputs.cross_attentions,
1472
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1473
+ encoder_hidden_states=encoder_outputs.hidden_states,
1474
+ encoder_attentions=encoder_outputs.attentions,
1475
+ )
1476
+
1477
+ def serving_output(self, output):
1478
+ pkv = tf.convert_to_tensor(output.past_key_values[1:]) if self.config.use_cache else None
1479
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1480
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1481
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1482
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1483
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1484
+
1485
+ return TFSeq2SeqLMOutput(
1486
+ logits=output.logits,
1487
+ past_key_values=pkv,
1488
+ decoder_hidden_states=dec_hs,
1489
+ decoder_attentions=dec_attns,
1490
+ cross_attentions=cross_attns,
1491
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1492
+ encoder_hidden_states=enc_hs,
1493
+ encoder_attentions=enc_attns,
1494
+ )
1495
+
1496
+ def prepare_inputs_for_generation(
1497
+ self,
1498
+ input_ids,
1499
+ past_key_values=None,
1500
+ attention_mask=None,
1501
+ decoder_attention_mask=None,
1502
+ head_mask=None,
1503
+ decoder_head_mask=None,
1504
+ use_cache=None,
1505
+ encoder_outputs=None,
1506
+ **kwargs,
1507
+ ):
1508
+ # cut decoder_input_ids if past is used
1509
+ if past_key_values is not None:
1510
+ input_ids = input_ids[:, -1:]
1511
+
1512
+ return {
1513
+ "input_ids": None, # needs to be passed to make Keras.layer.__call__ happy
1514
+ "decoder_input_ids": input_ids,
1515
+ "past_key_values": past_key_values,
1516
+ "encoder_outputs": encoder_outputs,
1517
+ "attention_mask": attention_mask,
1518
+ "decoder_attention_mask": decoder_attention_mask,
1519
+ "head_mask": head_mask,
1520
+ "decoder_head_mask": decoder_head_mask,
1521
+ "use_cache": use_cache,
1522
+ }
1523
+
1524
+ def prepare_decoder_input_ids_from_labels(self, labels: tf.Tensor):
1525
+ return self._shift_right(labels)
1526
+
1527
+
1528
+ @add_start_docstrings(
1529
+ "The bare T5 Model transformer outputting encoder's raw hidden-stateswithout any specific head on top.",
1530
+ T5_START_DOCSTRING,
1531
+ )
1532
+ class TFT5EncoderModel(TFT5PreTrainedModel):
1533
+ def __init__(self, config, *inputs, **kwargs):
1534
+ super().__init__(config, *inputs, **kwargs)
1535
+ self.shared = tf.keras.layers.Embedding(
1536
+ config.vocab_size,
1537
+ config.d_model,
1538
+ name="shared",
1539
+ embeddings_initializer=get_initializer(self.config.initializer_factor),
1540
+ )
1541
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1542
+ self.shared.load_weight_prefix = "shared"
1543
+
1544
+ encoder_config = copy.deepcopy(config)
1545
+ encoder_config.use_cache = False
1546
+ self.encoder = TFT5MainLayer(encoder_config, self.shared, name="encoder")
1547
+
1548
+ @property
1549
+ def dummy_inputs(self):
1550
+ return {"input_ids": tf.constant(DUMMY_INPUTS, dtype=tf.int32)}
1551
+
1552
+ def get_encoder(self):
1553
+ return self.encoder
1554
+
1555
+ @unpack_inputs
1556
+ @add_start_docstrings_to_model_forward(T5_ENCODER_INPUTS_DOCSTRING)
1557
+ @replace_return_docstrings(output_type=TFBaseModelOutput, config_class=_CONFIG_FOR_DOC)
1558
+ def call(
1559
+ self,
1560
+ input_ids: Optional[TFModelInputType] = None,
1561
+ attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1562
+ head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1563
+ inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
1564
+ output_attentions: Optional[bool] = None,
1565
+ output_hidden_states: Optional[bool] = None,
1566
+ return_dict: Optional[bool] = None,
1567
+ training: Optional[bool] = False,
1568
+ ) -> Union[Tuple, TFBaseModelOutput]:
1569
+ r"""
1570
+ Returns:
1571
+
1572
+ Examples:
1573
+
1574
+ ```python
1575
+ >>> from transformers import AutoTokenizer, TFT5EncoderModel
1576
+
1577
+ >>> tokenizer = AutoTokenizer.from_pretrained("t5-small")
1578
+ >>> model = TFT5EncoderModel.from_pretrained("t5-small")
1579
+
1580
+ >>> input_ids = tokenizer(
1581
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="tf"
1582
+ ... ).input_ids # Batch size 1
1583
+ >>> outputs = model(input_ids)
1584
+ ```"""
1585
+
1586
+ encoder_outputs = self.encoder(
1587
+ input_ids,
1588
+ attention_mask=attention_mask,
1589
+ encoder_hidden_states=None,
1590
+ encoder_attention_mask=None,
1591
+ inputs_embeds=inputs_embeds,
1592
+ head_mask=head_mask,
1593
+ past_key_values=None,
1594
+ use_cache=False,
1595
+ output_attentions=output_attentions,
1596
+ output_hidden_states=output_hidden_states,
1597
+ return_dict=return_dict,
1598
+ training=training,
1599
+ )
1600
+
1601
+ if not return_dict:
1602
+ return encoder_outputs
1603
+
1604
+ return TFBaseModelOutput(
1605
+ last_hidden_state=encoder_outputs.last_hidden_state,
1606
+ hidden_states=encoder_outputs.hidden_states,
1607
+ attentions=encoder_outputs.attentions,
1608
+ )
1609
+
1610
+ @tf.function(
1611
+ input_signature=[
1612
+ {
1613
+ "input_ids": tf.TensorSpec((None, None), tf.int32, name="input_ids"),
1614
+ "attention_mask": tf.TensorSpec((None, None), tf.int32, name="attention_mask"),
1615
+ }
1616
+ ]
1617
+ )
1618
+ def serving(self, inputs):
1619
+ output = self.call(inputs)
1620
+
1621
+ return self.serving_output(output)
1622
+
1623
+ # Copied from transformers.models.distilbert.modeling_tf_distilbert.TFDistilBertModel.serving_output
1624
+ def serving_output(self, output):
1625
+ hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
1626
+ attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
1627
+
1628
+ return TFBaseModelOutput(last_hidden_state=output.last_hidden_state, hidden_states=hs, attentions=attns)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/t5/tokenization_t5.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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
+ """ Tokenization class for model T5."""
16
+
17
+
18
+ import os
19
+ import re
20
+ import warnings
21
+ from shutil import copyfile
22
+ from typing import Any, Dict, List, Optional, Tuple
23
+
24
+ import sentencepiece as spm
25
+
26
+ from ...tokenization_utils import PreTrainedTokenizer
27
+ from ...utils import logging
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
33
+
34
+ PRETRAINED_VOCAB_FILES_MAP = {
35
+ "vocab_file": {
36
+ "t5-small": "https://huggingface.co/t5-small/resolve/main/spiece.model",
37
+ "t5-base": "https://huggingface.co/t5-base/resolve/main/spiece.model",
38
+ "t5-large": "https://huggingface.co/t5-large/resolve/main/spiece.model",
39
+ "t5-3b": "https://huggingface.co/t5-3b/resolve/main/spiece.model",
40
+ "t5-11b": "https://huggingface.co/t5-11b/resolve/main/spiece.model",
41
+ }
42
+ }
43
+
44
+
45
+ # TODO(PVP) - this should be removed in Transformers v5
46
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
47
+ "t5-small": 512,
48
+ "t5-base": 512,
49
+ "t5-large": 512,
50
+ "t5-3b": 512,
51
+ "t5-11b": 512,
52
+ }
53
+
54
+
55
+ class T5Tokenizer(PreTrainedTokenizer):
56
+ """
57
+ Construct a T5 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
58
+
59
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
60
+ this superclass for more information regarding those methods.
61
+
62
+ Args:
63
+ vocab_file (`str`):
64
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
65
+ contains the vocabulary necessary to instantiate a tokenizer.
66
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
67
+ The end of sequence token.
68
+
69
+ <Tip>
70
+
71
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
72
+ The token used is the `sep_token`.
73
+
74
+ </Tip>
75
+
76
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
77
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
78
+ token instead.
79
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
80
+ The token used for padding, for example when batching sequences of different lengths.
81
+ extra_ids (`int`, *optional*, defaults to 100):
82
+ Add a number of extra ids added to the vocabulary for use as sentinels. These tokens are
83
+ accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. These tokens can be
84
+ retrieved by calling get_sentinel_tokens method and token ids can be by calling get_sentinel_token_ids
85
+ method
86
+ additional_special_tokens (`List[str]`, *optional*):
87
+ Additional special tokens used by the tokenizer.
88
+ sp_model_kwargs (`dict`, *optional*):
89
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
90
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
91
+ to set:
92
+
93
+ - `enable_sampling`: Enable subword regularization.
94
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
95
+
96
+ - `nbest_size = {0,1}`: No sampling is performed.
97
+ - `nbest_size > 1`: samples from the nbest_size results.
98
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
99
+ using forward-filtering-and-backward-sampling algorithm.
100
+
101
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
102
+ BPE-dropout.
103
+
104
+ Attributes:
105
+ sp_model (`SentencePieceProcessor`):
106
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
107
+ """
108
+
109
+ vocab_files_names = VOCAB_FILES_NAMES
110
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
111
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
112
+ model_input_names = ["input_ids", "attention_mask"]
113
+
114
+ def __init__(
115
+ self,
116
+ vocab_file,
117
+ eos_token="</s>",
118
+ unk_token="<unk>",
119
+ pad_token="<pad>",
120
+ extra_ids=100,
121
+ additional_special_tokens=None,
122
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
123
+ **kwargs,
124
+ ) -> None:
125
+ # Add extra_ids to the special token list
126
+ if extra_ids > 0 and additional_special_tokens is None:
127
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
128
+ elif extra_ids > 0 and additional_special_tokens is not None:
129
+ # Check that we have the right number of extra_id special tokens
130
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
131
+ if extra_tokens != extra_ids:
132
+ raise ValueError(
133
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
134
+ " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
135
+ " tokens"
136
+ )
137
+
138
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
139
+
140
+ super().__init__(
141
+ eos_token=eos_token,
142
+ unk_token=unk_token,
143
+ pad_token=pad_token,
144
+ extra_ids=extra_ids,
145
+ additional_special_tokens=additional_special_tokens,
146
+ sp_model_kwargs=self.sp_model_kwargs,
147
+ **kwargs,
148
+ )
149
+
150
+ self.vocab_file = vocab_file
151
+ self._extra_ids = extra_ids
152
+
153
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
154
+ self.sp_model.Load(vocab_file)
155
+
156
+ @staticmethod
157
+ def _eventually_correct_t5_max_length(pretrained_model_name_or_path, max_model_length, init_max_model_length):
158
+ if pretrained_model_name_or_path in T5Tokenizer.max_model_input_sizes:
159
+ deprecated_max_model_length = T5Tokenizer.max_model_input_sizes[pretrained_model_name_or_path]
160
+ if init_max_model_length is not None and init_max_model_length != max_model_length:
161
+ return init_max_model_length
162
+ elif init_max_model_length is None:
163
+ warnings.warn(
164
+ "This tokenizer was incorrectly instantiated with a model max length of"
165
+ f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"
166
+ " behavior is kept to avoid breaking backwards compatibility when padding/encoding with"
167
+ " `truncation is True`.\n- Be aware that you SHOULD NOT rely on"
168
+ f" {pretrained_model_name_or_path} automatically truncating your input to"
169
+ f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"
170
+ f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"
171
+ " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please"
172
+ " instantiate this tokenizer with `model_max_length` set to your preferred value.",
173
+ FutureWarning,
174
+ )
175
+
176
+ return max_model_length
177
+
178
+ @property
179
+ def vocab_size(self):
180
+ return self.sp_model.get_piece_size() + self._extra_ids
181
+
182
+ def get_vocab(self):
183
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
184
+ vocab.update(self.added_tokens_encoder)
185
+ return vocab
186
+
187
+ def get_special_tokens_mask(
188
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
189
+ ) -> List[int]:
190
+ """
191
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
192
+ special tokens using the tokenizer `prepare_for_model` method.
193
+
194
+ Args:
195
+ token_ids_0 (`List[int]`):
196
+ List of IDs.
197
+ token_ids_1 (`List[int]`, *optional*):
198
+ Optional second list of IDs for sequence pairs.
199
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
200
+ Whether or not the token list is already formatted with special tokens for the model.
201
+
202
+ Returns:
203
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
204
+ """
205
+ if already_has_special_tokens:
206
+ return super().get_special_tokens_mask(
207
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
208
+ )
209
+
210
+ # normal case: some special tokens
211
+ if token_ids_1 is None:
212
+ return ([0] * len(token_ids_0)) + [1]
213
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
214
+
215
+ def get_sentinel_tokens(self):
216
+ return list(
217
+ set(filter(lambda x: bool(re.search(r"<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
218
+ )
219
+
220
+ def get_sentinel_token_ids(self):
221
+ return [self._convert_token_to_id(token) for token in self.get_sentinel_tokens()]
222
+
223
+ def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
224
+ """Do not add eos again if user already added it."""
225
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
226
+ warnings.warn(
227
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
228
+ " eos tokens being added."
229
+ )
230
+ return token_ids
231
+ else:
232
+ return token_ids + [self.eos_token_id]
233
+
234
+ def create_token_type_ids_from_sequences(
235
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
236
+ ) -> List[int]:
237
+ """
238
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
239
+ use of token type ids, therefore a list of zeros is returned.
240
+
241
+ Args:
242
+ token_ids_0 (`List[int]`):
243
+ List of IDs.
244
+ token_ids_1 (`List[int]`, *optional*):
245
+ Optional second list of IDs for sequence pairs.
246
+
247
+ Returns:
248
+ `List[int]`: List of zeros.
249
+ """
250
+ eos = [self.eos_token_id]
251
+
252
+ if token_ids_1 is None:
253
+ return len(token_ids_0 + eos) * [0]
254
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
255
+
256
+ def build_inputs_with_special_tokens(
257
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
258
+ ) -> List[int]:
259
+ """
260
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
261
+ adding special tokens. A sequence has the following format:
262
+
263
+ - single sequence: `X </s>`
264
+ - pair of sequences: `A </s> B </s>`
265
+
266
+ Args:
267
+ token_ids_0 (`List[int]`):
268
+ List of IDs to which the special tokens will be added.
269
+ token_ids_1 (`List[int]`, *optional*):
270
+ Optional second list of IDs for sequence pairs.
271
+
272
+ Returns:
273
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
274
+ """
275
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
276
+ if token_ids_1 is None:
277
+ return token_ids_0
278
+ else:
279
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
280
+ return token_ids_0 + token_ids_1
281
+
282
+ def __getstate__(self):
283
+ state = self.__dict__.copy()
284
+ state["sp_model"] = None
285
+ return state
286
+
287
+ def __setstate__(self, d):
288
+ self.__dict__ = d
289
+
290
+ # for backward compatibility
291
+ if not hasattr(self, "sp_model_kwargs"):
292
+ self.sp_model_kwargs = {}
293
+
294
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
295
+ self.sp_model.Load(self.vocab_file)
296
+
297
+ def _tokenize(self, text: str) -> List[str]:
298
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
299
+ return self.sp_model.encode(text, out_type=str)
300
+
301
+ def _convert_token_to_id(self, token):
302
+ """Converts a token (str) in an id using the vocab."""
303
+ if token.startswith("<extra_id_"):
304
+ match = re.match(r"<extra_id_(\d+)>", token)
305
+ num = int(match.group(1))
306
+ return self.vocab_size - num - 1
307
+ return self.sp_model.piece_to_id(token)
308
+
309
+ def _convert_id_to_token(self, index):
310
+ """Converts an index (integer) in a token (str) using the vocab."""
311
+ if index < self.sp_model.get_piece_size():
312
+ token = self.sp_model.IdToPiece(index)
313
+ else:
314
+ token = f"<extra_id_{self.vocab_size - 1 - index}>"
315
+ return token
316
+
317
+ def convert_tokens_to_string(self, tokens):
318
+ """Converts a sequence of tokens (string) in a single string."""
319
+ current_sub_tokens = []
320
+ out_string = ""
321
+ prev_is_special = False
322
+ for token in tokens:
323
+ # make sure that special tokens are not decoded using sentencepiece model
324
+ if token in self.all_special_tokens:
325
+ if not prev_is_special:
326
+ out_string += " "
327
+ out_string += self.sp_model.decode(current_sub_tokens) + token
328
+ prev_is_special = True
329
+ current_sub_tokens = []
330
+ else:
331
+ current_sub_tokens.append(token)
332
+ prev_is_special = False
333
+ out_string += self.sp_model.decode(current_sub_tokens)
334
+ return out_string.strip()
335
+
336
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
337
+ if not os.path.isdir(save_directory):
338
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
339
+ return
340
+ out_vocab_file = os.path.join(
341
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
342
+ )
343
+
344
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
345
+ copyfile(self.vocab_file, out_vocab_file)
346
+ elif not os.path.isfile(self.vocab_file):
347
+ with open(out_vocab_file, "wb") as fi:
348
+ content_spiece_model = self.sp_model.serialized_model_proto()
349
+ fi.write(content_spiece_model)
350
+
351
+ return (out_vocab_file,)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/table_transformer/convert_table_transformer_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Table Transformer checkpoints.
16
+
17
+ URL: https://github.com/microsoft/table-transformer
18
+ """
19
+
20
+
21
+ import argparse
22
+ from collections import OrderedDict
23
+ from pathlib import Path
24
+
25
+ import torch
26
+ from huggingface_hub import hf_hub_download
27
+ from PIL import Image
28
+ from torchvision.transforms import functional as F
29
+
30
+ from transformers import DetrFeatureExtractor, TableTransformerConfig, TableTransformerForObjectDetection
31
+ from transformers.utils import logging
32
+
33
+
34
+ logging.set_verbosity_info()
35
+ logger = logging.get_logger(__name__)
36
+
37
+ # here we list all keys to be renamed (original name on the left, our name on the right)
38
+ rename_keys = []
39
+ for i in range(6):
40
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
41
+ rename_keys.append(
42
+ (f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight")
43
+ )
44
+ rename_keys.append(
45
+ (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")
46
+ )
47
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight"))
48
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias"))
49
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight"))
50
+ rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias"))
51
+ rename_keys.append(
52
+ (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")
53
+ )
54
+ rename_keys.append((f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias"))
55
+ rename_keys.append((f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight"))
56
+ rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias"))
57
+ # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
58
+ rename_keys.append(
59
+ (f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight")
60
+ )
61
+ rename_keys.append(
62
+ (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")
63
+ )
64
+ rename_keys.append(
65
+ (
66
+ f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight",
67
+ f"decoder.layers.{i}.encoder_attn.out_proj.weight",
68
+ )
69
+ )
70
+ rename_keys.append(
71
+ (
72
+ f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias",
73
+ f"decoder.layers.{i}.encoder_attn.out_proj.bias",
74
+ )
75
+ )
76
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight"))
77
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias"))
78
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight"))
79
+ rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias"))
80
+ rename_keys.append(
81
+ (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")
82
+ )
83
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias"))
84
+ rename_keys.append(
85
+ (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")
86
+ )
87
+ rename_keys.append(
88
+ (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")
89
+ )
90
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight"))
91
+ rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias"))
92
+
93
+ # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads
94
+ rename_keys.extend(
95
+ [
96
+ ("input_proj.weight", "input_projection.weight"),
97
+ ("input_proj.bias", "input_projection.bias"),
98
+ ("query_embed.weight", "query_position_embeddings.weight"),
99
+ ("transformer.encoder.norm.weight", "encoder.layernorm.weight"),
100
+ ("transformer.encoder.norm.bias", "encoder.layernorm.bias"),
101
+ ("transformer.decoder.norm.weight", "decoder.layernorm.weight"),
102
+ ("transformer.decoder.norm.bias", "decoder.layernorm.bias"),
103
+ ("class_embed.weight", "class_labels_classifier.weight"),
104
+ ("class_embed.bias", "class_labels_classifier.bias"),
105
+ ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"),
106
+ ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"),
107
+ ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"),
108
+ ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"),
109
+ ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"),
110
+ ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"),
111
+ ]
112
+ )
113
+
114
+
115
+ def rename_key(state_dict, old, new):
116
+ val = state_dict.pop(old)
117
+ state_dict[new] = val
118
+
119
+
120
+ def rename_backbone_keys(state_dict):
121
+ new_state_dict = OrderedDict()
122
+ for key, value in state_dict.items():
123
+ if "backbone.0.body" in key:
124
+ new_key = key.replace("backbone.0.body", "backbone.conv_encoder.model")
125
+ new_state_dict[new_key] = value
126
+ else:
127
+ new_state_dict[key] = value
128
+
129
+ return new_state_dict
130
+
131
+
132
+ def read_in_q_k_v(state_dict):
133
+ prefix = ""
134
+
135
+ # first: transformer encoder
136
+ for i in range(6):
137
+ # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
138
+ in_proj_weight = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight")
139
+ in_proj_bias = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias")
140
+ # next, add query, keys and values (in that order) to the state dict
141
+ state_dict[f"encoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
142
+ state_dict[f"encoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
143
+ state_dict[f"encoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
144
+ state_dict[f"encoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
145
+ state_dict[f"encoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
146
+ state_dict[f"encoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
147
+ # next: transformer decoder (which is a bit more complex because it also includes cross-attention)
148
+ for i in range(6):
149
+ # read in weights + bias of input projection layer of self-attention
150
+ in_proj_weight = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight")
151
+ in_proj_bias = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias")
152
+ # next, add query, keys and values (in that order) to the state dict
153
+ state_dict[f"decoder.layers.{i}.self_attn.q_proj.weight"] = in_proj_weight[:256, :]
154
+ state_dict[f"decoder.layers.{i}.self_attn.q_proj.bias"] = in_proj_bias[:256]
155
+ state_dict[f"decoder.layers.{i}.self_attn.k_proj.weight"] = in_proj_weight[256:512, :]
156
+ state_dict[f"decoder.layers.{i}.self_attn.k_proj.bias"] = in_proj_bias[256:512]
157
+ state_dict[f"decoder.layers.{i}.self_attn.v_proj.weight"] = in_proj_weight[-256:, :]
158
+ state_dict[f"decoder.layers.{i}.self_attn.v_proj.bias"] = in_proj_bias[-256:]
159
+ # read in weights + bias of input projection layer of cross-attention
160
+ in_proj_weight_cross_attn = state_dict.pop(
161
+ f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight"
162
+ )
163
+ in_proj_bias_cross_attn = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias")
164
+ # next, add query, keys and values (in that order) of cross-attention to the state dict
165
+ state_dict[f"decoder.layers.{i}.encoder_attn.q_proj.weight"] = in_proj_weight_cross_attn[:256, :]
166
+ state_dict[f"decoder.layers.{i}.encoder_attn.q_proj.bias"] = in_proj_bias_cross_attn[:256]
167
+ state_dict[f"decoder.layers.{i}.encoder_attn.k_proj.weight"] = in_proj_weight_cross_attn[256:512, :]
168
+ state_dict[f"decoder.layers.{i}.encoder_attn.k_proj.bias"] = in_proj_bias_cross_attn[256:512]
169
+ state_dict[f"decoder.layers.{i}.encoder_attn.v_proj.weight"] = in_proj_weight_cross_attn[-256:, :]
170
+ state_dict[f"decoder.layers.{i}.encoder_attn.v_proj.bias"] = in_proj_bias_cross_attn[-256:]
171
+
172
+
173
+ def resize(image, checkpoint_url):
174
+ width, height = image.size
175
+ current_max_size = max(width, height)
176
+ target_max_size = 800 if "detection" in checkpoint_url else 1000
177
+ scale = target_max_size / current_max_size
178
+ resized_image = image.resize((int(round(scale * width)), int(round(scale * height))))
179
+
180
+ return resized_image
181
+
182
+
183
+ def normalize(image):
184
+ image = F.to_tensor(image)
185
+ image = F.normalize(image, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
186
+ return image
187
+
188
+
189
+ @torch.no_grad()
190
+ def convert_table_transformer_checkpoint(checkpoint_url, pytorch_dump_folder_path, push_to_hub):
191
+ """
192
+ Copy/paste/tweak model's weights to our DETR structure.
193
+ """
194
+
195
+ logger.info("Converting model...")
196
+
197
+ # load original state dict
198
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
199
+ # rename keys
200
+ for src, dest in rename_keys:
201
+ rename_key(state_dict, src, dest)
202
+ state_dict = rename_backbone_keys(state_dict)
203
+ # query, key and value matrices need special treatment
204
+ read_in_q_k_v(state_dict)
205
+ # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
206
+ prefix = "model."
207
+ for key in state_dict.copy().keys():
208
+ if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"):
209
+ val = state_dict.pop(key)
210
+ state_dict[prefix + key] = val
211
+ # create HuggingFace model and load state dict
212
+ config = TableTransformerConfig(
213
+ backbone="resnet18",
214
+ mask_loss_coefficient=1,
215
+ dice_loss_coefficient=1,
216
+ ce_loss_coefficient=1,
217
+ bbox_loss_coefficient=5,
218
+ giou_loss_coefficient=2,
219
+ eos_coefficient=0.4,
220
+ class_cost=1,
221
+ bbox_cost=5,
222
+ giou_cost=2,
223
+ )
224
+
225
+ if "detection" in checkpoint_url:
226
+ config.num_queries = 15
227
+ config.num_labels = 2
228
+ id2label = {0: "table", 1: "table rotated"}
229
+ config.id2label = id2label
230
+ config.label2id = {v: k for k, v in id2label.items()}
231
+ else:
232
+ config.num_queries = 125
233
+ config.num_labels = 6
234
+ id2label = {
235
+ 0: "table",
236
+ 1: "table column",
237
+ 2: "table row",
238
+ 3: "table column header",
239
+ 4: "table projected row header",
240
+ 5: "table spanning cell",
241
+ }
242
+ config.id2label = id2label
243
+ config.label2id = {v: k for k, v in id2label.items()}
244
+
245
+ feature_extractor = DetrFeatureExtractor(
246
+ format="coco_detection", max_size=800 if "detection" in checkpoint_url else 1000
247
+ )
248
+ model = TableTransformerForObjectDetection(config)
249
+ model.load_state_dict(state_dict)
250
+ model.eval()
251
+
252
+ # verify our conversion
253
+ filename = "example_pdf.png" if "detection" in checkpoint_url else "example_table.png"
254
+ file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename=filename)
255
+ image = Image.open(file_path).convert("RGB")
256
+ pixel_values = normalize(resize(image, checkpoint_url)).unsqueeze(0)
257
+
258
+ outputs = model(pixel_values)
259
+
260
+ if "detection" in checkpoint_url:
261
+ expected_shape = (1, 15, 3)
262
+ expected_logits = torch.tensor(
263
+ [[-6.7897, -16.9985, 6.7937], [-8.0186, -22.2192, 6.9677], [-7.3117, -21.0708, 7.4055]]
264
+ )
265
+ expected_boxes = torch.tensor([[0.4867, 0.1767, 0.6732], [0.6718, 0.4479, 0.3830], [0.4716, 0.1760, 0.6364]])
266
+
267
+ else:
268
+ expected_shape = (1, 125, 7)
269
+ expected_logits = torch.tensor(
270
+ [[-18.1430, -8.3214, 4.8274], [-18.4685, -7.1361, -4.2667], [-26.3693, -9.3429, -4.9962]]
271
+ )
272
+ expected_boxes = torch.tensor([[0.4983, 0.5595, 0.9440], [0.4916, 0.6315, 0.5954], [0.6108, 0.8637, 0.1135]])
273
+
274
+ assert outputs.logits.shape == expected_shape
275
+ assert torch.allclose(outputs.logits[0, :3, :3], expected_logits, atol=1e-4)
276
+ assert torch.allclose(outputs.pred_boxes[0, :3, :3], expected_boxes, atol=1e-4)
277
+ print("Looks ok!")
278
+
279
+ if pytorch_dump_folder_path is not None:
280
+ # Save model and feature extractor
281
+ logger.info(f"Saving PyTorch model and feature extractor to {pytorch_dump_folder_path}...")
282
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
283
+ model.save_pretrained(pytorch_dump_folder_path)
284
+ feature_extractor.save_pretrained(pytorch_dump_folder_path)
285
+
286
+ if push_to_hub:
287
+ # Push model to HF hub
288
+ logger.info("Pushing model to the hub...")
289
+ model_name = (
290
+ "microsoft/table-transformer-detection"
291
+ if "detection" in checkpoint_url
292
+ else "microsoft/table-transformer-structure-recognition"
293
+ )
294
+ model.push_to_hub(model_name)
295
+ feature_extractor.push_to_hub(model_name)
296
+
297
+
298
+ if __name__ == "__main__":
299
+ parser = argparse.ArgumentParser()
300
+
301
+ parser.add_argument(
302
+ "--checkpoint_url",
303
+ default="https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth",
304
+ type=str,
305
+ choices=[
306
+ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth",
307
+ "https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth",
308
+ ],
309
+ help="URL of the Table Transformer checkpoint you'd like to convert.",
310
+ )
311
+ parser.add_argument(
312
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
313
+ )
314
+ parser.add_argument(
315
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
316
+ )
317
+ args = parser.parse_args()
318
+ convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/table_transformer/modeling_table_transformer.py ADDED
@@ -0,0 +1,1943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft Research 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 Table Transformer model."""
16
+
17
+
18
+ import math
19
+ import random
20
+ from dataclasses import dataclass
21
+ from typing import Dict, List, Optional, Tuple
22
+
23
+ import torch
24
+ from torch import Tensor, nn
25
+
26
+ from ...activations import ACT2FN
27
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithCrossAttentions, Seq2SeqModelOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ is_scipy_available,
34
+ is_timm_available,
35
+ is_vision_available,
36
+ logging,
37
+ replace_return_docstrings,
38
+ requires_backends,
39
+ )
40
+ from ..auto import AutoBackbone
41
+ from .configuration_table_transformer import TableTransformerConfig
42
+
43
+
44
+ if is_scipy_available():
45
+ from scipy.optimize import linear_sum_assignment
46
+
47
+ if is_timm_available():
48
+ from timm import create_model
49
+
50
+ if is_vision_available():
51
+ from transformers.image_transforms import center_to_corners_format
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "TableTransformerConfig"
56
+ _CHECKPOINT_FOR_DOC = "microsoft/table-transformer-detection"
57
+
58
+ TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
59
+ "microsoft/table-transformer-detection",
60
+ # See all Table Transformer models at https://huggingface.co/models?filter=table-transformer
61
+ ]
62
+
63
+
64
+ @dataclass
65
+ # Copied from transformers.models.detr.modeling_detr.DetrDecoderOutput with DETR->TABLE_TRANSFORMER,Detr->TableTransformer
66
+ class TableTransformerDecoderOutput(BaseModelOutputWithCrossAttentions):
67
+ """
68
+ Base class for outputs of the TABLE_TRANSFORMER decoder. This class adds one attribute to
69
+ BaseModelOutputWithCrossAttentions, namely an optional stack of intermediate decoder activations, i.e. the output
70
+ of each decoder layer, each of them gone through a layernorm. This is useful when training the model with auxiliary
71
+ decoding losses.
72
+
73
+ Args:
74
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
75
+ Sequence of hidden-states at the output of the last layer of the model.
76
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
77
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
78
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
79
+ plus the initial embedding outputs.
80
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
81
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
82
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
83
+ the self-attention heads.
84
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
85
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
86
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
87
+ used to compute the weighted average in the cross-attention heads.
88
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
89
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
90
+ layernorm.
91
+ """
92
+
93
+ intermediate_hidden_states: Optional[torch.FloatTensor] = None
94
+
95
+
96
+ @dataclass
97
+ # Copied from transformers.models.detr.modeling_detr.DetrModelOutput with DETR->TABLE_TRANSFORMER,Detr->TableTransformer
98
+ class TableTransformerModelOutput(Seq2SeqModelOutput):
99
+ """
100
+ Base class for outputs of the TABLE_TRANSFORMER encoder-decoder model. This class adds one attribute to
101
+ Seq2SeqModelOutput, namely an optional stack of intermediate decoder activations, i.e. the output of each decoder
102
+ layer, each of them gone through a layernorm. This is useful when training the model with auxiliary decoding
103
+ losses.
104
+
105
+ Args:
106
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
107
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
108
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
109
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
110
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each
111
+ layer plus the initial embedding outputs.
112
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
113
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
114
+ sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the
115
+ weighted average in the self-attention heads.
116
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
117
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
118
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
119
+ used to compute the weighted average in the cross-attention heads.
120
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
121
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
122
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
123
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
124
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
125
+ layer plus the initial embedding outputs.
126
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
127
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
128
+ sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the
129
+ weighted average in the self-attention heads.
130
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
131
+ Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
132
+ layernorm.
133
+ """
134
+
135
+ intermediate_hidden_states: Optional[torch.FloatTensor] = None
136
+
137
+
138
+ @dataclass
139
+ # Copied from transformers.models.detr.modeling_detr.DetrObjectDetectionOutput with Detr->TableTransformer,DetrImageProcessor->DetrImageProcessor
140
+ class TableTransformerObjectDetectionOutput(ModelOutput):
141
+ """
142
+ Output type of [`TableTransformerForObjectDetection`].
143
+
144
+ Args:
145
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
146
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
147
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
148
+ scale-invariant IoU loss.
149
+ loss_dict (`Dict`, *optional*):
150
+ A dictionary containing the individual losses. Useful for logging.
151
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
152
+ Classification logits (including no-object) for all queries.
153
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
154
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
155
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
156
+ possible padding). You can use [`~TableTransformerImageProcessor.post_process_object_detection`] to
157
+ retrieve the unnormalized bounding boxes.
158
+ auxiliary_outputs (`list[Dict]`, *optional*):
159
+ Optional, only returned when auxilary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
160
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
161
+ `pred_boxes`) for each decoder layer.
162
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
163
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
164
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
165
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
166
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each
167
+ layer plus the initial embedding outputs.
168
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
169
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
170
+ sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the
171
+ weighted average in the self-attention heads.
172
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
173
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
174
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
175
+ used to compute the weighted average in the cross-attention heads.
176
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
177
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
178
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
179
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
180
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
181
+ layer plus the initial embedding outputs.
182
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
183
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
184
+ sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the
185
+ weighted average in the self-attention heads.
186
+ """
187
+
188
+ loss: Optional[torch.FloatTensor] = None
189
+ loss_dict: Optional[Dict] = None
190
+ logits: torch.FloatTensor = None
191
+ pred_boxes: torch.FloatTensor = None
192
+ auxiliary_outputs: Optional[List[Dict]] = None
193
+ last_hidden_state: Optional[torch.FloatTensor] = None
194
+ decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
195
+ decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
196
+ cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
197
+ encoder_last_hidden_state: Optional[torch.FloatTensor] = None
198
+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
199
+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
200
+
201
+
202
+ # Copied from transformers.models.detr.modeling_detr.DetrFrozenBatchNorm2d with Detr->TableTransformer
203
+ class TableTransformerFrozenBatchNorm2d(nn.Module):
204
+ """
205
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
206
+
207
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
208
+ torchvision.models.resnet[18,34,50,101] produce nans.
209
+ """
210
+
211
+ def __init__(self, n):
212
+ super().__init__()
213
+ self.register_buffer("weight", torch.ones(n))
214
+ self.register_buffer("bias", torch.zeros(n))
215
+ self.register_buffer("running_mean", torch.zeros(n))
216
+ self.register_buffer("running_var", torch.ones(n))
217
+
218
+ def _load_from_state_dict(
219
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
220
+ ):
221
+ num_batches_tracked_key = prefix + "num_batches_tracked"
222
+ if num_batches_tracked_key in state_dict:
223
+ del state_dict[num_batches_tracked_key]
224
+
225
+ super()._load_from_state_dict(
226
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
227
+ )
228
+
229
+ def forward(self, x):
230
+ # move reshapes to the beginning
231
+ # to make it user-friendly
232
+ weight = self.weight.reshape(1, -1, 1, 1)
233
+ bias = self.bias.reshape(1, -1, 1, 1)
234
+ running_var = self.running_var.reshape(1, -1, 1, 1)
235
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
236
+ epsilon = 1e-5
237
+ scale = weight * (running_var + epsilon).rsqrt()
238
+ bias = bias - running_mean * scale
239
+ return x * scale + bias
240
+
241
+
242
+ # Copied from transformers.models.detr.modeling_detr.replace_batch_norm with Detr->TableTransformer
243
+ def replace_batch_norm(m, name=""):
244
+ for attr_str in dir(m):
245
+ target_attr = getattr(m, attr_str)
246
+ if isinstance(target_attr, nn.BatchNorm2d):
247
+ frozen = TableTransformerFrozenBatchNorm2d(target_attr.num_features)
248
+ bn = getattr(m, attr_str)
249
+ frozen.weight.data.copy_(bn.weight)
250
+ frozen.bias.data.copy_(bn.bias)
251
+ frozen.running_mean.data.copy_(bn.running_mean)
252
+ frozen.running_var.data.copy_(bn.running_var)
253
+ setattr(m, attr_str, frozen)
254
+ for n, ch in m.named_children():
255
+ replace_batch_norm(ch, n)
256
+
257
+
258
+ # Copied from transformers.models.detr.modeling_detr.DetrConvEncoder with Detr->TableTransformer
259
+ class TableTransformerConvEncoder(nn.Module):
260
+ """
261
+ Convolutional backbone, using either the AutoBackbone API or one from the timm library.
262
+
263
+ nn.BatchNorm2d layers are replaced by TableTransformerFrozenBatchNorm2d as defined above.
264
+
265
+ """
266
+
267
+ def __init__(self, config):
268
+ super().__init__()
269
+
270
+ self.config = config
271
+
272
+ if config.use_timm_backbone:
273
+ requires_backends(self, ["timm"])
274
+ kwargs = {}
275
+ if config.dilation:
276
+ kwargs["output_stride"] = 16
277
+ backbone = create_model(
278
+ config.backbone,
279
+ pretrained=config.use_pretrained_backbone,
280
+ features_only=True,
281
+ out_indices=(1, 2, 3, 4),
282
+ in_chans=config.num_channels,
283
+ **kwargs,
284
+ )
285
+ else:
286
+ backbone = AutoBackbone.from_config(config.backbone_config)
287
+
288
+ # replace batch norm by frozen batch norm
289
+ with torch.no_grad():
290
+ replace_batch_norm(backbone)
291
+ self.model = backbone
292
+ self.intermediate_channel_sizes = (
293
+ self.model.feature_info.channels() if config.use_timm_backbone else self.model.channels
294
+ )
295
+
296
+ backbone_model_type = config.backbone if config.use_timm_backbone else config.backbone_config.model_type
297
+ if "resnet" in backbone_model_type:
298
+ for name, parameter in self.model.named_parameters():
299
+ if config.use_timm_backbone:
300
+ if "layer2" not in name and "layer3" not in name and "layer4" not in name:
301
+ parameter.requires_grad_(False)
302
+ else:
303
+ if "stage.1" not in name and "stage.2" not in name and "stage.3" not in name:
304
+ parameter.requires_grad_(False)
305
+
306
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
307
+ # send pixel_values through the model to get list of feature maps
308
+ features = self.model(pixel_values) if self.config.use_timm_backbone else self.model(pixel_values).feature_maps
309
+
310
+ out = []
311
+ for feature_map in features:
312
+ # downsample pixel_mask to match shape of corresponding feature_map
313
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
314
+ out.append((feature_map, mask))
315
+ return out
316
+
317
+
318
+ # Copied from transformers.models.detr.modeling_detr.DetrConvModel with Detr->TableTransformer
319
+ class TableTransformerConvModel(nn.Module):
320
+ """
321
+ This module adds 2D position embeddings to all intermediate feature maps of the convolutional encoder.
322
+ """
323
+
324
+ def __init__(self, conv_encoder, position_embedding):
325
+ super().__init__()
326
+ self.conv_encoder = conv_encoder
327
+ self.position_embedding = position_embedding
328
+
329
+ def forward(self, pixel_values, pixel_mask):
330
+ # send pixel_values and pixel_mask through backbone to get list of (feature_map, pixel_mask) tuples
331
+ out = self.conv_encoder(pixel_values, pixel_mask)
332
+ pos = []
333
+ for feature_map, mask in out:
334
+ # position encoding
335
+ pos.append(self.position_embedding(feature_map, mask).to(feature_map.dtype))
336
+
337
+ return out, pos
338
+
339
+
340
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, target_len: Optional[int] = None):
341
+ """
342
+ Expands attention_mask from `[batch_size, seq_len]` to `[batch_size, 1, target_seq_len, source_seq_len]`.
343
+ """
344
+ batch_size, source_len = mask.size()
345
+ target_len = target_len if target_len is not None else source_len
346
+
347
+ expanded_mask = mask[:, None, None, :].expand(batch_size, 1, target_len, source_len).to(dtype)
348
+
349
+ inverted_mask = 1.0 - expanded_mask
350
+
351
+ return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
352
+
353
+
354
+ # Copied from transformers.models.detr.modeling_detr.DetrSinePositionEmbedding with Detr->TableTransformer
355
+ class TableTransformerSinePositionEmbedding(nn.Module):
356
+ """
357
+ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
358
+ need paper, generalized to work on images.
359
+ """
360
+
361
+ def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None):
362
+ super().__init__()
363
+ self.embedding_dim = embedding_dim
364
+ self.temperature = temperature
365
+ self.normalize = normalize
366
+ if scale is not None and normalize is False:
367
+ raise ValueError("normalize should be True if scale is passed")
368
+ if scale is None:
369
+ scale = 2 * math.pi
370
+ self.scale = scale
371
+
372
+ def forward(self, pixel_values, pixel_mask):
373
+ if pixel_mask is None:
374
+ raise ValueError("No pixel mask provided")
375
+ y_embed = pixel_mask.cumsum(1, dtype=torch.float32)
376
+ x_embed = pixel_mask.cumsum(2, dtype=torch.float32)
377
+ if self.normalize:
378
+ y_embed = y_embed / (y_embed[:, -1:, :] + 1e-6) * self.scale
379
+ x_embed = x_embed / (x_embed[:, :, -1:] + 1e-6) * self.scale
380
+
381
+ dim_t = torch.arange(self.embedding_dim, dtype=torch.float32, device=pixel_values.device)
382
+ dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.embedding_dim)
383
+
384
+ pos_x = x_embed[:, :, :, None] / dim_t
385
+ pos_y = y_embed[:, :, :, None] / dim_t
386
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
387
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
388
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
389
+ return pos
390
+
391
+
392
+ # Copied from transformers.models.detr.modeling_detr.DetrLearnedPositionEmbedding with Detr->TableTransformer
393
+ class TableTransformerLearnedPositionEmbedding(nn.Module):
394
+ """
395
+ This module learns positional embeddings up to a fixed maximum size.
396
+ """
397
+
398
+ def __init__(self, embedding_dim=256):
399
+ super().__init__()
400
+ self.row_embeddings = nn.Embedding(50, embedding_dim)
401
+ self.column_embeddings = nn.Embedding(50, embedding_dim)
402
+
403
+ def forward(self, pixel_values, pixel_mask=None):
404
+ height, width = pixel_values.shape[-2:]
405
+ width_values = torch.arange(width, device=pixel_values.device)
406
+ height_values = torch.arange(height, device=pixel_values.device)
407
+ x_emb = self.column_embeddings(width_values)
408
+ y_emb = self.row_embeddings(height_values)
409
+ pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1)
410
+ pos = pos.permute(2, 0, 1)
411
+ pos = pos.unsqueeze(0)
412
+ pos = pos.repeat(pixel_values.shape[0], 1, 1, 1)
413
+ return pos
414
+
415
+
416
+ # Copied from transformers.models.detr.modeling_detr.build_position_encoding with Detr->TableTransformer
417
+ def build_position_encoding(config):
418
+ n_steps = config.d_model // 2
419
+ if config.position_embedding_type == "sine":
420
+ # TODO find a better way of exposing other arguments
421
+ position_embedding = TableTransformerSinePositionEmbedding(n_steps, normalize=True)
422
+ elif config.position_embedding_type == "learned":
423
+ position_embedding = TableTransformerLearnedPositionEmbedding(n_steps)
424
+ else:
425
+ raise ValueError(f"Not supported {config.position_embedding_type}")
426
+
427
+ return position_embedding
428
+
429
+
430
+ # Copied from transformers.models.detr.modeling_detr.DetrAttention with DETR->TABLE_TRANSFORMER,Detr->TableTransformer
431
+ class TableTransformerAttention(nn.Module):
432
+ """
433
+ Multi-headed attention from 'Attention Is All You Need' paper.
434
+
435
+ Here, we add position embeddings to the queries and keys (as explained in the TABLE_TRANSFORMER paper).
436
+ """
437
+
438
+ def __init__(
439
+ self,
440
+ embed_dim: int,
441
+ num_heads: int,
442
+ dropout: float = 0.0,
443
+ is_decoder: bool = False,
444
+ bias: bool = True,
445
+ ):
446
+ super().__init__()
447
+ self.embed_dim = embed_dim
448
+ self.num_heads = num_heads
449
+ self.dropout = dropout
450
+ self.head_dim = embed_dim // num_heads
451
+ if self.head_dim * num_heads != self.embed_dim:
452
+ raise ValueError(
453
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
454
+ f" {num_heads})."
455
+ )
456
+ self.scaling = self.head_dim**-0.5
457
+
458
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
459
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
460
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
461
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
462
+
463
+ def _shape(self, tensor: torch.Tensor, seq_len: int, batch_size: int):
464
+ return tensor.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
465
+
466
+ def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]):
467
+ return tensor if position_embeddings is None else tensor + position_embeddings
468
+
469
+ def forward(
470
+ self,
471
+ hidden_states: torch.Tensor,
472
+ attention_mask: Optional[torch.Tensor] = None,
473
+ position_embeddings: Optional[torch.Tensor] = None,
474
+ key_value_states: Optional[torch.Tensor] = None,
475
+ key_value_position_embeddings: 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
+ batch_size, target_len, embed_dim = hidden_states.size()
484
+
485
+ # add position embeddings to the hidden states before projecting to queries and keys
486
+ if position_embeddings is not None:
487
+ hidden_states_original = hidden_states
488
+ hidden_states = self.with_pos_embed(hidden_states, position_embeddings)
489
+
490
+ # add key-value position embeddings to the key value states
491
+ if key_value_position_embeddings is not None:
492
+ key_value_states_original = key_value_states
493
+ key_value_states = self.with_pos_embed(key_value_states, key_value_position_embeddings)
494
+
495
+ # get query proj
496
+ query_states = self.q_proj(hidden_states) * self.scaling
497
+ # get key, value proj
498
+ if is_cross_attention:
499
+ # cross_attentions
500
+ key_states = self._shape(self.k_proj(key_value_states), -1, batch_size)
501
+ value_states = self._shape(self.v_proj(key_value_states_original), -1, batch_size)
502
+ else:
503
+ # self_attention
504
+ key_states = self._shape(self.k_proj(hidden_states), -1, batch_size)
505
+ value_states = self._shape(self.v_proj(hidden_states_original), -1, batch_size)
506
+
507
+ proj_shape = (batch_size * self.num_heads, -1, self.head_dim)
508
+ query_states = self._shape(query_states, target_len, batch_size).view(*proj_shape)
509
+ key_states = key_states.view(*proj_shape)
510
+ value_states = value_states.view(*proj_shape)
511
+
512
+ source_len = key_states.size(1)
513
+
514
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
515
+
516
+ if attn_weights.size() != (batch_size * self.num_heads, target_len, source_len):
517
+ raise ValueError(
518
+ f"Attention weights should be of size {(batch_size * self.num_heads, target_len, source_len)}, but is"
519
+ f" {attn_weights.size()}"
520
+ )
521
+
522
+ if attention_mask is not None:
523
+ if attention_mask.size() != (batch_size, 1, target_len, source_len):
524
+ raise ValueError(
525
+ f"Attention mask should be of size {(batch_size, 1, target_len, source_len)}, but is"
526
+ f" {attention_mask.size()}"
527
+ )
528
+ attn_weights = attn_weights.view(batch_size, self.num_heads, target_len, source_len) + attention_mask
529
+ attn_weights = attn_weights.view(batch_size * self.num_heads, target_len, source_len)
530
+
531
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
532
+
533
+ if output_attentions:
534
+ # this operation is a bit awkward, but it's required to
535
+ # make sure that attn_weights keeps its gradient.
536
+ # In order to do so, attn_weights have to reshaped
537
+ # twice and have to be reused in the following
538
+ attn_weights_reshaped = attn_weights.view(batch_size, self.num_heads, target_len, source_len)
539
+ attn_weights = attn_weights_reshaped.view(batch_size * self.num_heads, target_len, source_len)
540
+ else:
541
+ attn_weights_reshaped = None
542
+
543
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
544
+
545
+ attn_output = torch.bmm(attn_probs, value_states)
546
+
547
+ if attn_output.size() != (batch_size * self.num_heads, target_len, self.head_dim):
548
+ raise ValueError(
549
+ f"`attn_output` should be of size {(batch_size, self.num_heads, target_len, self.head_dim)}, but is"
550
+ f" {attn_output.size()}"
551
+ )
552
+
553
+ attn_output = attn_output.view(batch_size, self.num_heads, target_len, self.head_dim)
554
+ attn_output = attn_output.transpose(1, 2)
555
+ attn_output = attn_output.reshape(batch_size, target_len, embed_dim)
556
+
557
+ attn_output = self.out_proj(attn_output)
558
+
559
+ return attn_output, attn_weights_reshaped
560
+
561
+
562
+ class TableTransformerEncoderLayer(nn.Module):
563
+ # Copied from transformers.models.detr.modeling_detr.DetrEncoderLayer.__init__ with Detr->TableTransformer
564
+ def __init__(self, config: TableTransformerConfig):
565
+ super().__init__()
566
+ self.embed_dim = config.d_model
567
+ self.self_attn = TableTransformerAttention(
568
+ embed_dim=self.embed_dim,
569
+ num_heads=config.encoder_attention_heads,
570
+ dropout=config.attention_dropout,
571
+ )
572
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
573
+ self.dropout = config.dropout
574
+ self.activation_fn = ACT2FN[config.activation_function]
575
+ self.activation_dropout = config.activation_dropout
576
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
577
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
578
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
579
+
580
+ def forward(
581
+ self,
582
+ hidden_states: torch.Tensor,
583
+ attention_mask: torch.Tensor,
584
+ position_embeddings: torch.Tensor = None,
585
+ output_attentions: bool = False,
586
+ ):
587
+ """
588
+ Args:
589
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
590
+ attention_mask (`torch.FloatTensor`): attention mask of size
591
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
592
+ values.
593
+ position_embeddings (`torch.FloatTensor`, *optional*): position embeddings, to be added to hidden_states.
594
+ output_attentions (`bool`, *optional*):
595
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
596
+ returned tensors for more detail.
597
+ """
598
+ residual = hidden_states
599
+ hidden_states = self.self_attn_layer_norm(hidden_states)
600
+
601
+ hidden_states, attn_weights = self.self_attn(
602
+ hidden_states=hidden_states,
603
+ attention_mask=attention_mask,
604
+ position_embeddings=position_embeddings,
605
+ output_attentions=output_attentions,
606
+ )
607
+
608
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
609
+ hidden_states = residual + hidden_states
610
+
611
+ residual = hidden_states
612
+ hidden_states = self.final_layer_norm(hidden_states)
613
+
614
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
615
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
616
+
617
+ hidden_states = self.fc2(hidden_states)
618
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
619
+
620
+ hidden_states = residual + hidden_states
621
+
622
+ if self.training:
623
+ if torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any():
624
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
625
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
626
+
627
+ outputs = (hidden_states,)
628
+
629
+ if output_attentions:
630
+ outputs += (attn_weights,)
631
+
632
+ return outputs
633
+
634
+
635
+ class TableTransformerDecoderLayer(nn.Module):
636
+ # Copied from transformers.models.detr.modeling_detr.DetrDecoderLayer.__init__ with Detr->TableTransformer
637
+ def __init__(self, config: TableTransformerConfig):
638
+ super().__init__()
639
+ self.embed_dim = config.d_model
640
+
641
+ self.self_attn = TableTransformerAttention(
642
+ embed_dim=self.embed_dim,
643
+ num_heads=config.decoder_attention_heads,
644
+ dropout=config.attention_dropout,
645
+ is_decoder=True,
646
+ )
647
+ self.dropout = config.dropout
648
+ self.activation_fn = ACT2FN[config.activation_function]
649
+ self.activation_dropout = config.activation_dropout
650
+
651
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
652
+ self.encoder_attn = TableTransformerAttention(
653
+ self.embed_dim,
654
+ config.decoder_attention_heads,
655
+ dropout=config.attention_dropout,
656
+ is_decoder=True,
657
+ )
658
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
659
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
660
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
661
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
662
+
663
+ def forward(
664
+ self,
665
+ hidden_states: torch.Tensor,
666
+ attention_mask: Optional[torch.Tensor] = None,
667
+ position_embeddings: Optional[torch.Tensor] = None,
668
+ query_position_embeddings: Optional[torch.Tensor] = None,
669
+ encoder_hidden_states: Optional[torch.Tensor] = None,
670
+ encoder_attention_mask: Optional[torch.Tensor] = None,
671
+ output_attentions: Optional[bool] = False,
672
+ ):
673
+ """
674
+ Args:
675
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
676
+ attention_mask (`torch.FloatTensor`): attention mask of size
677
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
678
+ values.
679
+ position_embeddings (`torch.FloatTensor`, *optional*):
680
+ position embeddings that are added to the queries and keys
681
+ in the cross-attention layer.
682
+ query_position_embeddings (`torch.FloatTensor`, *optional*):
683
+ position embeddings that are added to the queries and keys
684
+ in the self-attention layer.
685
+ encoder_hidden_states (`torch.FloatTensor`):
686
+ cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
687
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
688
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
689
+ values.
690
+ output_attentions (`bool`, *optional*):
691
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
692
+ returned tensors for more detail.
693
+ """
694
+ residual = hidden_states
695
+ hidden_states = self.self_attn_layer_norm(hidden_states)
696
+
697
+ # Self Attention
698
+ hidden_states, self_attn_weights = self.self_attn(
699
+ hidden_states=hidden_states,
700
+ position_embeddings=query_position_embeddings,
701
+ attention_mask=attention_mask,
702
+ output_attentions=output_attentions,
703
+ )
704
+
705
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
706
+ hidden_states = residual + hidden_states
707
+
708
+ residual = hidden_states
709
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
710
+
711
+ # Cross-Attention Block
712
+ cross_attn_weights = None
713
+ if encoder_hidden_states is not None:
714
+ hidden_states, cross_attn_weights = self.encoder_attn(
715
+ hidden_states=hidden_states,
716
+ position_embeddings=query_position_embeddings,
717
+ key_value_states=encoder_hidden_states,
718
+ attention_mask=encoder_attention_mask,
719
+ key_value_position_embeddings=position_embeddings,
720
+ output_attentions=output_attentions,
721
+ )
722
+
723
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
724
+ hidden_states = residual + hidden_states
725
+
726
+ residual = hidden_states
727
+ hidden_states = self.final_layer_norm(hidden_states)
728
+
729
+ # Fully Connected
730
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
731
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
732
+ hidden_states = self.fc2(hidden_states)
733
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
734
+ hidden_states = residual + hidden_states
735
+
736
+ outputs = (hidden_states,)
737
+
738
+ if output_attentions:
739
+ outputs += (self_attn_weights, cross_attn_weights)
740
+
741
+ return outputs
742
+
743
+
744
+ # Copied from transformers.models.detr.modeling_detr.DetrClassificationHead with Detr->TableTransformer
745
+ class TableTransformerClassificationHead(nn.Module):
746
+ """Head for sentence-level classification tasks."""
747
+
748
+ def __init__(self, input_dim: int, inner_dim: int, num_classes: int, pooler_dropout: float):
749
+ super().__init__()
750
+ self.dense = nn.Linear(input_dim, inner_dim)
751
+ self.dropout = nn.Dropout(p=pooler_dropout)
752
+ self.out_proj = nn.Linear(inner_dim, num_classes)
753
+
754
+ def forward(self, hidden_states: torch.Tensor):
755
+ hidden_states = self.dropout(hidden_states)
756
+ hidden_states = self.dense(hidden_states)
757
+ hidden_states = torch.tanh(hidden_states)
758
+ hidden_states = self.dropout(hidden_states)
759
+ hidden_states = self.out_proj(hidden_states)
760
+ return hidden_states
761
+
762
+
763
+ class TableTransformerPreTrainedModel(PreTrainedModel):
764
+ config_class = TableTransformerConfig
765
+ base_model_prefix = "model"
766
+ main_input_name = "pixel_values"
767
+
768
+ def _init_weights(self, module):
769
+ std = self.config.init_std
770
+
771
+ if isinstance(module, TableTransformerLearnedPositionEmbedding):
772
+ nn.init.uniform_(module.row_embeddings.weight)
773
+ nn.init.uniform_(module.column_embeddings.weight)
774
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
775
+ # Slightly different from the TF version which uses truncated_normal for initialization
776
+ # cf https://github.com/pytorch/pytorch/pull/5617
777
+ module.weight.data.normal_(mean=0.0, std=std)
778
+ if module.bias is not None:
779
+ module.bias.data.zero_()
780
+ elif isinstance(module, nn.Embedding):
781
+ module.weight.data.normal_(mean=0.0, std=std)
782
+ if module.padding_idx is not None:
783
+ module.weight.data[module.padding_idx].zero_()
784
+
785
+ def _set_gradient_checkpointing(self, module, value=False):
786
+ if isinstance(module, TableTransformerDecoder):
787
+ module.gradient_checkpointing = value
788
+
789
+
790
+ TABLE_TRANSFORMER_START_DOCSTRING = r"""
791
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
792
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
793
+ etc.)
794
+
795
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
796
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
797
+ and behavior.
798
+
799
+ Parameters:
800
+ config ([`TableTransformerConfig`]):
801
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
802
+ load the weights associated with the model, only the configuration. Check out the
803
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
804
+ """
805
+
806
+ TABLE_TRANSFORMER_INPUTS_DOCSTRING = r"""
807
+ Args:
808
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
809
+ Pixel values. Padding will be ignored by default should you provide it.
810
+
811
+ Pixel values can be obtained using [`DetrImageProcessor`]. See [`DetrImageProcessor.__call__`] for details.
812
+
813
+ pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
814
+ Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
815
+
816
+ - 1 for pixels that are real (i.e. **not masked**),
817
+ - 0 for pixels that are padding (i.e. **masked**).
818
+
819
+ [What are attention masks?](../glossary#attention-mask)
820
+
821
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, num_queries)`, *optional*):
822
+ Not used by default. Can be used to mask object queries.
823
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
824
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
825
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
826
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
827
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
828
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
829
+ can choose to directly pass a flattened representation of an image.
830
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
831
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
832
+ embedded representation.
833
+ output_attentions (`bool`, *optional*):
834
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
835
+ tensors for more detail.
836
+ output_hidden_states (`bool`, *optional*):
837
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
838
+ more detail.
839
+ return_dict (`bool`, *optional*):
840
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
841
+ """
842
+
843
+
844
+ class TableTransformerEncoder(TableTransformerPreTrainedModel):
845
+ """
846
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
847
+ [`TableTransformerEncoderLayer`].
848
+
849
+ The encoder updates the flattened feature map through multiple self-attention layers.
850
+
851
+ Small tweak for Table Transformer:
852
+
853
+ - position_embeddings are added to the forward pass.
854
+
855
+ Args:
856
+ config: TableTransformerConfig
857
+ """
858
+
859
+ def __init__(self, config: TableTransformerConfig):
860
+ super().__init__(config)
861
+
862
+ self.dropout = config.dropout
863
+ self.layerdrop = config.encoder_layerdrop
864
+
865
+ self.layers = nn.ModuleList([TableTransformerEncoderLayer(config) for _ in range(config.encoder_layers)])
866
+
867
+ self.layernorm = nn.LayerNorm(config.d_model)
868
+
869
+ # Initialize weights and apply final processing
870
+ self.post_init()
871
+
872
+ def forward(
873
+ self,
874
+ inputs_embeds=None,
875
+ attention_mask=None,
876
+ position_embeddings=None,
877
+ output_attentions=None,
878
+ output_hidden_states=None,
879
+ return_dict=None,
880
+ ):
881
+ r"""
882
+ Args:
883
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
884
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
885
+
886
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
887
+ Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
888
+
889
+ - 1 for pixel features that are real (i.e. **not masked**),
890
+ - 0 for pixel features that are padding (i.e. **masked**).
891
+
892
+ [What are attention masks?](../glossary#attention-mask)
893
+
894
+ position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
895
+ Position embeddings that are added to the queries and keys in each self-attention layer.
896
+
897
+ output_attentions (`bool`, *optional*):
898
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
899
+ returned tensors for more detail.
900
+ output_hidden_states (`bool`, *optional*):
901
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
902
+ for more detail.
903
+ return_dict (`bool`, *optional*):
904
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
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
+ hidden_states = inputs_embeds
913
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
914
+
915
+ # expand attention_mask
916
+ if attention_mask is not None:
917
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
918
+ attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
919
+
920
+ encoder_states = () if output_hidden_states else None
921
+ all_attentions = () if output_attentions else None
922
+ for encoder_layer in self.layers:
923
+ if output_hidden_states:
924
+ encoder_states = encoder_states + (hidden_states,)
925
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
926
+ dropout_probability = random.uniform(0, 1)
927
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
928
+ layer_outputs = (None, None)
929
+ else:
930
+ # we add position_embeddings as extra input to the encoder_layer
931
+ layer_outputs = encoder_layer(
932
+ hidden_states,
933
+ attention_mask,
934
+ position_embeddings=position_embeddings,
935
+ output_attentions=output_attentions,
936
+ )
937
+
938
+ hidden_states = layer_outputs[0]
939
+
940
+ if output_attentions:
941
+ all_attentions = all_attentions + (layer_outputs[1],)
942
+
943
+ if output_hidden_states:
944
+ encoder_states = encoder_states + (hidden_states,)
945
+
946
+ hidden_states = self.layernorm(hidden_states)
947
+
948
+ if not return_dict:
949
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
950
+ return BaseModelOutput(
951
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
952
+ )
953
+
954
+
955
+ # Copied from transformers.models.detr.modeling_detr.DetrDecoder with DETR->TABLE_TRANSFORMER,Detr->TableTransformer
956
+ class TableTransformerDecoder(TableTransformerPreTrainedModel):
957
+ """
958
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TableTransformerDecoderLayer`].
959
+
960
+ The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
961
+
962
+ Some small tweaks for TABLE_TRANSFORMER:
963
+
964
+ - position_embeddings and query_position_embeddings are added to the forward pass.
965
+ - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
966
+
967
+ Args:
968
+ config: TableTransformerConfig
969
+ """
970
+
971
+ def __init__(self, config: TableTransformerConfig):
972
+ super().__init__(config)
973
+ self.dropout = config.dropout
974
+ self.layerdrop = config.decoder_layerdrop
975
+
976
+ self.layers = nn.ModuleList([TableTransformerDecoderLayer(config) for _ in range(config.decoder_layers)])
977
+ # in TABLE_TRANSFORMER, the decoder uses layernorm after the last decoder layer output
978
+ self.layernorm = nn.LayerNorm(config.d_model)
979
+
980
+ self.gradient_checkpointing = False
981
+ # Initialize weights and apply final processing
982
+ self.post_init()
983
+
984
+ def forward(
985
+ self,
986
+ inputs_embeds=None,
987
+ attention_mask=None,
988
+ encoder_hidden_states=None,
989
+ encoder_attention_mask=None,
990
+ position_embeddings=None,
991
+ query_position_embeddings=None,
992
+ output_attentions=None,
993
+ output_hidden_states=None,
994
+ return_dict=None,
995
+ ):
996
+ r"""
997
+ Args:
998
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
999
+ The query embeddings that are passed into the decoder.
1000
+
1001
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1002
+ Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:
1003
+
1004
+ - 1 for queries that are **not masked**,
1005
+ - 0 for queries that are **masked**.
1006
+
1007
+ [What are attention masks?](../glossary#attention-mask)
1008
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1009
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1010
+ of the decoder.
1011
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1012
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
1013
+ in `[0, 1]`:
1014
+
1015
+ - 1 for pixels that are real (i.e. **not masked**),
1016
+ - 0 for pixels that are padding (i.e. **masked**).
1017
+
1018
+ position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1019
+ Position embeddings that are added to the queries and keys in each cross-attention layer.
1020
+ query_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
1021
+ , *optional*): Position embeddings that are added to the queries and keys in each self-attention layer.
1022
+ output_attentions (`bool`, *optional*):
1023
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1024
+ returned tensors for more detail.
1025
+ output_hidden_states (`bool`, *optional*):
1026
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1027
+ for more detail.
1028
+ return_dict (`bool`, *optional*):
1029
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1030
+ """
1031
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1032
+ output_hidden_states = (
1033
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1034
+ )
1035
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1036
+
1037
+ if inputs_embeds is not None:
1038
+ hidden_states = inputs_embeds
1039
+ input_shape = inputs_embeds.size()[:-1]
1040
+
1041
+ combined_attention_mask = None
1042
+
1043
+ if attention_mask is not None and combined_attention_mask is not None:
1044
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
1045
+ combined_attention_mask = combined_attention_mask + _expand_mask(
1046
+ attention_mask, inputs_embeds.dtype, target_len=input_shape[-1]
1047
+ )
1048
+
1049
+ # expand encoder attention mask
1050
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1051
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
1052
+ encoder_attention_mask = _expand_mask(
1053
+ encoder_attention_mask, inputs_embeds.dtype, target_len=input_shape[-1]
1054
+ )
1055
+
1056
+ # optional intermediate hidden states
1057
+ intermediate = () if self.config.auxiliary_loss else None
1058
+
1059
+ # decoder layers
1060
+ all_hidden_states = () if output_hidden_states else None
1061
+ all_self_attns = () if output_attentions else None
1062
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1063
+
1064
+ for idx, decoder_layer in enumerate(self.layers):
1065
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1066
+ if output_hidden_states:
1067
+ all_hidden_states += (hidden_states,)
1068
+ dropout_probability = random.uniform(0, 1)
1069
+ if self.training and (dropout_probability < self.layerdrop):
1070
+ continue
1071
+
1072
+ if self.gradient_checkpointing and self.training:
1073
+
1074
+ def create_custom_forward(module):
1075
+ def custom_forward(*inputs):
1076
+ return module(*inputs, output_attentions)
1077
+
1078
+ return custom_forward
1079
+
1080
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1081
+ create_custom_forward(decoder_layer),
1082
+ hidden_states,
1083
+ combined_attention_mask,
1084
+ encoder_hidden_states,
1085
+ encoder_attention_mask,
1086
+ None,
1087
+ )
1088
+ else:
1089
+ layer_outputs = decoder_layer(
1090
+ hidden_states,
1091
+ attention_mask=combined_attention_mask,
1092
+ position_embeddings=position_embeddings,
1093
+ query_position_embeddings=query_position_embeddings,
1094
+ encoder_hidden_states=encoder_hidden_states,
1095
+ encoder_attention_mask=encoder_attention_mask,
1096
+ output_attentions=output_attentions,
1097
+ )
1098
+
1099
+ hidden_states = layer_outputs[0]
1100
+
1101
+ if self.config.auxiliary_loss:
1102
+ hidden_states = self.layernorm(hidden_states)
1103
+ intermediate += (hidden_states,)
1104
+
1105
+ if output_attentions:
1106
+ all_self_attns += (layer_outputs[1],)
1107
+
1108
+ if encoder_hidden_states is not None:
1109
+ all_cross_attentions += (layer_outputs[2],)
1110
+
1111
+ # finally, apply layernorm
1112
+ hidden_states = self.layernorm(hidden_states)
1113
+
1114
+ # add hidden states from the last decoder layer
1115
+ if output_hidden_states:
1116
+ all_hidden_states += (hidden_states,)
1117
+
1118
+ # stack intermediate decoder activations
1119
+ if self.config.auxiliary_loss:
1120
+ intermediate = torch.stack(intermediate)
1121
+
1122
+ if not return_dict:
1123
+ return tuple(
1124
+ v
1125
+ for v in [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions, intermediate]
1126
+ if v is not None
1127
+ )
1128
+ return TableTransformerDecoderOutput(
1129
+ last_hidden_state=hidden_states,
1130
+ hidden_states=all_hidden_states,
1131
+ attentions=all_self_attns,
1132
+ cross_attentions=all_cross_attentions,
1133
+ intermediate_hidden_states=intermediate,
1134
+ )
1135
+
1136
+
1137
+ @add_start_docstrings(
1138
+ """
1139
+ The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) outputting raw
1140
+ hidden-states without any specific head on top.
1141
+ """,
1142
+ TABLE_TRANSFORMER_START_DOCSTRING,
1143
+ )
1144
+ class TableTransformerModel(TableTransformerPreTrainedModel):
1145
+ # Copied from transformers.models.detr.modeling_detr.DetrModel.__init__ with Detr->TableTransformer
1146
+ def __init__(self, config: TableTransformerConfig):
1147
+ super().__init__(config)
1148
+
1149
+ # Create backbone + positional encoding
1150
+ backbone = TableTransformerConvEncoder(config)
1151
+ position_embeddings = build_position_encoding(config)
1152
+ self.backbone = TableTransformerConvModel(backbone, position_embeddings)
1153
+
1154
+ # Create projection layer
1155
+ self.input_projection = nn.Conv2d(backbone.intermediate_channel_sizes[-1], config.d_model, kernel_size=1)
1156
+
1157
+ self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)
1158
+
1159
+ self.encoder = TableTransformerEncoder(config)
1160
+ self.decoder = TableTransformerDecoder(config)
1161
+
1162
+ # Initialize weights and apply final processing
1163
+ self.post_init()
1164
+
1165
+ def get_encoder(self):
1166
+ return self.encoder
1167
+
1168
+ def get_decoder(self):
1169
+ return self.decoder
1170
+
1171
+ def freeze_backbone(self):
1172
+ for name, param in self.backbone.conv_encoder.model.named_parameters():
1173
+ param.requires_grad_(False)
1174
+
1175
+ def unfreeze_backbone(self):
1176
+ for name, param in self.backbone.conv_encoder.model.named_parameters():
1177
+ param.requires_grad_(True)
1178
+
1179
+ @add_start_docstrings_to_model_forward(TABLE_TRANSFORMER_INPUTS_DOCSTRING)
1180
+ @replace_return_docstrings(output_type=TableTransformerModelOutput, config_class=_CONFIG_FOR_DOC)
1181
+ def forward(
1182
+ self,
1183
+ pixel_values,
1184
+ pixel_mask=None,
1185
+ decoder_attention_mask=None,
1186
+ encoder_outputs=None,
1187
+ inputs_embeds=None,
1188
+ decoder_inputs_embeds=None,
1189
+ output_attentions=None,
1190
+ output_hidden_states=None,
1191
+ return_dict=None,
1192
+ ):
1193
+ r"""
1194
+ Returns:
1195
+
1196
+ Examples:
1197
+
1198
+ ```python
1199
+ >>> from transformers import AutoImageProcessor, TableTransformerModel
1200
+ >>> from huggingface_hub import hf_hub_download
1201
+ >>> from PIL import Image
1202
+
1203
+ >>> file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_pdf.png")
1204
+ >>> image = Image.open(file_path).convert("RGB")
1205
+
1206
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection")
1207
+ >>> model = TableTransformerModel.from_pretrained("microsoft/table-transformer-detection")
1208
+
1209
+ >>> # prepare image for the model
1210
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1211
+
1212
+ >>> # forward pass
1213
+ >>> outputs = model(**inputs)
1214
+
1215
+ >>> # the last hidden states are the final query embeddings of the Transformer decoder
1216
+ >>> # these are of shape (batch_size, num_queries, hidden_size)
1217
+ >>> last_hidden_states = outputs.last_hidden_state
1218
+ >>> list(last_hidden_states.shape)
1219
+ [1, 15, 256]
1220
+ ```"""
1221
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1222
+ output_hidden_states = (
1223
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1224
+ )
1225
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1226
+
1227
+ batch_size, num_channels, height, width = pixel_values.shape
1228
+ device = pixel_values.device
1229
+
1230
+ if pixel_mask is None:
1231
+ pixel_mask = torch.ones(((batch_size, height, width)), device=device)
1232
+
1233
+ # First, sent pixel_values + pixel_mask through Backbone to obtain the features
1234
+ # pixel_values should be of shape (batch_size, num_channels, height, width)
1235
+ # pixel_mask should be of shape (batch_size, height, width)
1236
+ features, position_embeddings_list = self.backbone(pixel_values, pixel_mask)
1237
+
1238
+ # get final feature map and downsampled mask
1239
+ feature_map, mask = features[-1]
1240
+
1241
+ if mask is None:
1242
+ raise ValueError("Backbone does not return downsampled pixel mask")
1243
+
1244
+ # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
1245
+ projected_feature_map = self.input_projection(feature_map)
1246
+
1247
+ # Third, flatten the feature map + position embeddings of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
1248
+ # In other words, turn their shape into (batch_size, sequence_length, hidden_size)
1249
+ flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
1250
+ position_embeddings = position_embeddings_list[-1].flatten(2).permute(0, 2, 1)
1251
+
1252
+ flattened_mask = mask.flatten(1)
1253
+
1254
+ # Fourth, sent flattened_features + flattened_mask + position embeddings through encoder
1255
+ # flattened_features is a Tensor of shape (batch_size, heigth*width, hidden_size)
1256
+ # flattened_mask is a Tensor of shape (batch_size, heigth*width)
1257
+ if encoder_outputs is None:
1258
+ encoder_outputs = self.encoder(
1259
+ inputs_embeds=flattened_features,
1260
+ attention_mask=flattened_mask,
1261
+ position_embeddings=position_embeddings,
1262
+ output_attentions=output_attentions,
1263
+ output_hidden_states=output_hidden_states,
1264
+ return_dict=return_dict,
1265
+ )
1266
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1267
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1268
+ encoder_outputs = BaseModelOutput(
1269
+ last_hidden_state=encoder_outputs[0],
1270
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1271
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1272
+ )
1273
+
1274
+ # Fifth, sent query embeddings + position embeddings through the decoder (which is conditioned on the encoder output)
1275
+ query_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)
1276
+ queries = torch.zeros_like(query_position_embeddings)
1277
+
1278
+ # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
1279
+ decoder_outputs = self.decoder(
1280
+ inputs_embeds=queries,
1281
+ attention_mask=None,
1282
+ position_embeddings=position_embeddings,
1283
+ query_position_embeddings=query_position_embeddings,
1284
+ encoder_hidden_states=encoder_outputs[0],
1285
+ encoder_attention_mask=flattened_mask,
1286
+ output_attentions=output_attentions,
1287
+ output_hidden_states=output_hidden_states,
1288
+ return_dict=return_dict,
1289
+ )
1290
+
1291
+ if not return_dict:
1292
+ return decoder_outputs + encoder_outputs
1293
+
1294
+ return TableTransformerModelOutput(
1295
+ last_hidden_state=decoder_outputs.last_hidden_state,
1296
+ decoder_hidden_states=decoder_outputs.hidden_states,
1297
+ decoder_attentions=decoder_outputs.attentions,
1298
+ cross_attentions=decoder_outputs.cross_attentions,
1299
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1300
+ encoder_hidden_states=encoder_outputs.hidden_states,
1301
+ encoder_attentions=encoder_outputs.attentions,
1302
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
1303
+ )
1304
+
1305
+
1306
+ @add_start_docstrings(
1307
+ """
1308
+ Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on
1309
+ top, for tasks such as COCO detection.
1310
+ """,
1311
+ TABLE_TRANSFORMER_START_DOCSTRING,
1312
+ )
1313
+ class TableTransformerForObjectDetection(TableTransformerPreTrainedModel):
1314
+ # Copied from transformers.models.detr.modeling_detr.DetrForObjectDetection.__init__ with Detr->TableTransformer
1315
+ def __init__(self, config: TableTransformerConfig):
1316
+ super().__init__(config)
1317
+
1318
+ # DETR encoder-decoder model
1319
+ self.model = TableTransformerModel(config)
1320
+
1321
+ # Object detection heads
1322
+ self.class_labels_classifier = nn.Linear(
1323
+ config.d_model, config.num_labels + 1
1324
+ ) # We add one for the "no object" class
1325
+ self.bbox_predictor = TableTransformerMLPPredictionHead(
1326
+ input_dim=config.d_model, hidden_dim=config.d_model, output_dim=4, num_layers=3
1327
+ )
1328
+
1329
+ # Initialize weights and apply final processing
1330
+ self.post_init()
1331
+
1332
+ @torch.jit.unused
1333
+ # Copied from transformers.models.detr.modeling_detr.DetrForObjectDetection._set_aux_loss
1334
+ def _set_aux_loss(self, outputs_class, outputs_coord):
1335
+ # this is a workaround to make torchscript happy, as torchscript
1336
+ # doesn't support dictionary with non-homogeneous values, such
1337
+ # as a dict having both a Tensor and a list.
1338
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
1339
+
1340
+ @add_start_docstrings_to_model_forward(TABLE_TRANSFORMER_INPUTS_DOCSTRING)
1341
+ @replace_return_docstrings(output_type=TableTransformerObjectDetectionOutput, config_class=_CONFIG_FOR_DOC)
1342
+ def forward(
1343
+ self,
1344
+ pixel_values,
1345
+ pixel_mask=None,
1346
+ decoder_attention_mask=None,
1347
+ encoder_outputs=None,
1348
+ inputs_embeds=None,
1349
+ decoder_inputs_embeds=None,
1350
+ labels=None,
1351
+ output_attentions=None,
1352
+ output_hidden_states=None,
1353
+ return_dict=None,
1354
+ ):
1355
+ r"""
1356
+ labels (`List[Dict]` of len `(batch_size,)`, *optional*):
1357
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
1358
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
1359
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
1360
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
1361
+
1362
+ Returns:
1363
+
1364
+ Examples:
1365
+
1366
+ ```python
1367
+ >>> from huggingface_hub import hf_hub_download
1368
+ >>> from transformers import AutoImageProcessor, TableTransformerForObjectDetection
1369
+ >>> import torch
1370
+ >>> from PIL import Image
1371
+
1372
+ >>> file_path = hf_hub_download(repo_id="nielsr/example-pdf", repo_type="dataset", filename="example_pdf.png")
1373
+ >>> image = Image.open(file_path).convert("RGB")
1374
+
1375
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection")
1376
+ >>> model = TableTransformerForObjectDetection.from_pretrained("microsoft/table-transformer-detection")
1377
+
1378
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1379
+ >>> outputs = model(**inputs)
1380
+
1381
+ >>> # convert outputs (bounding boxes and class logits) to COCO API
1382
+ >>> target_sizes = torch.tensor([image.size[::-1]])
1383
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
1384
+ ... 0
1385
+ ... ]
1386
+
1387
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
1388
+ ... box = [round(i, 2) for i in box.tolist()]
1389
+ ... print(
1390
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
1391
+ ... f"{round(score.item(), 3)} at location {box}"
1392
+ ... )
1393
+ Detected table with confidence 1.0 at location [202.1, 210.59, 1119.22, 385.09]
1394
+ ```"""
1395
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1396
+
1397
+ # First, sent images through TABLE_TRANSFORMER base model to obtain encoder + decoder outputs
1398
+ outputs = self.model(
1399
+ pixel_values,
1400
+ pixel_mask=pixel_mask,
1401
+ decoder_attention_mask=decoder_attention_mask,
1402
+ encoder_outputs=encoder_outputs,
1403
+ inputs_embeds=inputs_embeds,
1404
+ decoder_inputs_embeds=decoder_inputs_embeds,
1405
+ output_attentions=output_attentions,
1406
+ output_hidden_states=output_hidden_states,
1407
+ return_dict=return_dict,
1408
+ )
1409
+
1410
+ sequence_output = outputs[0]
1411
+
1412
+ # class logits + predicted bounding boxes
1413
+ logits = self.class_labels_classifier(sequence_output)
1414
+ pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
1415
+
1416
+ loss, loss_dict, auxiliary_outputs = None, None, None
1417
+ if labels is not None:
1418
+ # First: create the matcher
1419
+ matcher = TableTransformerHungarianMatcher(
1420
+ class_cost=self.config.class_cost, bbox_cost=self.config.bbox_cost, giou_cost=self.config.giou_cost
1421
+ )
1422
+ # Second: create the criterion
1423
+ losses = ["labels", "boxes", "cardinality"]
1424
+ criterion = TableTransformerLoss(
1425
+ matcher=matcher,
1426
+ num_classes=self.config.num_labels,
1427
+ eos_coef=self.config.eos_coefficient,
1428
+ losses=losses,
1429
+ )
1430
+ criterion.to(self.device)
1431
+ # Third: compute the losses, based on outputs and labels
1432
+ outputs_loss = {}
1433
+ outputs_loss["logits"] = logits
1434
+ outputs_loss["pred_boxes"] = pred_boxes
1435
+ if self.config.auxiliary_loss:
1436
+ intermediate = outputs.intermediate_hidden_states if return_dict else outputs[4]
1437
+ outputs_class = self.class_labels_classifier(intermediate)
1438
+ outputs_coord = self.bbox_predictor(intermediate).sigmoid()
1439
+ auxiliary_outputs = self._set_aux_loss(outputs_class, outputs_coord)
1440
+ outputs_loss["auxiliary_outputs"] = auxiliary_outputs
1441
+
1442
+ loss_dict = criterion(outputs_loss, labels)
1443
+ # Fourth: compute total loss, as a weighted sum of the various losses
1444
+ weight_dict = {"loss_ce": 1, "loss_bbox": self.config.bbox_loss_coefficient}
1445
+ weight_dict["loss_giou"] = self.config.giou_loss_coefficient
1446
+ if self.config.auxiliary_loss:
1447
+ aux_weight_dict = {}
1448
+ for i in range(self.config.decoder_layers - 1):
1449
+ aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()})
1450
+ weight_dict.update(aux_weight_dict)
1451
+ loss = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)
1452
+
1453
+ if not return_dict:
1454
+ if auxiliary_outputs is not None:
1455
+ output = (logits, pred_boxes) + auxiliary_outputs + outputs
1456
+ else:
1457
+ output = (logits, pred_boxes) + outputs
1458
+ return ((loss, loss_dict) + output) if loss is not None else output
1459
+
1460
+ return TableTransformerObjectDetectionOutput(
1461
+ loss=loss,
1462
+ loss_dict=loss_dict,
1463
+ logits=logits,
1464
+ pred_boxes=pred_boxes,
1465
+ auxiliary_outputs=auxiliary_outputs,
1466
+ last_hidden_state=outputs.last_hidden_state,
1467
+ decoder_hidden_states=outputs.decoder_hidden_states,
1468
+ decoder_attentions=outputs.decoder_attentions,
1469
+ cross_attentions=outputs.cross_attentions,
1470
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1471
+ encoder_hidden_states=outputs.encoder_hidden_states,
1472
+ encoder_attentions=outputs.encoder_attentions,
1473
+ )
1474
+
1475
+
1476
+ # Copied from transformers.models.detr.modeling_detr.dice_loss
1477
+ def dice_loss(inputs, targets, num_boxes):
1478
+ """
1479
+ Compute the DICE loss, similar to generalized IOU for masks
1480
+
1481
+ Args:
1482
+ inputs: A float tensor of arbitrary shape.
1483
+ The predictions for each example.
1484
+ targets: A float tensor with the same shape as inputs. Stores the binary
1485
+ classification label for each element in inputs (0 for the negative class and 1 for the positive
1486
+ class).
1487
+ """
1488
+ inputs = inputs.sigmoid()
1489
+ inputs = inputs.flatten(1)
1490
+ numerator = 2 * (inputs * targets).sum(1)
1491
+ denominator = inputs.sum(-1) + targets.sum(-1)
1492
+ loss = 1 - (numerator + 1) / (denominator + 1)
1493
+ return loss.sum() / num_boxes
1494
+
1495
+
1496
+ # Copied from transformers.models.detr.modeling_detr.sigmoid_focal_loss
1497
+ def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):
1498
+ """
1499
+ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
1500
+
1501
+ Args:
1502
+ inputs (`torch.FloatTensor` of arbitrary shape):
1503
+ The predictions for each example.
1504
+ targets (`torch.FloatTensor` with the same shape as `inputs`)
1505
+ A tensor storing the binary classification label for each element in the `inputs` (0 for the negative class
1506
+ and 1 for the positive class).
1507
+ alpha (`float`, *optional*, defaults to `0.25`):
1508
+ Optional weighting factor in the range (0,1) to balance positive vs. negative examples.
1509
+ gamma (`int`, *optional*, defaults to `2`):
1510
+ Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples.
1511
+
1512
+ Returns:
1513
+ Loss tensor
1514
+ """
1515
+ prob = inputs.sigmoid()
1516
+ ce_loss = nn.functional.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
1517
+ # add modulating factor
1518
+ p_t = prob * targets + (1 - prob) * (1 - targets)
1519
+ loss = ce_loss * ((1 - p_t) ** gamma)
1520
+
1521
+ if alpha >= 0:
1522
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
1523
+ loss = alpha_t * loss
1524
+
1525
+ return loss.mean(1).sum() / num_boxes
1526
+
1527
+
1528
+ # Copied from transformers.models.detr.modeling_detr.DetrLoss with Detr->TableTransformer,detr->table_transformer
1529
+ class TableTransformerLoss(nn.Module):
1530
+ """
1531
+ This class computes the losses for TableTransformerForObjectDetection/TableTransformerForSegmentation. The process
1532
+ happens in two steps: 1) we compute hungarian assignment between ground truth boxes and the outputs of the model 2)
1533
+ we supervise each pair of matched ground-truth / prediction (supervise class and box).
1534
+
1535
+ A note on the `num_classes` argument (copied from original repo in table_transformer.py): "the naming of the
1536
+ `num_classes` parameter of the criterion is somewhat misleading. It indeed corresponds to `max_obj_id` + 1, where
1537
+ `max_obj_id` is the maximum id for a class in your dataset. For example, COCO has a `max_obj_id` of 90, so we pass
1538
+ `num_classes` to be 91. As another example, for a dataset that has a single class with `id` 1, you should pass
1539
+ `num_classes` to be 2 (`max_obj_id` + 1). For more details on this, check the following discussion
1540
+ https://github.com/facebookresearch/table_transformer/issues/108#issuecomment-650269223"
1541
+
1542
+
1543
+ Args:
1544
+ matcher (`TableTransformerHungarianMatcher`):
1545
+ Module able to compute a matching between targets and proposals.
1546
+ num_classes (`int`):
1547
+ Number of object categories, omitting the special no-object category.
1548
+ eos_coef (`float`):
1549
+ Relative classification weight applied to the no-object category.
1550
+ losses (`List[str]`):
1551
+ List of all the losses to be applied. See `get_loss` for a list of all available losses.
1552
+ """
1553
+
1554
+ def __init__(self, matcher, num_classes, eos_coef, losses):
1555
+ super().__init__()
1556
+ self.matcher = matcher
1557
+ self.num_classes = num_classes
1558
+ self.eos_coef = eos_coef
1559
+ self.losses = losses
1560
+ empty_weight = torch.ones(self.num_classes + 1)
1561
+ empty_weight[-1] = self.eos_coef
1562
+ self.register_buffer("empty_weight", empty_weight)
1563
+
1564
+ # removed logging parameter, which was part of the original implementation
1565
+ def loss_labels(self, outputs, targets, indices, num_boxes):
1566
+ """
1567
+ Classification loss (NLL) targets dicts must contain the key "class_labels" containing a tensor of dim
1568
+ [nb_target_boxes]
1569
+ """
1570
+ if "logits" not in outputs:
1571
+ raise KeyError("No logits were found in the outputs")
1572
+ source_logits = outputs["logits"]
1573
+
1574
+ idx = self._get_source_permutation_idx(indices)
1575
+ target_classes_o = torch.cat([t["class_labels"][J] for t, (_, J) in zip(targets, indices)])
1576
+ target_classes = torch.full(
1577
+ source_logits.shape[:2], self.num_classes, dtype=torch.int64, device=source_logits.device
1578
+ )
1579
+ target_classes[idx] = target_classes_o
1580
+
1581
+ loss_ce = nn.functional.cross_entropy(source_logits.transpose(1, 2), target_classes, self.empty_weight)
1582
+ losses = {"loss_ce": loss_ce}
1583
+
1584
+ return losses
1585
+
1586
+ @torch.no_grad()
1587
+ def loss_cardinality(self, outputs, targets, indices, num_boxes):
1588
+ """
1589
+ Compute the cardinality error, i.e. the absolute error in the number of predicted non-empty boxes.
1590
+
1591
+ This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients.
1592
+ """
1593
+ logits = outputs["logits"]
1594
+ device = logits.device
1595
+ target_lengths = torch.as_tensor([len(v["class_labels"]) for v in targets], device=device)
1596
+ # Count the number of predictions that are NOT "no-object" (which is the last class)
1597
+ card_pred = (logits.argmax(-1) != logits.shape[-1] - 1).sum(1)
1598
+ card_err = nn.functional.l1_loss(card_pred.float(), target_lengths.float())
1599
+ losses = {"cardinality_error": card_err}
1600
+ return losses
1601
+
1602
+ def loss_boxes(self, outputs, targets, indices, num_boxes):
1603
+ """
1604
+ Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss.
1605
+
1606
+ Targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]. The target boxes
1607
+ are expected in format (center_x, center_y, w, h), normalized by the image size.
1608
+ """
1609
+ if "pred_boxes" not in outputs:
1610
+ raise KeyError("No predicted boxes found in outputs")
1611
+ idx = self._get_source_permutation_idx(indices)
1612
+ source_boxes = outputs["pred_boxes"][idx]
1613
+ target_boxes = torch.cat([t["boxes"][i] for t, (_, i) in zip(targets, indices)], dim=0)
1614
+
1615
+ loss_bbox = nn.functional.l1_loss(source_boxes, target_boxes, reduction="none")
1616
+
1617
+ losses = {}
1618
+ losses["loss_bbox"] = loss_bbox.sum() / num_boxes
1619
+
1620
+ loss_giou = 1 - torch.diag(
1621
+ generalized_box_iou(center_to_corners_format(source_boxes), center_to_corners_format(target_boxes))
1622
+ )
1623
+ losses["loss_giou"] = loss_giou.sum() / num_boxes
1624
+ return losses
1625
+
1626
+ def loss_masks(self, outputs, targets, indices, num_boxes):
1627
+ """
1628
+ Compute the losses related to the masks: the focal loss and the dice loss.
1629
+
1630
+ Targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w].
1631
+ """
1632
+ if "pred_masks" not in outputs:
1633
+ raise KeyError("No predicted masks found in outputs")
1634
+
1635
+ source_idx = self._get_source_permutation_idx(indices)
1636
+ target_idx = self._get_target_permutation_idx(indices)
1637
+ source_masks = outputs["pred_masks"]
1638
+ source_masks = source_masks[source_idx]
1639
+ masks = [t["masks"] for t in targets]
1640
+ # TODO use valid to mask invalid areas due to padding in loss
1641
+ target_masks, valid = nested_tensor_from_tensor_list(masks).decompose()
1642
+ target_masks = target_masks.to(source_masks)
1643
+ target_masks = target_masks[target_idx]
1644
+
1645
+ # upsample predictions to the target size
1646
+ source_masks = nn.functional.interpolate(
1647
+ source_masks[:, None], size=target_masks.shape[-2:], mode="bilinear", align_corners=False
1648
+ )
1649
+ source_masks = source_masks[:, 0].flatten(1)
1650
+
1651
+ target_masks = target_masks.flatten(1)
1652
+ target_masks = target_masks.view(source_masks.shape)
1653
+ losses = {
1654
+ "loss_mask": sigmoid_focal_loss(source_masks, target_masks, num_boxes),
1655
+ "loss_dice": dice_loss(source_masks, target_masks, num_boxes),
1656
+ }
1657
+ return losses
1658
+
1659
+ def _get_source_permutation_idx(self, indices):
1660
+ # permute predictions following indices
1661
+ batch_idx = torch.cat([torch.full_like(source, i) for i, (source, _) in enumerate(indices)])
1662
+ source_idx = torch.cat([source for (source, _) in indices])
1663
+ return batch_idx, source_idx
1664
+
1665
+ def _get_target_permutation_idx(self, indices):
1666
+ # permute targets following indices
1667
+ batch_idx = torch.cat([torch.full_like(target, i) for i, (_, target) in enumerate(indices)])
1668
+ target_idx = torch.cat([target for (_, target) in indices])
1669
+ return batch_idx, target_idx
1670
+
1671
+ def get_loss(self, loss, outputs, targets, indices, num_boxes):
1672
+ loss_map = {
1673
+ "labels": self.loss_labels,
1674
+ "cardinality": self.loss_cardinality,
1675
+ "boxes": self.loss_boxes,
1676
+ "masks": self.loss_masks,
1677
+ }
1678
+ if loss not in loss_map:
1679
+ raise ValueError(f"Loss {loss} not supported")
1680
+ return loss_map[loss](outputs, targets, indices, num_boxes)
1681
+
1682
+ def forward(self, outputs, targets):
1683
+ """
1684
+ This performs the loss computation.
1685
+
1686
+ Args:
1687
+ outputs (`dict`, *optional*):
1688
+ Dictionary of tensors, see the output specification of the model for the format.
1689
+ targets (`List[dict]`, *optional*):
1690
+ List of dicts, such that `len(targets) == batch_size`. The expected keys in each dict depends on the
1691
+ losses applied, see each loss' doc.
1692
+ """
1693
+ outputs_without_aux = {k: v for k, v in outputs.items() if k != "auxiliary_outputs"}
1694
+
1695
+ # Retrieve the matching between the outputs of the last layer and the targets
1696
+ indices = self.matcher(outputs_without_aux, targets)
1697
+
1698
+ # Compute the average number of target boxes across all nodes, for normalization purposes
1699
+ num_boxes = sum(len(t["class_labels"]) for t in targets)
1700
+ num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
1701
+ # (Niels): comment out function below, distributed training to be added
1702
+ # if is_dist_avail_and_initialized():
1703
+ # torch.distributed.all_reduce(num_boxes)
1704
+ # (Niels) in original implementation, num_boxes is divided by get_world_size()
1705
+ num_boxes = torch.clamp(num_boxes, min=1).item()
1706
+
1707
+ # Compute all the requested losses
1708
+ losses = {}
1709
+ for loss in self.losses:
1710
+ losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))
1711
+
1712
+ # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
1713
+ if "auxiliary_outputs" in outputs:
1714
+ for i, auxiliary_outputs in enumerate(outputs["auxiliary_outputs"]):
1715
+ indices = self.matcher(auxiliary_outputs, targets)
1716
+ for loss in self.losses:
1717
+ if loss == "masks":
1718
+ # Intermediate masks losses are too costly to compute, we ignore them.
1719
+ continue
1720
+ l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes)
1721
+ l_dict = {k + f"_{i}": v for k, v in l_dict.items()}
1722
+ losses.update(l_dict)
1723
+
1724
+ return losses
1725
+
1726
+
1727
+ # Copied from transformers.models.detr.modeling_detr.DetrMLPPredictionHead with Detr->TableTransformer,detr->table_transformer
1728
+ class TableTransformerMLPPredictionHead(nn.Module):
1729
+ """
1730
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
1731
+ height and width of a bounding box w.r.t. an image.
1732
+
1733
+ Copied from https://github.com/facebookresearch/table_transformer/blob/master/models/table_transformer.py
1734
+
1735
+ """
1736
+
1737
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
1738
+ super().__init__()
1739
+ self.num_layers = num_layers
1740
+ h = [hidden_dim] * (num_layers - 1)
1741
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
1742
+
1743
+ def forward(self, x):
1744
+ for i, layer in enumerate(self.layers):
1745
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
1746
+ return x
1747
+
1748
+
1749
+ # Copied from transformers.models.detr.modeling_detr.DetrHungarianMatcher with Detr->TableTransformer
1750
+ class TableTransformerHungarianMatcher(nn.Module):
1751
+ """
1752
+ This class computes an assignment between the targets and the predictions of the network.
1753
+
1754
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more
1755
+ predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are
1756
+ un-matched (and thus treated as non-objects).
1757
+
1758
+ Args:
1759
+ class_cost:
1760
+ The relative weight of the classification error in the matching cost.
1761
+ bbox_cost:
1762
+ The relative weight of the L1 error of the bounding box coordinates in the matching cost.
1763
+ giou_cost:
1764
+ The relative weight of the giou loss of the bounding box in the matching cost.
1765
+ """
1766
+
1767
+ def __init__(self, class_cost: float = 1, bbox_cost: float = 1, giou_cost: float = 1):
1768
+ super().__init__()
1769
+ requires_backends(self, ["scipy"])
1770
+
1771
+ self.class_cost = class_cost
1772
+ self.bbox_cost = bbox_cost
1773
+ self.giou_cost = giou_cost
1774
+ if class_cost == 0 and bbox_cost == 0 and giou_cost == 0:
1775
+ raise ValueError("All costs of the Matcher can't be 0")
1776
+
1777
+ @torch.no_grad()
1778
+ def forward(self, outputs, targets):
1779
+ """
1780
+ Args:
1781
+ outputs (`dict`):
1782
+ A dictionary that contains at least these entries:
1783
+ * "logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
1784
+ * "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates.
1785
+ targets (`List[dict]`):
1786
+ A list of targets (len(targets) = batch_size), where each target is a dict containing:
1787
+ * "class_labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of
1788
+ ground-truth
1789
+ objects in the target) containing the class labels
1790
+ * "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates.
1791
+
1792
+ Returns:
1793
+ `List[Tuple]`: A list of size `batch_size`, containing tuples of (index_i, index_j) where:
1794
+ - index_i is the indices of the selected predictions (in order)
1795
+ - index_j is the indices of the corresponding selected targets (in order)
1796
+ For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
1797
+ """
1798
+ batch_size, num_queries = outputs["logits"].shape[:2]
1799
+
1800
+ # We flatten to compute the cost matrices in a batch
1801
+ out_prob = outputs["logits"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, num_classes]
1802
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
1803
+
1804
+ # Also concat the target labels and boxes
1805
+ target_ids = torch.cat([v["class_labels"] for v in targets])
1806
+ target_bbox = torch.cat([v["boxes"] for v in targets])
1807
+
1808
+ # Compute the classification cost. Contrary to the loss, we don't use the NLL,
1809
+ # but approximate it in 1 - proba[target class].
1810
+ # The 1 is a constant that doesn't change the matching, it can be ommitted.
1811
+ class_cost = -out_prob[:, target_ids]
1812
+
1813
+ # Compute the L1 cost between boxes
1814
+ bbox_cost = torch.cdist(out_bbox, target_bbox, p=1)
1815
+
1816
+ # Compute the giou cost between boxes
1817
+ giou_cost = -generalized_box_iou(center_to_corners_format(out_bbox), center_to_corners_format(target_bbox))
1818
+
1819
+ # Final cost matrix
1820
+ cost_matrix = self.bbox_cost * bbox_cost + self.class_cost * class_cost + self.giou_cost * giou_cost
1821
+ cost_matrix = cost_matrix.view(batch_size, num_queries, -1).cpu()
1822
+
1823
+ sizes = [len(v["boxes"]) for v in targets]
1824
+ indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))]
1825
+ return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
1826
+
1827
+
1828
+ # Copied from transformers.models.detr.modeling_detr._upcast
1829
+ def _upcast(t: Tensor) -> Tensor:
1830
+ # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type
1831
+ if t.is_floating_point():
1832
+ return t if t.dtype in (torch.float32, torch.float64) else t.float()
1833
+ else:
1834
+ return t if t.dtype in (torch.int32, torch.int64) else t.int()
1835
+
1836
+
1837
+ # Copied from transformers.models.detr.modeling_detr.box_area
1838
+ def box_area(boxes: Tensor) -> Tensor:
1839
+ """
1840
+ Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2) coordinates.
1841
+
1842
+ Args:
1843
+ boxes (`torch.FloatTensor` of shape `(number_of_boxes, 4)`):
1844
+ Boxes for which the area will be computed. They are expected to be in (x1, y1, x2, y2) format with `0 <= x1
1845
+ < x2` and `0 <= y1 < y2`.
1846
+
1847
+ Returns:
1848
+ `torch.FloatTensor`: a tensor containing the area for each box.
1849
+ """
1850
+ boxes = _upcast(boxes)
1851
+ return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
1852
+
1853
+
1854
+ # Copied from transformers.models.detr.modeling_detr.box_iou
1855
+ def box_iou(boxes1, boxes2):
1856
+ area1 = box_area(boxes1)
1857
+ area2 = box_area(boxes2)
1858
+
1859
+ left_top = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
1860
+ right_bottom = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
1861
+
1862
+ width_height = (right_bottom - left_top).clamp(min=0) # [N,M,2]
1863
+ inter = width_height[:, :, 0] * width_height[:, :, 1] # [N,M]
1864
+
1865
+ union = area1[:, None] + area2 - inter
1866
+
1867
+ iou = inter / union
1868
+ return iou, union
1869
+
1870
+
1871
+ # Copied from transformers.models.detr.modeling_detr.generalized_box_iou
1872
+ def generalized_box_iou(boxes1, boxes2):
1873
+ """
1874
+ Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format.
1875
+
1876
+ Returns:
1877
+ `torch.FloatTensor`: a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
1878
+ """
1879
+ # degenerate boxes gives inf / nan results
1880
+ # so do an early check
1881
+ if not (boxes1[:, 2:] >= boxes1[:, :2]).all():
1882
+ raise ValueError(f"boxes1 must be in [x0, y0, x1, y1] (corner) format, but got {boxes1}")
1883
+ if not (boxes2[:, 2:] >= boxes2[:, :2]).all():
1884
+ raise ValueError(f"boxes2 must be in [x0, y0, x1, y1] (corner) format, but got {boxes2}")
1885
+ iou, union = box_iou(boxes1, boxes2)
1886
+
1887
+ top_left = torch.min(boxes1[:, None, :2], boxes2[:, :2])
1888
+ bottom_right = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
1889
+
1890
+ width_height = (bottom_right - top_left).clamp(min=0) # [N,M,2]
1891
+ area = width_height[:, :, 0] * width_height[:, :, 1]
1892
+
1893
+ return iou - (area - union) / area
1894
+
1895
+
1896
+ # Copied from transformers.models.detr.modeling_detr._max_by_axis
1897
+ def _max_by_axis(the_list):
1898
+ # type: (List[List[int]]) -> List[int]
1899
+ maxes = the_list[0]
1900
+ for sublist in the_list[1:]:
1901
+ for index, item in enumerate(sublist):
1902
+ maxes[index] = max(maxes[index], item)
1903
+ return maxes
1904
+
1905
+
1906
+ # Copied from transformers.models.detr.modeling_detr.NestedTensor
1907
+ class NestedTensor(object):
1908
+ def __init__(self, tensors, mask: Optional[Tensor]):
1909
+ self.tensors = tensors
1910
+ self.mask = mask
1911
+
1912
+ def to(self, device):
1913
+ cast_tensor = self.tensors.to(device)
1914
+ mask = self.mask
1915
+ if mask is not None:
1916
+ cast_mask = mask.to(device)
1917
+ else:
1918
+ cast_mask = None
1919
+ return NestedTensor(cast_tensor, cast_mask)
1920
+
1921
+ def decompose(self):
1922
+ return self.tensors, self.mask
1923
+
1924
+ def __repr__(self):
1925
+ return str(self.tensors)
1926
+
1927
+
1928
+ # Copied from transformers.models.detr.modeling_detr.nested_tensor_from_tensor_list
1929
+ def nested_tensor_from_tensor_list(tensor_list: List[Tensor]):
1930
+ if tensor_list[0].ndim == 3:
1931
+ max_size = _max_by_axis([list(img.shape) for img in tensor_list])
1932
+ batch_shape = [len(tensor_list)] + max_size
1933
+ batch_size, num_channels, height, width = batch_shape
1934
+ dtype = tensor_list[0].dtype
1935
+ device = tensor_list[0].device
1936
+ tensor = torch.zeros(batch_shape, dtype=dtype, device=device)
1937
+ mask = torch.ones((batch_size, height, width), dtype=torch.bool, device=device)
1938
+ for img, pad_img, m in zip(tensor_list, tensor, mask):
1939
+ pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
1940
+ m[: img.shape[1], : img.shape[2]] = False
1941
+ else:
1942
+ raise ValueError("Only 3-dimensional tensors are supported")
1943
+ return NestedTensor(tensor, mask)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tapas/__init__.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 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
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
18
+
19
+
20
+ _import_structure = {
21
+ "configuration_tapas": ["TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP", "TapasConfig"],
22
+ "tokenization_tapas": ["TapasTokenizer"],
23
+ }
24
+
25
+ try:
26
+ if not is_torch_available():
27
+ raise OptionalDependencyNotAvailable()
28
+ except OptionalDependencyNotAvailable:
29
+ pass
30
+ else:
31
+ _import_structure["modeling_tapas"] = [
32
+ "TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST",
33
+ "TapasForMaskedLM",
34
+ "TapasForQuestionAnswering",
35
+ "TapasForSequenceClassification",
36
+ "TapasModel",
37
+ "TapasPreTrainedModel",
38
+ "load_tf_weights_in_tapas",
39
+ ]
40
+ try:
41
+ if not is_tf_available():
42
+ raise OptionalDependencyNotAvailable()
43
+ except OptionalDependencyNotAvailable:
44
+ pass
45
+ else:
46
+ _import_structure["modeling_tf_tapas"] = [
47
+ "TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST",
48
+ "TFTapasForMaskedLM",
49
+ "TFTapasForQuestionAnswering",
50
+ "TFTapasForSequenceClassification",
51
+ "TFTapasModel",
52
+ "TFTapasPreTrainedModel",
53
+ ]
54
+
55
+
56
+ if TYPE_CHECKING:
57
+ from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig
58
+ from .tokenization_tapas import TapasTokenizer
59
+
60
+ try:
61
+ if not is_torch_available():
62
+ raise OptionalDependencyNotAvailable()
63
+ except OptionalDependencyNotAvailable:
64
+ pass
65
+ else:
66
+ from .modeling_tapas import (
67
+ TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,
68
+ TapasForMaskedLM,
69
+ TapasForQuestionAnswering,
70
+ TapasForSequenceClassification,
71
+ TapasModel,
72
+ TapasPreTrainedModel,
73
+ load_tf_weights_in_tapas,
74
+ )
75
+
76
+ try:
77
+ if not is_tf_available():
78
+ raise OptionalDependencyNotAvailable()
79
+ except OptionalDependencyNotAvailable:
80
+ pass
81
+ else:
82
+ from .modeling_tf_tapas import (
83
+ TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,
84
+ TFTapasForMaskedLM,
85
+ TFTapasForQuestionAnswering,
86
+ TFTapasForSequenceClassification,
87
+ TFTapasModel,
88
+ TFTapasPreTrainedModel,
89
+ )
90
+
91
+
92
+ else:
93
+ import sys
94
+
95
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tapas/tokenization_tapas.py ADDED
The diff for this file is too large to render. See raw diff
 
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tapex/tokenization_tapex.py ADDED
@@ -0,0 +1,1486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft Research 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
+ """Tokenization classes for TAPEX."""
16
+
17
+ import json
18
+ import os
19
+ import random
20
+ from functools import lru_cache
21
+ from typing import Dict, List, Optional, Tuple, Union
22
+
23
+ import regex as re
24
+
25
+ from ...file_utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available
26
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
27
+ from ...tokenization_utils_base import ENCODE_KWARGS_DOCSTRING, BatchEncoding, TextInput, TruncationStrategy
28
+ from ...utils import logging
29
+
30
+
31
+ if is_pandas_available():
32
+ import pandas as pd
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
38
+
39
+ PRETRAINED_VOCAB_FILES_MAP = {
40
+ "vocab_file": {
41
+ "microsoft/tapex-base": "https://huggingface.co/microsoft/tapex-base/resolve/main/vocab.json",
42
+ },
43
+ "merges_file": {
44
+ "microsoft/tapex-base": "https://huggingface.co/microsoft/tapex-base/resolve/main/merges.txt",
45
+ },
46
+ }
47
+
48
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
49
+ "microsoft/tapex-base": 512,
50
+ }
51
+
52
+ PRETRAINED_INIT_CONFIGURATION = {
53
+ "microsoft/tapex-base": {"do_lower_case": True},
54
+ }
55
+
56
+
57
+ class TapexTruncationStrategy(ExplicitEnum):
58
+ """
59
+ Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
60
+ """
61
+
62
+ DROP_ROWS_TO_FIT = "drop_rows_to_fit"
63
+
64
+
65
+ TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
66
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
67
+ Whether or not to encode the sequences with the special tokens relative to their model.
68
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
69
+ Activates and controls padding. Accepts the following values:
70
+
71
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
72
+ sequence if provided).
73
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
74
+ acceptable input length for the model if that argument is not provided.
75
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
76
+ lengths).
77
+ truncation (`bool`, `str`, [`TapexTruncationStrategy`] or [`~tokenization_utils_base.TruncationStrategy`],
78
+ *optional*, defaults to `False`):
79
+
80
+ Activates and controls truncation. Accepts the following values:
81
+
82
+ - `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` or to the
83
+ maximum acceptable input length for the model if that argument is not provided. This will truncate
84
+ row by row, removing rows from the table.
85
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
86
+ to the maximum acceptable input length for the model if that argument is not provided. This will
87
+ truncate token by token, removing a token from the longest sequence in the pair if a pair of
88
+ sequences (or a batch of pairs) is provided.
89
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
90
+ maximum acceptable input length for the model if that argument is not provided. This will only
91
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
92
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
93
+ maximum acceptable input length for the model if that argument is not provided. This will only
94
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
95
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
96
+ greater than the model maximum admissible input size).
97
+ max_length (`int`, *optional*):
98
+ Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
99
+ `None`, this will use the predefined model maximum length if a maximum length is required by one of the
100
+ truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
101
+ truncation/padding to a maximum length will be deactivated.
102
+ stride (`int`, *optional*, defaults to 0):
103
+ If set to a number along with `max_length`, the overflowing tokens returned when
104
+ `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
105
+ returned to provide some overlap between truncated and overflowing sequences. The value of this
106
+ argument defines the number of overlapping tokens.
107
+ pad_to_multiple_of (`int`, *optional*):
108
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
109
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
110
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
111
+ If set, will return tensors instead of list of python integers. Acceptable values are:
112
+
113
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
114
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
115
+ - `'np'`: Return Numpy `np.ndarray` objects.
116
+ """
117
+
118
+
119
+ @lru_cache()
120
+ def bytes_to_unicode():
121
+ """
122
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
123
+ characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
124
+ of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
125
+ you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
126
+ vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
127
+ """
128
+ bs = (
129
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
130
+ )
131
+ cs = bs[:]
132
+ n = 0
133
+ for b in range(2**8):
134
+ if b not in bs:
135
+ bs.append(b)
136
+ cs.append(2**8 + n)
137
+ n += 1
138
+ cs = [chr(n) for n in cs]
139
+ return dict(zip(bs, cs))
140
+
141
+
142
+ def get_pairs(word):
143
+ """
144
+ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
145
+ strings).
146
+ """
147
+ pairs = set()
148
+ prev_char = word[0]
149
+ for char in word[1:]:
150
+ pairs.add((prev_char, char))
151
+ prev_char = char
152
+ return pairs
153
+
154
+
155
+ class IndexedRowTableLinearize:
156
+ """
157
+ FORMAT: col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
158
+ """
159
+
160
+ def process_table(self, table_content: Dict):
161
+ """
162
+ Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
163
+ """
164
+ assert "header" in table_content and "rows" in table_content, self.PROMPT_MESSAGE
165
+ # process header
166
+ table_str = self.process_header(table_content["header"]) + " "
167
+ # process rows
168
+ for i, row_example in enumerate(table_content["rows"]):
169
+ # NOTE: the row should start from row 1 instead of 0
170
+ table_str += self.process_row(row_example, row_index=i + 1) + " "
171
+ return table_str.strip()
172
+
173
+ def process_header(self, headers: List):
174
+ """
175
+ Given a list of headers, TableLinearize aims at converting it into a flatten sequence with special symbols.
176
+ """
177
+ return "col : " + " | ".join(headers)
178
+
179
+ def process_row(self, row: List, row_index: int):
180
+ """
181
+ Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
182
+ """
183
+ row_str = ""
184
+ row_cell_values = []
185
+ for cell_value in row:
186
+ if isinstance(cell_value, int):
187
+ row_cell_values.append(str(cell_value))
188
+ else:
189
+ row_cell_values.append(cell_value)
190
+ row_str += " | ".join(row_cell_values)
191
+ return "row " + str(row_index) + " : " + row_str
192
+
193
+
194
+ class TapexTokenizer(PreTrainedTokenizer):
195
+ r"""
196
+ Construct a TAPEX tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).
197
+
198
+ This tokenizer can be used to flatten one or more table(s) and concatenate them with one or more related sentences
199
+ to be used by TAPEX models. The format that the TAPEX tokenizer creates is the following:
200
+
201
+ sentence col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
202
+
203
+ The tokenizer supports a single table + single query, a single table and multiple queries (in which case the table
204
+ will be duplicated for every query), a single query and multiple tables (in which case the query will be duplicated
205
+ for every table), and multiple tables and queries. In other words, you can provide a batch of tables + questions to
206
+ the tokenizer for instance to prepare them for the model.
207
+
208
+ Tokenization itself is based on the BPE algorithm. It is identical to the one used by BART, RoBERTa and GPT-2.
209
+
210
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
211
+ this superclass for more information regarding those methods.
212
+
213
+ Args:
214
+ vocab_file (`str`):
215
+ Path to the vocabulary file.
216
+ merges_file (`str`):
217
+ Path to the merges file.
218
+ do_lower_case (`bool`, *optional*, defaults to `True`):
219
+ Whether or not to lowercase the input when tokenizing.
220
+ errors (`str`, *optional*, defaults to `"replace"`):
221
+ Paradigm to follow when decoding bytes to UTF-8. See
222
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
223
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
224
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
225
+
226
+ <Tip>
227
+
228
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
229
+ sequence. The token used is the `cls_token`.
230
+
231
+ </Tip>
232
+
233
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
234
+ The end of sequence token.
235
+
236
+ <Tip>
237
+
238
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
239
+ The token used is the `sep_token`.
240
+
241
+ </Tip>
242
+
243
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
244
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
245
+ sequence classification or for a text and a question for question answering. It is also used as the last
246
+ token of a sequence built with special tokens.
247
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
248
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
249
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
250
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
251
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
252
+ token instead.
253
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
254
+ The token used for padding, for example when batching sequences of different lengths.
255
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
256
+ The token used for masking values. This is the token used when training this model with masked language
257
+ modeling. This is the token which the model will try to predict.
258
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
259
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
260
+ other word. (BART tokenizer detect beginning of words by the preceding space).
261
+ max_cell_length (`int`, *optional*, defaults to 15):
262
+ Maximum number of characters per cell when linearizing a table. If this number is exceeded, truncation
263
+ takes place.
264
+ """
265
+
266
+ vocab_files_names = VOCAB_FILES_NAMES
267
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
268
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
269
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
270
+ model_input_names = ["input_ids", "attention_mask"]
271
+
272
+ def __init__(
273
+ self,
274
+ vocab_file,
275
+ merges_file,
276
+ do_lower_case=True,
277
+ errors="replace",
278
+ bos_token="<s>",
279
+ eos_token="</s>",
280
+ sep_token="</s>",
281
+ cls_token="<s>",
282
+ unk_token="<unk>",
283
+ pad_token="<pad>",
284
+ mask_token="<mask>",
285
+ add_prefix_space=False,
286
+ max_cell_length=15,
287
+ **kwargs,
288
+ ):
289
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
290
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
291
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
292
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
293
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
294
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
295
+
296
+ # Mask token behave like a normal word, i.e. include the space before it
297
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
298
+
299
+ super().__init__(
300
+ vocab_file=vocab_file,
301
+ merges_file=merges_file,
302
+ do_lower_case=do_lower_case,
303
+ errors=errors,
304
+ bos_token=bos_token,
305
+ eos_token=eos_token,
306
+ unk_token=unk_token,
307
+ sep_token=sep_token,
308
+ cls_token=cls_token,
309
+ pad_token=pad_token,
310
+ mask_token=mask_token,
311
+ add_prefix_space=add_prefix_space,
312
+ max_cell_length=max_cell_length,
313
+ **kwargs,
314
+ )
315
+
316
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
317
+ self.encoder = json.load(vocab_handle)
318
+ self.decoder = {v: k for k, v in self.encoder.items()}
319
+ self.errors = errors # how to handle errors in decoding
320
+ self.byte_encoder = bytes_to_unicode()
321
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
322
+ with open(merges_file, encoding="utf-8") as merges_handle:
323
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
324
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
325
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
326
+ self.cache = {}
327
+ self.add_prefix_space = add_prefix_space
328
+ self.do_lower_case = do_lower_case
329
+
330
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
331
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
332
+
333
+ # additional properties
334
+ self.max_cell_length = max_cell_length
335
+ self.table_linearize = IndexedRowTableLinearize()
336
+
337
+ def build_inputs_with_special_tokens(
338
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
339
+ ) -> List[int]:
340
+ """
341
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
342
+ adding special tokens. A TAPEX sequence has the following format:
343
+ - single sequence: `<s> X </s>`
344
+ - pair of sequences: `<s> A </s></s> B </s>`
345
+
346
+ Args:
347
+ token_ids_0 (`List[int]`):
348
+ List of IDs to which the special tokens will be added.
349
+ token_ids_1 (`List[int]`, *optional*):
350
+ Optional second list of IDs for sequence pairs.
351
+ Returns:
352
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
353
+ """
354
+ if token_ids_1 is None:
355
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
356
+ cls = [self.cls_token_id]
357
+ sep = [self.sep_token_id]
358
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
359
+
360
+ def get_special_tokens_mask(
361
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
362
+ ) -> List[int]:
363
+ """
364
+ Args:
365
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
366
+ special tokens using the tokenizer `prepare_for_model` method.
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
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
372
+ Whether or not the token list is already formatted with special tokens for the model.
373
+ Returns:
374
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
375
+ """
376
+ if already_has_special_tokens:
377
+ return super().get_special_tokens_mask(
378
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
379
+ )
380
+
381
+ if token_ids_1 is None:
382
+ return [1] + ([0] * len(token_ids_0)) + [1]
383
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
384
+
385
+ def create_token_type_ids_from_sequences(
386
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
387
+ ) -> List[int]:
388
+ """
389
+ Args:
390
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
391
+ make use of token type ids, therefore a list of zeros is returned.
392
+ token_ids_0 (`List[int]`):
393
+ List of IDs.
394
+ token_ids_1 (`List[int]`, *optional*):
395
+ Optional second list of IDs for sequence pairs.
396
+ Returns:
397
+ `List[int]`: List of zeros.
398
+ """
399
+ sep = [self.sep_token_id]
400
+ cls = [self.cls_token_id]
401
+
402
+ if token_ids_1 is None:
403
+ return len(cls + token_ids_0 + sep) * [0]
404
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
405
+
406
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
407
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
408
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
409
+ text = " " + text
410
+ return (text, kwargs)
411
+
412
+ @property
413
+ def vocab_size(self):
414
+ return len(self.encoder)
415
+
416
+ def get_vocab(self):
417
+ return dict(self.encoder, **self.added_tokens_encoder)
418
+
419
+ def bpe(self, token):
420
+ if token in self.cache:
421
+ return self.cache[token]
422
+ word = tuple(token)
423
+ pairs = get_pairs(word)
424
+
425
+ if not pairs:
426
+ return token
427
+
428
+ while True:
429
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
430
+ if bigram not in self.bpe_ranks:
431
+ break
432
+ first, second = bigram
433
+ new_word = []
434
+ i = 0
435
+ while i < len(word):
436
+ try:
437
+ j = word.index(first, i)
438
+ except ValueError:
439
+ new_word.extend(word[i:])
440
+ break
441
+ else:
442
+ new_word.extend(word[i:j])
443
+ i = j
444
+
445
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
446
+ new_word.append(first + second)
447
+ i += 2
448
+ else:
449
+ new_word.append(word[i])
450
+ i += 1
451
+ new_word = tuple(new_word)
452
+ word = new_word
453
+ if len(word) == 1:
454
+ break
455
+ else:
456
+ pairs = get_pairs(word)
457
+ word = " ".join(word)
458
+ self.cache[token] = word
459
+ return word
460
+
461
+ def _tokenize(self, text):
462
+ """Tokenize a string."""
463
+ bpe_tokens = []
464
+ for token in re.findall(self.pat, text):
465
+ token = "".join(
466
+ self.byte_encoder[b] for b in token.encode("utf-8")
467
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
468
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
469
+ return bpe_tokens
470
+
471
+ def _convert_token_to_id(self, token):
472
+ """Converts a token (str) in an id using the vocab."""
473
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
474
+
475
+ def _convert_id_to_token(self, index):
476
+ """Converts an index (integer) in a token (str) using the vocab."""
477
+ return self.decoder.get(index)
478
+
479
+ def convert_tokens_to_string(self, tokens):
480
+ """Converts a sequence of tokens (string) in a single string."""
481
+ text = "".join(tokens)
482
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
483
+ return text
484
+
485
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
486
+ if not os.path.isdir(save_directory):
487
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
488
+ return
489
+ vocab_file = os.path.join(
490
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
491
+ )
492
+ merge_file = os.path.join(
493
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
494
+ )
495
+
496
+ with open(vocab_file, "w", encoding="utf-8") as f:
497
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
498
+
499
+ index = 0
500
+ with open(merge_file, "w", encoding="utf-8") as writer:
501
+ writer.write("#version: 0.2\n")
502
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
503
+ if index != token_index:
504
+ logger.warning(
505
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
506
+ " Please check that the tokenizer is not corrupted!"
507
+ )
508
+ index = token_index
509
+ writer.write(" ".join(bpe_tokens) + "\n")
510
+ index += 1
511
+
512
+ return vocab_file, merge_file
513
+
514
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
515
+ def __call__(
516
+ self,
517
+ table: Union["pd.DataFrame", List["pd.DataFrame"]] = None,
518
+ query: Optional[Union[TextInput, List[TextInput]]] = None,
519
+ answer: Union[str, List[str]] = None,
520
+ add_special_tokens: bool = True,
521
+ padding: Union[bool, str, PaddingStrategy] = False,
522
+ truncation: Union[bool, str, TruncationStrategy] = None,
523
+ max_length: Optional[int] = None,
524
+ stride: int = 0,
525
+ pad_to_multiple_of: Optional[int] = None,
526
+ return_tensors: Optional[Union[str, TensorType]] = None,
527
+ return_token_type_ids: Optional[bool] = None,
528
+ return_attention_mask: Optional[bool] = None,
529
+ return_overflowing_tokens: bool = False,
530
+ return_special_tokens_mask: bool = False,
531
+ return_offsets_mapping: bool = False,
532
+ return_length: bool = False,
533
+ verbose: bool = True,
534
+ **kwargs,
535
+ ) -> BatchEncoding:
536
+ """
537
+ Main method to tokenize and prepare for the model one or several table-sequence pair(s).
538
+
539
+ Args:
540
+ table (`pd.DataFrame`, `List[pd.DataFrame]`):
541
+ Table(s) containing tabular data.
542
+ query (`str` or `List[str]`, *optional*):
543
+ Sentence or batch of sentences related to one or more table(s) to be encoded. Note that the number of
544
+ sentences must match the number of tables.
545
+ answer (`str` or `List[str]`, *optional*):
546
+ Optionally, the corresponding answer to the questions as supervision.
547
+ """
548
+
549
+ if table is not None:
550
+ return self.source_call_func(
551
+ table=table,
552
+ query=query,
553
+ answer=answer,
554
+ add_special_tokens=add_special_tokens,
555
+ padding=padding,
556
+ truncation=truncation,
557
+ max_length=max_length,
558
+ stride=stride,
559
+ pad_to_multiple_of=pad_to_multiple_of,
560
+ return_tensors=return_tensors,
561
+ return_token_type_ids=return_token_type_ids,
562
+ return_attention_mask=return_attention_mask,
563
+ return_overflowing_tokens=return_overflowing_tokens,
564
+ return_special_tokens_mask=return_special_tokens_mask,
565
+ return_offsets_mapping=return_offsets_mapping,
566
+ return_length=return_length,
567
+ verbose=verbose,
568
+ **kwargs,
569
+ )
570
+ elif answer is not None:
571
+ return self.target_call_func(
572
+ answer=answer,
573
+ add_special_tokens=add_special_tokens,
574
+ padding=padding,
575
+ truncation=truncation,
576
+ max_length=max_length,
577
+ stride=stride,
578
+ pad_to_multiple_of=pad_to_multiple_of,
579
+ return_tensors=return_tensors,
580
+ return_token_type_ids=return_token_type_ids,
581
+ return_attention_mask=return_attention_mask,
582
+ return_overflowing_tokens=return_overflowing_tokens,
583
+ return_special_tokens_mask=return_special_tokens_mask,
584
+ return_offsets_mapping=return_offsets_mapping,
585
+ return_length=return_length,
586
+ verbose=verbose,
587
+ **kwargs,
588
+ )
589
+ else:
590
+ raise ValueError("You need to provide either a `table` or an `answer`.")
591
+
592
+ def source_call_func(
593
+ self,
594
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
595
+ query: Optional[Union[TextInput, List[TextInput]]] = None,
596
+ answer: Union[str, List[str]] = None,
597
+ add_special_tokens: bool = True,
598
+ padding: Union[bool, str, PaddingStrategy] = False,
599
+ truncation: Union[bool, str, TruncationStrategy] = None,
600
+ max_length: Optional[int] = None,
601
+ stride: int = 0,
602
+ pad_to_multiple_of: Optional[int] = None,
603
+ return_tensors: Optional[Union[str, TensorType]] = None,
604
+ return_token_type_ids: Optional[bool] = None,
605
+ return_attention_mask: Optional[bool] = None,
606
+ return_overflowing_tokens: bool = False,
607
+ return_special_tokens_mask: bool = False,
608
+ return_offsets_mapping: bool = False,
609
+ return_length: bool = False,
610
+ verbose: bool = True,
611
+ **kwargs,
612
+ ) -> BatchEncoding:
613
+ # Input type checking for clearer error
614
+ valid_table = False
615
+ valid_query = False
616
+
617
+ # Check that table have a valid type
618
+ if isinstance(table, pd.DataFrame):
619
+ valid_table = True
620
+ elif isinstance(table, (list, tuple)) and isinstance(table[0], pd.DataFrame):
621
+ valid_table = True
622
+
623
+ # Check that query have a valid type
624
+ if query is None or isinstance(query, str):
625
+ valid_query = True
626
+ elif isinstance(query, (list, tuple)):
627
+ if len(query) == 0 or isinstance(query[0], str):
628
+ valid_query = True
629
+
630
+ if not valid_table:
631
+ raise ValueError(
632
+ "table input must of type `pd.DataFrame` (single example), `List[pd.DataFrame]` (batch of examples). "
633
+ )
634
+ if not valid_query:
635
+ raise ValueError("query input must of type `str` (single example), `List[str]` (batch of examples). ")
636
+ is_batched = isinstance(table, (list, tuple)) or isinstance(query, (list, tuple))
637
+
638
+ if is_batched:
639
+ return self.batch_encode_plus(
640
+ table=table,
641
+ query=query,
642
+ answer=answer,
643
+ add_special_tokens=add_special_tokens,
644
+ padding=padding,
645
+ truncation=truncation,
646
+ max_length=max_length,
647
+ pad_to_multiple_of=pad_to_multiple_of,
648
+ return_tensors=return_tensors,
649
+ return_token_type_ids=return_token_type_ids,
650
+ return_attention_mask=return_attention_mask,
651
+ return_overflowing_tokens=return_overflowing_tokens,
652
+ return_special_tokens_mask=return_special_tokens_mask,
653
+ return_offsets_mapping=return_offsets_mapping,
654
+ return_length=return_length,
655
+ verbose=verbose,
656
+ **kwargs,
657
+ )
658
+ else:
659
+ return self.encode_plus(
660
+ table=table,
661
+ query=query,
662
+ answer=answer,
663
+ add_special_tokens=add_special_tokens,
664
+ padding=padding,
665
+ truncation=truncation,
666
+ max_length=max_length,
667
+ pad_to_multiple_of=pad_to_multiple_of,
668
+ return_tensors=return_tensors,
669
+ return_token_type_ids=return_token_type_ids,
670
+ return_attention_mask=return_attention_mask,
671
+ return_overflowing_tokens=return_overflowing_tokens,
672
+ return_special_tokens_mask=return_special_tokens_mask,
673
+ return_offsets_mapping=return_offsets_mapping,
674
+ return_length=return_length,
675
+ verbose=verbose,
676
+ **kwargs,
677
+ )
678
+
679
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
680
+ def batch_encode_plus(
681
+ self,
682
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
683
+ query: Optional[List[TextInput]] = None,
684
+ answer: List[str] = None,
685
+ add_special_tokens: bool = True,
686
+ padding: Union[bool, str, PaddingStrategy] = False,
687
+ truncation: Union[bool, str] = None,
688
+ max_length: Optional[int] = None,
689
+ pad_to_multiple_of: Optional[int] = None,
690
+ return_tensors: Optional[Union[str, TensorType]] = None,
691
+ return_token_type_ids: Optional[bool] = None,
692
+ return_attention_mask: Optional[bool] = None,
693
+ return_overflowing_tokens: bool = False,
694
+ return_special_tokens_mask: bool = False,
695
+ return_offsets_mapping: bool = False,
696
+ return_length: bool = False,
697
+ verbose: bool = True,
698
+ **kwargs,
699
+ ) -> BatchEncoding:
700
+ """
701
+ <Tip warning={true}>
702
+
703
+ This method is deprecated, `__call__` should be used instead.
704
+
705
+ </Tip>
706
+ """
707
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
708
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
709
+ padding=padding,
710
+ truncation=truncation,
711
+ max_length=max_length,
712
+ pad_to_multiple_of=pad_to_multiple_of,
713
+ verbose=verbose,
714
+ **kwargs,
715
+ )
716
+
717
+ return self._batch_encode_plus(
718
+ table=table,
719
+ query=query,
720
+ answer=answer,
721
+ add_special_tokens=add_special_tokens,
722
+ padding_strategy=padding_strategy,
723
+ truncation_strategy=truncation_strategy,
724
+ max_length=max_length,
725
+ pad_to_multiple_of=pad_to_multiple_of,
726
+ return_tensors=return_tensors,
727
+ return_token_type_ids=return_token_type_ids,
728
+ return_attention_mask=return_attention_mask,
729
+ return_overflowing_tokens=return_overflowing_tokens,
730
+ return_special_tokens_mask=return_special_tokens_mask,
731
+ return_offsets_mapping=return_offsets_mapping,
732
+ return_length=return_length,
733
+ verbose=verbose,
734
+ **kwargs,
735
+ )
736
+
737
+ def _batch_encode_plus(
738
+ self,
739
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
740
+ query: Optional[List[TextInput]] = None,
741
+ answer: Optional[List[str]] = None,
742
+ add_special_tokens: bool = True,
743
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
744
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
745
+ max_length: Optional[int] = None,
746
+ stride: int = 0,
747
+ pad_to_multiple_of: Optional[int] = None,
748
+ return_tensors: Optional[Union[str, TensorType]] = None,
749
+ return_token_type_ids: Optional[bool] = None,
750
+ return_attention_mask: Optional[bool] = None,
751
+ return_overflowing_tokens: bool = False,
752
+ return_special_tokens_mask: bool = False,
753
+ return_offsets_mapping: bool = False,
754
+ return_length: bool = False,
755
+ verbose: bool = True,
756
+ **kwargs,
757
+ ) -> BatchEncoding:
758
+ if return_offsets_mapping:
759
+ raise NotImplementedError(
760
+ "return_offset_mapping is not available when using Python tokenizers. "
761
+ "To use this feature, change your tokenizer to one deriving from "
762
+ "transformers.PreTrainedTokenizerFast."
763
+ )
764
+
765
+ if isinstance(table, pd.DataFrame) and isinstance(query, (list, tuple)):
766
+ # single table, many queries case
767
+ # duplicate table for every query
768
+ table = [table] * len(query)
769
+ if isinstance(table, (list, tuple)) and isinstance(query, str):
770
+ # many tables, single query case
771
+ # duplicate query for every table
772
+ query = [query] * len(table)
773
+
774
+ batch_outputs = self._batch_prepare_for_model(
775
+ table=table,
776
+ query=query,
777
+ answer=answer,
778
+ add_special_tokens=add_special_tokens,
779
+ padding_strategy=padding_strategy,
780
+ truncation_strategy=truncation_strategy,
781
+ max_length=max_length,
782
+ stride=stride,
783
+ pad_to_multiple_of=pad_to_multiple_of,
784
+ return_attention_mask=return_attention_mask,
785
+ return_token_type_ids=return_token_type_ids,
786
+ return_overflowing_tokens=return_overflowing_tokens,
787
+ return_special_tokens_mask=return_special_tokens_mask,
788
+ return_length=return_length,
789
+ return_tensors=return_tensors,
790
+ verbose=verbose,
791
+ )
792
+
793
+ return BatchEncoding(batch_outputs)
794
+
795
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
796
+ def _batch_prepare_for_model(
797
+ self,
798
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
799
+ query: Optional[Union[TextInput, List[TextInput]]] = None,
800
+ answer: Optional[Union[str, List[str]]] = None,
801
+ add_special_tokens: bool = True,
802
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
803
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
804
+ max_length: Optional[int] = None,
805
+ stride: int = 0,
806
+ pad_to_multiple_of: Optional[int] = None,
807
+ return_tensors: Optional[str] = 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_length: bool = False,
813
+ verbose: bool = True,
814
+ ) -> BatchEncoding:
815
+ """
816
+ This method adds special tokens, truncates sequences if overflowing while taking into account the special
817
+ tokens and manages a moving window (with user defined stride) for overflowing tokens.
818
+ """
819
+ batch_outputs = {}
820
+ if answer is None:
821
+ answer = [None] * len(table)
822
+ for _table, _query, _answer in zip(table, query, answer):
823
+ text = self.prepare_table_query(
824
+ _table, _query, _answer, truncation_strategy=truncation_strategy, max_length=max_length
825
+ )
826
+
827
+ if self.do_lower_case:
828
+ text = text.lower()
829
+
830
+ tokens = self.tokenize(text)
831
+ outputs = self.prepare_for_model(
832
+ ids=self.convert_tokens_to_ids(tokens),
833
+ add_special_tokens=add_special_tokens,
834
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
835
+ truncation=truncation_strategy.value,
836
+ max_length=max_length,
837
+ stride=stride,
838
+ pad_to_multiple_of=None, # we pad in batch afterwards
839
+ return_attention_mask=False, # we pad in batch afterwards
840
+ return_token_type_ids=return_token_type_ids,
841
+ return_overflowing_tokens=return_overflowing_tokens,
842
+ return_special_tokens_mask=return_special_tokens_mask,
843
+ return_length=return_length,
844
+ return_tensors=None, # We convert the whole batch to tensors at the end
845
+ prepend_batch_axis=False,
846
+ verbose=verbose,
847
+ )
848
+
849
+ for key, value in outputs.items():
850
+ if key not in batch_outputs:
851
+ batch_outputs[key] = []
852
+ batch_outputs[key].append(value)
853
+
854
+ batch_outputs = self.pad(
855
+ batch_outputs,
856
+ padding=padding_strategy.value,
857
+ max_length=max_length,
858
+ pad_to_multiple_of=pad_to_multiple_of,
859
+ return_attention_mask=return_attention_mask,
860
+ )
861
+
862
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
863
+
864
+ return batch_outputs
865
+
866
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
867
+ def encode(
868
+ self,
869
+ table: "pd.DataFrame",
870
+ query: Optional[TextInput] = None,
871
+ answer: Optional[str] = None,
872
+ add_special_tokens: bool = True,
873
+ padding: Union[bool, str, PaddingStrategy] = False,
874
+ truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
875
+ max_length: Optional[int] = None,
876
+ return_tensors: Optional[Union[str, TensorType]] = None,
877
+ **kwargs,
878
+ ) -> List[int]:
879
+ """
880
+ Prepare a table, a string and possible answer for the model. This method does not return token type IDs,
881
+ attention masks, etc. which are necessary for the model to work correctly. Use this method if you want to build
882
+ your processing on your own, otherwise refer to `__call__`.
883
+ """
884
+ encoded_inputs = self.encode_plus(
885
+ table,
886
+ query=query,
887
+ answer=answer,
888
+ add_special_tokens=add_special_tokens,
889
+ padding=padding,
890
+ truncation=truncation,
891
+ max_length=max_length,
892
+ return_tensors=return_tensors,
893
+ **kwargs,
894
+ )
895
+
896
+ return encoded_inputs["input_ids"]
897
+
898
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
899
+ def encode_plus(
900
+ self,
901
+ table: "pd.DataFrame",
902
+ query: Optional[TextInput] = None,
903
+ answer: Optional[str] = None,
904
+ add_special_tokens: bool = True,
905
+ padding: Union[bool, str, PaddingStrategy] = False,
906
+ truncation: Union[bool, str] = None,
907
+ max_length: Optional[int] = None,
908
+ pad_to_multiple_of: Optional[int] = None,
909
+ return_tensors: Optional[Union[str, TensorType]] = None,
910
+ return_token_type_ids: Optional[bool] = None,
911
+ return_attention_mask: Optional[bool] = None,
912
+ return_special_tokens_mask: bool = False,
913
+ return_offsets_mapping: bool = False,
914
+ return_length: bool = False,
915
+ verbose: bool = True,
916
+ **kwargs,
917
+ ) -> BatchEncoding:
918
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
919
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
920
+ padding=padding,
921
+ truncation=truncation,
922
+ max_length=max_length,
923
+ pad_to_multiple_of=pad_to_multiple_of,
924
+ verbose=verbose,
925
+ **kwargs,
926
+ )
927
+
928
+ return self._encode_plus(
929
+ table=table,
930
+ query=query,
931
+ answer=answer,
932
+ add_special_tokens=add_special_tokens,
933
+ padding_strategy=padding_strategy,
934
+ truncation_strategy=truncation_strategy,
935
+ max_length=max_length,
936
+ pad_to_multiple_of=pad_to_multiple_of,
937
+ return_tensors=return_tensors,
938
+ return_token_type_ids=return_token_type_ids,
939
+ return_attention_mask=return_attention_mask,
940
+ return_special_tokens_mask=return_special_tokens_mask,
941
+ return_offsets_mapping=return_offsets_mapping,
942
+ return_length=return_length,
943
+ verbose=verbose,
944
+ **kwargs,
945
+ )
946
+
947
+ def _encode_plus(
948
+ self,
949
+ table: "pd.DataFrame",
950
+ query: Optional[TextInput] = None,
951
+ answer: Optional[str] = None,
952
+ add_special_tokens: bool = True,
953
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
954
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
955
+ max_length: Optional[int] = None,
956
+ stride: int = 0,
957
+ pad_to_multiple_of: Optional[int] = None,
958
+ return_tensors: Optional[Union[str, TensorType]] = None,
959
+ return_token_type_ids: Optional[bool] = None,
960
+ return_attention_mask: Optional[bool] = None,
961
+ return_overflowing_tokens: bool = False,
962
+ return_special_tokens_mask: bool = False,
963
+ return_offsets_mapping: bool = False,
964
+ return_length: bool = False,
965
+ verbose: bool = True,
966
+ **kwargs,
967
+ ) -> BatchEncoding:
968
+ if return_offsets_mapping:
969
+ raise NotImplementedError(
970
+ "return_offset_mapping is not available when using Python tokenizers. "
971
+ "To use this feature, change your tokenizer to one deriving from "
972
+ "transformers.PreTrainedTokenizerFast. "
973
+ "More information on available tokenizers at "
974
+ "https://github.com/huggingface/transformers/pull/2674"
975
+ )
976
+
977
+ text = self.prepare_table_query(
978
+ table, query, answer, truncation_strategy=truncation_strategy, max_length=max_length
979
+ )
980
+
981
+ # if necessary, perform lower case
982
+ if self.do_lower_case:
983
+ text = text.lower()
984
+
985
+ tokens = self.tokenize(text)
986
+
987
+ return self.prepare_for_model(
988
+ ids=self.convert_tokens_to_ids(tokens),
989
+ add_special_tokens=add_special_tokens,
990
+ padding=padding_strategy.value,
991
+ truncation=truncation_strategy.value,
992
+ max_length=max_length,
993
+ stride=stride,
994
+ pad_to_multiple_of=pad_to_multiple_of,
995
+ return_tensors=return_tensors,
996
+ prepend_batch_axis=True,
997
+ return_attention_mask=return_attention_mask,
998
+ return_token_type_ids=return_token_type_ids,
999
+ return_overflowing_tokens=return_overflowing_tokens,
1000
+ return_special_tokens_mask=return_special_tokens_mask,
1001
+ return_length=return_length,
1002
+ verbose=verbose,
1003
+ )
1004
+
1005
+ def target_call_func(
1006
+ self,
1007
+ answer: Union[str, List[str]],
1008
+ add_special_tokens: bool = True,
1009
+ padding: Union[bool, str, PaddingStrategy] = False,
1010
+ truncation: Union[bool, str, TruncationStrategy] = None,
1011
+ max_length: Optional[int] = None,
1012
+ stride: int = 0,
1013
+ pad_to_multiple_of: Optional[int] = None,
1014
+ return_tensors: Optional[Union[str, TensorType]] = None,
1015
+ return_token_type_ids: Optional[bool] = None,
1016
+ return_attention_mask: Optional[bool] = None,
1017
+ return_overflowing_tokens: bool = False,
1018
+ return_special_tokens_mask: bool = False,
1019
+ return_offsets_mapping: bool = False,
1020
+ return_length: bool = False,
1021
+ verbose: bool = True,
1022
+ **kwargs,
1023
+ ) -> BatchEncoding:
1024
+ """
1025
+ The method tokenizes and prepares the answer label for the model.
1026
+
1027
+ Args:
1028
+ answer (`str` or `List[str]`):
1029
+ Corresponding answer supervision to the queries for training the model.
1030
+ """
1031
+ is_batched = isinstance(answer, (list, tuple))
1032
+
1033
+ if is_batched:
1034
+ return self.target_batch_encode_plus(
1035
+ answer=answer,
1036
+ add_special_tokens=add_special_tokens,
1037
+ padding=padding,
1038
+ truncation=truncation,
1039
+ max_length=max_length,
1040
+ pad_to_multiple_of=pad_to_multiple_of,
1041
+ return_tensors=return_tensors,
1042
+ return_token_type_ids=return_token_type_ids,
1043
+ return_attention_mask=return_attention_mask,
1044
+ return_overflowing_tokens=return_overflowing_tokens,
1045
+ return_special_tokens_mask=return_special_tokens_mask,
1046
+ return_offsets_mapping=return_offsets_mapping,
1047
+ return_length=return_length,
1048
+ verbose=verbose,
1049
+ **kwargs,
1050
+ )
1051
+ else:
1052
+ return self.target_encode_plus(
1053
+ answer=answer,
1054
+ add_special_tokens=add_special_tokens,
1055
+ padding=padding,
1056
+ truncation=truncation,
1057
+ max_length=max_length,
1058
+ pad_to_multiple_of=pad_to_multiple_of,
1059
+ return_tensors=return_tensors,
1060
+ return_token_type_ids=return_token_type_ids,
1061
+ return_attention_mask=return_attention_mask,
1062
+ return_overflowing_tokens=return_overflowing_tokens,
1063
+ return_special_tokens_mask=return_special_tokens_mask,
1064
+ return_offsets_mapping=return_offsets_mapping,
1065
+ return_length=return_length,
1066
+ verbose=verbose,
1067
+ **kwargs,
1068
+ )
1069
+
1070
+ def target_batch_encode_plus(
1071
+ self,
1072
+ answer: List[str],
1073
+ add_special_tokens: bool = True,
1074
+ padding: Union[bool, str, PaddingStrategy] = False,
1075
+ truncation: Union[bool, str] = None,
1076
+ max_length: Optional[int] = None,
1077
+ pad_to_multiple_of: Optional[int] = None,
1078
+ return_tensors: Optional[Union[str, TensorType]] = None,
1079
+ return_token_type_ids: Optional[bool] = None,
1080
+ return_attention_mask: Optional[bool] = None,
1081
+ return_overflowing_tokens: bool = False,
1082
+ return_special_tokens_mask: bool = False,
1083
+ return_offsets_mapping: bool = False,
1084
+ return_length: bool = False,
1085
+ verbose: bool = True,
1086
+ **kwargs,
1087
+ ) -> BatchEncoding:
1088
+ """
1089
+ Prepare answer strings for the model.
1090
+
1091
+ Args:
1092
+ answer `List[str]`:
1093
+ Corresponding answer supervision to the queries for training the model.
1094
+ """
1095
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
1096
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
1097
+ padding=padding,
1098
+ truncation=truncation,
1099
+ max_length=max_length,
1100
+ pad_to_multiple_of=pad_to_multiple_of,
1101
+ verbose=verbose,
1102
+ **kwargs,
1103
+ )
1104
+
1105
+ return self._target_batch_encode_plus(
1106
+ answer=answer,
1107
+ add_special_tokens=add_special_tokens,
1108
+ padding_strategy=padding_strategy,
1109
+ truncation_strategy=truncation_strategy,
1110
+ max_length=max_length,
1111
+ pad_to_multiple_of=pad_to_multiple_of,
1112
+ return_tensors=return_tensors,
1113
+ return_token_type_ids=return_token_type_ids,
1114
+ return_attention_mask=return_attention_mask,
1115
+ return_overflowing_tokens=return_overflowing_tokens,
1116
+ return_special_tokens_mask=return_special_tokens_mask,
1117
+ return_offsets_mapping=return_offsets_mapping,
1118
+ return_length=return_length,
1119
+ verbose=verbose,
1120
+ **kwargs,
1121
+ )
1122
+
1123
+ def _target_batch_encode_plus(
1124
+ self,
1125
+ answer: List[str],
1126
+ add_special_tokens: bool = True,
1127
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1128
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
1129
+ max_length: Optional[int] = None,
1130
+ stride: int = 0,
1131
+ pad_to_multiple_of: Optional[int] = None,
1132
+ return_tensors: Optional[Union[str, TensorType]] = None,
1133
+ return_token_type_ids: Optional[bool] = None,
1134
+ return_attention_mask: Optional[bool] = None,
1135
+ return_overflowing_tokens: bool = False,
1136
+ return_special_tokens_mask: bool = False,
1137
+ return_offsets_mapping: bool = False,
1138
+ return_length: bool = False,
1139
+ verbose: bool = True,
1140
+ **kwargs,
1141
+ ) -> BatchEncoding:
1142
+ batch_outputs = {}
1143
+ for text in answer:
1144
+ if self.do_lower_case:
1145
+ text = text.lower()
1146
+
1147
+ tokens = self.tokenize(text)
1148
+ outputs = self.prepare_for_model(
1149
+ ids=self.convert_tokens_to_ids(tokens),
1150
+ add_special_tokens=add_special_tokens,
1151
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
1152
+ truncation=truncation_strategy.value,
1153
+ max_length=max_length,
1154
+ stride=stride,
1155
+ pad_to_multiple_of=None, # we pad in batch afterwards
1156
+ return_attention_mask=False, # we pad in batch afterwards
1157
+ return_token_type_ids=return_token_type_ids,
1158
+ return_overflowing_tokens=return_overflowing_tokens,
1159
+ return_special_tokens_mask=return_special_tokens_mask,
1160
+ return_length=return_length,
1161
+ return_tensors=None, # We convert the whole batch to tensors at the end
1162
+ prepend_batch_axis=False,
1163
+ verbose=verbose,
1164
+ )
1165
+
1166
+ for key, value in outputs.items():
1167
+ if key not in batch_outputs:
1168
+ batch_outputs[key] = []
1169
+ batch_outputs[key].append(value)
1170
+
1171
+ batch_outputs = self.pad(
1172
+ batch_outputs,
1173
+ padding=padding_strategy.value,
1174
+ max_length=max_length,
1175
+ pad_to_multiple_of=pad_to_multiple_of,
1176
+ return_attention_mask=return_attention_mask,
1177
+ )
1178
+
1179
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
1180
+
1181
+ return BatchEncoding(batch_outputs)
1182
+
1183
+ def target_encode(
1184
+ self,
1185
+ answer: str,
1186
+ add_special_tokens: bool = True,
1187
+ padding: Union[bool, str, PaddingStrategy] = False,
1188
+ truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
1189
+ max_length: Optional[int] = None,
1190
+ return_tensors: Optional[Union[str, TensorType]] = None,
1191
+ **kwargs,
1192
+ ) -> List[int]:
1193
+ """
1194
+ Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
1195
+ which are necessary for the model to work correctly. Use this method if you want to build your processing on
1196
+ your own, otherwise refer to `__call__`.
1197
+
1198
+ Args:
1199
+ answer `str`:
1200
+ Corresponding answer supervision to the queries for training the model
1201
+ """
1202
+ encoded_outputs = self.target_encode_plus(
1203
+ answer=answer,
1204
+ add_special_tokens=add_special_tokens,
1205
+ padding=padding,
1206
+ truncation=truncation,
1207
+ max_length=max_length,
1208
+ return_tensors=return_tensors,
1209
+ **kwargs,
1210
+ )
1211
+
1212
+ return encoded_outputs["input_ids"]
1213
+
1214
+ def target_encode_plus(
1215
+ self,
1216
+ answer: str,
1217
+ add_special_tokens: bool = True,
1218
+ padding: Union[bool, str, PaddingStrategy] = False,
1219
+ truncation: Union[bool, str] = None,
1220
+ max_length: Optional[int] = None,
1221
+ pad_to_multiple_of: Optional[int] = None,
1222
+ return_tensors: Optional[Union[str, TensorType]] = None,
1223
+ return_token_type_ids: Optional[bool] = None,
1224
+ return_attention_mask: Optional[bool] = None,
1225
+ return_special_tokens_mask: bool = False,
1226
+ return_offsets_mapping: bool = False,
1227
+ return_length: bool = False,
1228
+ verbose: bool = True,
1229
+ **kwargs,
1230
+ ) -> BatchEncoding:
1231
+ """
1232
+ Prepare a answer string for the model.
1233
+
1234
+ Args:
1235
+ answer `str`:
1236
+ Corresponding answer supervision to the queries for training the model.
1237
+ """
1238
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
1239
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
1240
+ padding=padding,
1241
+ truncation=truncation,
1242
+ max_length=max_length,
1243
+ pad_to_multiple_of=pad_to_multiple_of,
1244
+ verbose=verbose,
1245
+ **kwargs,
1246
+ )
1247
+
1248
+ return self._target_encode_plus(
1249
+ answer=answer,
1250
+ add_special_tokens=add_special_tokens,
1251
+ padding_strategy=padding_strategy,
1252
+ truncation_strategy=truncation_strategy,
1253
+ max_length=max_length,
1254
+ pad_to_multiple_of=pad_to_multiple_of,
1255
+ return_tensors=return_tensors,
1256
+ return_token_type_ids=return_token_type_ids,
1257
+ return_attention_mask=return_attention_mask,
1258
+ return_special_tokens_mask=return_special_tokens_mask,
1259
+ return_offsets_mapping=return_offsets_mapping,
1260
+ return_length=return_length,
1261
+ verbose=verbose,
1262
+ **kwargs,
1263
+ )
1264
+
1265
+ def _target_encode_plus(
1266
+ self,
1267
+ answer: str,
1268
+ add_special_tokens: bool = True,
1269
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1270
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
1271
+ max_length: Optional[int] = None,
1272
+ stride: int = 0,
1273
+ pad_to_multiple_of: Optional[int] = None,
1274
+ return_tensors: Optional[Union[str, TensorType]] = None,
1275
+ return_token_type_ids: Optional[bool] = None,
1276
+ return_attention_mask: Optional[bool] = None,
1277
+ return_overflowing_tokens: bool = False,
1278
+ return_special_tokens_mask: bool = False,
1279
+ return_offsets_mapping: bool = False,
1280
+ return_length: bool = False,
1281
+ verbose: bool = True,
1282
+ **kwargs,
1283
+ ) -> BatchEncoding:
1284
+ if return_offsets_mapping:
1285
+ raise NotImplementedError(
1286
+ "return_offset_mapping is not available when using Python tokenizers. "
1287
+ "To use this feature, change your tokenizer to one deriving from "
1288
+ "transformers.PreTrainedTokenizerFast. "
1289
+ "More information on available tokenizers at "
1290
+ "https://github.com/huggingface/transformers/pull/2674"
1291
+ )
1292
+
1293
+ text = answer
1294
+
1295
+ # if necessary, perform lower case
1296
+ if self.do_lower_case:
1297
+ text = text.lower()
1298
+
1299
+ tokens = self.tokenize(text)
1300
+
1301
+ return self.prepare_for_model(
1302
+ ids=self.convert_tokens_to_ids(tokens),
1303
+ add_special_tokens=add_special_tokens,
1304
+ padding=padding_strategy.value,
1305
+ truncation=truncation_strategy.value,
1306
+ max_length=max_length,
1307
+ stride=stride,
1308
+ pad_to_multiple_of=pad_to_multiple_of,
1309
+ return_tensors=return_tensors,
1310
+ prepend_batch_axis=True,
1311
+ return_attention_mask=return_attention_mask,
1312
+ return_token_type_ids=return_token_type_ids,
1313
+ return_overflowing_tokens=return_overflowing_tokens,
1314
+ return_special_tokens_mask=return_special_tokens_mask,
1315
+ return_length=return_length,
1316
+ verbose=verbose,
1317
+ )
1318
+
1319
+ def prepare_table_query(
1320
+ self,
1321
+ table,
1322
+ query,
1323
+ answer=None,
1324
+ truncation_strategy=Union[str, TruncationStrategy, TapexTruncationStrategy],
1325
+ max_length=None,
1326
+ ):
1327
+ """
1328
+ This method can be used to linearize a table and add a corresponding query.
1329
+
1330
+ Optionally, it also handles truncation of the table (cells).
1331
+
1332
+ An answer can be provided for more precise truncation.
1333
+ """
1334
+ if not table.empty:
1335
+ # step 1: create table dictionary
1336
+ table_content = {"header": list(table.columns), "rows": [list(row.values) for i, row in table.iterrows()]}
1337
+
1338
+ # step 2: modify table internally
1339
+ # always truncate table cells based on self.max_cell_length
1340
+ # optionally truncate rows if truncation_strategy is set to it
1341
+ self.truncate_table_cells(table_content, query, answer)
1342
+ if truncation_strategy == TapexTruncationStrategy.DROP_ROWS_TO_FIT:
1343
+ self.truncate_table_rows(table_content, query, answer, max_length=max_length)
1344
+
1345
+ # step 3: linearize table
1346
+ linear_table = self.table_linearize.process_table(table_content)
1347
+ else:
1348
+ linear_table = ""
1349
+
1350
+ if linear_table == "":
1351
+ logger.warning(
1352
+ "You provide an empty table, or all cells contain much tokens (e.g., >= 1024 tokens). "
1353
+ + f"Please carefully check the corresponding table with the query : {query}."
1354
+ )
1355
+ if query == "":
1356
+ logger.warning("You provide nothing to query with respect to the table.")
1357
+ # step 4: concatenate query with linear_table
1358
+ separator = " " if query and linear_table else ""
1359
+ joint_input = (query + separator + linear_table) if query else linear_table
1360
+
1361
+ return joint_input
1362
+
1363
+ def truncate_table_cells(self, table_content: Dict, question: str, answer: List):
1364
+ # TODO (Qian): is it possible to revert the original cell if it is in the final answer?
1365
+ cell_mapping = {}
1366
+ for row in table_content["rows"]:
1367
+ for i, cell in enumerate(row):
1368
+ truncate_cell = self.truncate_cell(cell)
1369
+ if truncate_cell is not None:
1370
+ cell_mapping[cell] = truncate_cell
1371
+ row[i] = truncate_cell
1372
+
1373
+ # modify the answer list
1374
+ if answer is not None:
1375
+ for i, case in enumerate(answer):
1376
+ if case in cell_mapping.keys():
1377
+ answer[i] = cell_mapping[case]
1378
+
1379
+ def truncate_cell(self, cell_value):
1380
+ # do not process on these cases
1381
+ if isinstance(cell_value, int) or isinstance(cell_value, float):
1382
+ return cell_value
1383
+ if cell_value.strip() != "":
1384
+ try_tokens = self.tokenize(cell_value)
1385
+ if len(try_tokens) >= self.max_cell_length:
1386
+ retain_tokens = try_tokens[: self.max_cell_length]
1387
+ retain_cell_value = self.convert_tokens_to_string(retain_tokens)
1388
+ return retain_cell_value
1389
+ else:
1390
+ return None
1391
+ else:
1392
+ return cell_value
1393
+
1394
+ def truncate_table_rows(
1395
+ self, table_content: Dict, question: str, answer: Optional[Union[str, List[str]]] = None, max_length=None
1396
+ ):
1397
+ """
1398
+ Args:
1399
+ table_content:
1400
+ {"header": xxx, "rows": xxx, "id" (Optionally): xxx}
1401
+
1402
+ question:
1403
+ natural language sentence
1404
+
1405
+ answer:
1406
+ if for training, is the supervision; otherwise will be empty
1407
+ """
1408
+ delete_ratio, remain_token_len = self.estimate_delete_ratio(table_content, question, max_length)
1409
+ # randomly delete unrelated rows
1410
+ self.delete_unrelated_rows(table_content, question, answer, delete_ratio)
1411
+ # guarantee the result < max_length
1412
+ maximum_keep_rows = 0
1413
+ for ind, row_example in enumerate(table_content["rows"]):
1414
+ value_string = self.table_linearize.process_row(row_example, ind + 1)
1415
+ value_token_len = len(self.tokenize(value_string))
1416
+ # over the size limit, and take action
1417
+ if value_token_len > remain_token_len:
1418
+ break
1419
+ remain_token_len -= value_token_len
1420
+ maximum_keep_rows += 1
1421
+ del table_content["rows"][maximum_keep_rows:]
1422
+
1423
+ def estimate_delete_ratio(self, table_content: Dict, question: str, max_length=None):
1424
+ if "header" not in table_content or "rows" not in table_content:
1425
+ raise ValueError("The table content should contain both 'header' and 'rows' keys.")
1426
+ # calculate the tokens of header, special tokens will only be pre-prepended into question
1427
+ question_tokens = self.tokenize(question, add_special_tokens=True)
1428
+ # calculate the tokens of header
1429
+ header_string = self.table_linearize.process_header(table_content["header"])
1430
+ header_tokens = self.tokenize(header_string, add_special_tokens=False)
1431
+ # split all cell values into tokens and see how many can be accommodated
1432
+ used_token_len = len(question_tokens) + len(header_tokens)
1433
+ # remaining token space for rows
1434
+ remain_token_len = max_length - used_token_len
1435
+
1436
+ value_string = ""
1437
+ for _, row_example in enumerate(table_content["rows"]):
1438
+ # use a general index to roughly estimate the overall token len
1439
+ value_string += self.table_linearize.process_row(row_example, 100) + " "
1440
+ value_token_len = len(self.tokenize(value_string))
1441
+
1442
+ if value_token_len < remain_token_len:
1443
+ # no row will be deleted
1444
+ return 0.0, remain_token_len
1445
+ else:
1446
+ # calc a roughly delete rate
1447
+ return 1.0 - remain_token_len / value_token_len, remain_token_len
1448
+
1449
+ def delete_unrelated_rows(self, table_content: Dict, question: str, answer: List, delete_ratio: float):
1450
+ """
1451
+ The argument answer is used only during training.
1452
+ """
1453
+ truncated_unrelated_indices = []
1454
+ related_indices = []
1455
+ if answer is None or len(answer) == 0:
1456
+ answer_set = set()
1457
+ else:
1458
+ answer_set = {ans_ex.lower() for ans_ex in answer}
1459
+ # add question key words into answer set
1460
+ if question is not None:
1461
+ answer_set.update(question.split())
1462
+ question_set = set(question.strip("?!.,").split(" "))
1463
+ row_max_len = len(table_content["rows"])
1464
+ for _row_idx, row in enumerate(table_content["rows"]):
1465
+ lower_row = {str(cell).lower() for cell in row}
1466
+ if len(lower_row & answer_set) == 0 and len(lower_row & question_set) == 0:
1467
+ truncated_unrelated_indices.append(_row_idx)
1468
+ else:
1469
+ # add neighbours to preserve information aggressively
1470
+ related_indices.extend([_row_idx - 2, _row_idx - 1, _row_idx, _row_idx + 1, _row_idx + 2])
1471
+
1472
+ # remove the neighbours
1473
+ truncated_unrelated_indices = [
1474
+ _row_idx for _row_idx in truncated_unrelated_indices if _row_idx not in related_indices
1475
+ ]
1476
+ # select some cases to drop
1477
+ drop_items = min(len(truncated_unrelated_indices), int(len(table_content["rows"]) * delete_ratio))
1478
+ drop_row_indices = random.choices(truncated_unrelated_indices, k=drop_items)
1479
+
1480
+ for _row_idx in reversed(range(row_max_len)):
1481
+ if _row_idx in drop_row_indices:
1482
+ del table_content["rows"][_row_idx]
1483
+
1484
+ # only when the drop ratio is too large, logging for warning.
1485
+ if "id" in table_content and len(drop_row_indices) > 0:
1486
+ logger.warning("Delete {:.2f} rows in table {}".format(len(drop_row_indices), table_content["id"]))
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/time_series_transformer/__init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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 OptionalDependencyNotAvailable, _LazyModule, is_torch_available
17
+
18
+
19
+ _import_structure = {
20
+ "configuration_time_series_transformer": [
21
+ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
22
+ "TimeSeriesTransformerConfig",
23
+ ],
24
+ }
25
+
26
+ try:
27
+ if not is_torch_available():
28
+ raise OptionalDependencyNotAvailable()
29
+ except OptionalDependencyNotAvailable:
30
+ pass
31
+ else:
32
+ _import_structure["modeling_time_series_transformer"] = [
33
+ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
34
+ "TimeSeriesTransformerForPrediction",
35
+ "TimeSeriesTransformerModel",
36
+ "TimeSeriesTransformerPreTrainedModel",
37
+ ]
38
+
39
+
40
+ if TYPE_CHECKING:
41
+ from .configuration_time_series_transformer import (
42
+ TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
43
+ TimeSeriesTransformerConfig,
44
+ )
45
+
46
+ try:
47
+ if not is_torch_available():
48
+ raise OptionalDependencyNotAvailable()
49
+ except OptionalDependencyNotAvailable:
50
+ pass
51
+ else:
52
+ from .modeling_time_series_transformer import (
53
+ TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
54
+ TimeSeriesTransformerForPrediction,
55
+ TimeSeriesTransformerModel,
56
+ TimeSeriesTransformerPreTrainedModel,
57
+ )
58
+
59
+ else:
60
+ import sys
61
+
62
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/time_series_transformer/configuration_time_series_transformer.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "huggingface/time-series-transformer-tourism-monthly": (
27
+ "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json"
28
+ ),
29
+ # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
30
+ }
31
+
32
+
33
+ class TimeSeriesTransformerConfig(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`TimeSeriesTransformerModel`]. It is used to
36
+ instantiate a Time Series Transformer model according to the specified arguments, defining the model architecture.
37
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Time Series
38
+ Transformer
39
+ [huggingface/time-series-transformer-tourism-monthly](https://huggingface.co/huggingface/time-series-transformer-tourism-monthly)
40
+ architecture.
41
+
42
+ Configuration objects inherit from [`PretrainedConfig`] can be used to control the model outputs. Read the
43
+ documentation from [`PretrainedConfig`] for more information.
44
+
45
+ Args:
46
+ prediction_length (`int`):
47
+ The prediction length for the decoder. In other words, the prediction horizon of the model. This value is
48
+ typically dictated by the dataset and we recommend to set it appropriately.
49
+ context_length (`int`, *optional*, defaults to `prediction_length`):
50
+ The context length for the encoder. If `None`, the context length will be the same as the
51
+ `prediction_length`.
52
+ distribution_output (`string`, *optional*, defaults to `"student_t"`):
53
+ The distribution emission head for the model. Could be either "student_t", "normal" or "negative_binomial".
54
+ loss (`string`, *optional*, defaults to `"nll"`):
55
+ The loss function for the model corresponding to the `distribution_output` head. For parametric
56
+ distributions it is the negative log likelihood (nll) - which currently is the only supported one.
57
+ input_size (`int`, *optional*, defaults to 1):
58
+ The size of the target variable which by default is 1 for univariate targets. Would be > 1 in case of
59
+ multivariate targets.
60
+ scaling (`string` or `bool`, *optional* defaults to `"mean"`):
61
+ Whether to scale the input targets via "mean" scaler, "std" scaler or no scaler if `None`. If `True`, the
62
+ scaler is set to "mean".
63
+ lags_sequence (`list[int]`, *optional*, defaults to `[1, 2, 3, 4, 5, 6, 7]`):
64
+ The lags of the input time series as covariates often dictated by the frequency of the data. Default is
65
+ `[1, 2, 3, 4, 5, 6, 7]` but we recommend to change it based on the dataset appropriately.
66
+ num_time_features (`int`, *optional*, defaults to 0):
67
+ The number of time features in the input time series.
68
+ num_dynamic_real_features (`int`, *optional*, defaults to 0):
69
+ The number of dynamic real valued features.
70
+ num_static_categorical_features (`int`, *optional*, defaults to 0):
71
+ The number of static categorical features.
72
+ num_static_real_features (`int`, *optional*, defaults to 0):
73
+ The number of static real valued features.
74
+ cardinality (`list[int]`, *optional*):
75
+ The cardinality (number of different values) for each of the static categorical features. Should be a list
76
+ of integers, having the same length as `num_static_categorical_features`. Cannot be `None` if
77
+ `num_static_categorical_features` is > 0.
78
+ embedding_dimension (`list[int]`, *optional*):
79
+ The dimension of the embedding for each of the static categorical features. Should be a list of integers,
80
+ having the same length as `num_static_categorical_features`. Cannot be `None` if
81
+ `num_static_categorical_features` is > 0.
82
+ d_model (`int`, *optional*, defaults to 64):
83
+ Dimensionality of the transformer layers.
84
+ encoder_layers (`int`, *optional*, defaults to 2):
85
+ Number of encoder layers.
86
+ decoder_layers (`int`, *optional*, defaults to 2):
87
+ Number of decoder layers.
88
+ encoder_attention_heads (`int`, *optional*, defaults to 2):
89
+ Number of attention heads for each attention layer in the Transformer encoder.
90
+ decoder_attention_heads (`int`, *optional*, defaults to 2):
91
+ Number of attention heads for each attention layer in the Transformer decoder.
92
+ encoder_ffn_dim (`int`, *optional*, defaults to 32):
93
+ Dimension of the "intermediate" (often named feed-forward) layer in encoder.
94
+ decoder_ffn_dim (`int`, *optional*, defaults to 32):
95
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
96
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
97
+ The non-linear activation function (function or string) in the encoder and decoder. If string, `"gelu"` and
98
+ `"relu"` are supported.
99
+ dropout (`float`, *optional*, defaults to 0.1):
100
+ The dropout probability for all fully connected layers in the encoder, and decoder.
101
+ encoder_layerdrop (`float`, *optional*, defaults to 0.1):
102
+ The dropout probability for the attention and fully connected layers for each encoder layer.
103
+ decoder_layerdrop (`float`, *optional*, defaults to 0.1):
104
+ The dropout probability for the attention and fully connected layers for each decoder layer.
105
+ attention_dropout (`float`, *optional*, defaults to 0.1):
106
+ The dropout probability for the attention probabilities.
107
+ activation_dropout (`float`, *optional*, defaults to 0.1):
108
+ The dropout probability used between the two layers of the feed-forward networks.
109
+ num_parallel_samples (`int`, *optional*, defaults to 100):
110
+ The number of samples to generate in parallel for each time step of inference.
111
+ init_std (`float`, *optional*, defaults to 0.02):
112
+ The standard deviation of the truncated normal weight initialization distribution.
113
+ use_cache (`bool`, *optional*, defaults to `True`):
114
+ Whether to use the past key/values attentions (if applicable to the model) to speed up decoding.
115
+
116
+ Example:
117
+
118
+ ```python
119
+ >>> from transformers import TimeSeriesTransformerConfig, TimeSeriesTransformerModel
120
+
121
+ >>> # Initializing a Time Series Transformer configuration with 12 time steps for prediction
122
+ >>> configuration = TimeSeriesTransformerConfig(prediction_length=12)
123
+
124
+ >>> # Randomly initializing a model (with random weights) from the configuration
125
+ >>> model = TimeSeriesTransformerModel(configuration)
126
+
127
+ >>> # Accessing the model configuration
128
+ >>> configuration = model.config
129
+ ```"""
130
+ model_type = "time_series_transformer"
131
+ attribute_map = {
132
+ "hidden_size": "d_model",
133
+ "num_attention_heads": "encoder_attention_heads",
134
+ "num_hidden_layers": "encoder_layers",
135
+ }
136
+
137
+ def __init__(
138
+ self,
139
+ prediction_length: Optional[int] = None,
140
+ context_length: Optional[int] = None,
141
+ distribution_output: str = "student_t",
142
+ loss: str = "nll",
143
+ input_size: int = 1,
144
+ lags_sequence: List[int] = [1, 2, 3, 4, 5, 6, 7],
145
+ scaling: Optional[Union[str, bool]] = "mean",
146
+ num_dynamic_real_features: int = 0,
147
+ num_static_categorical_features: int = 0,
148
+ num_static_real_features: int = 0,
149
+ num_time_features: int = 0,
150
+ cardinality: Optional[List[int]] = None,
151
+ embedding_dimension: Optional[List[int]] = None,
152
+ encoder_ffn_dim: int = 32,
153
+ decoder_ffn_dim: int = 32,
154
+ encoder_attention_heads: int = 2,
155
+ decoder_attention_heads: int = 2,
156
+ encoder_layers: int = 2,
157
+ decoder_layers: int = 2,
158
+ is_encoder_decoder: bool = True,
159
+ activation_function: str = "gelu",
160
+ d_model: int = 64,
161
+ dropout: float = 0.1,
162
+ encoder_layerdrop: float = 0.1,
163
+ decoder_layerdrop: float = 0.1,
164
+ attention_dropout: float = 0.1,
165
+ activation_dropout: float = 0.1,
166
+ num_parallel_samples: int = 100,
167
+ init_std: float = 0.02,
168
+ use_cache=True,
169
+ **kwargs,
170
+ ):
171
+ # time series specific configuration
172
+ self.prediction_length = prediction_length
173
+ self.context_length = context_length or prediction_length
174
+ self.distribution_output = distribution_output
175
+ self.loss = loss
176
+ self.input_size = input_size
177
+ self.num_time_features = num_time_features
178
+ self.lags_sequence = lags_sequence
179
+ self.scaling = scaling
180
+ self.num_dynamic_real_features = num_dynamic_real_features
181
+ self.num_static_real_features = num_static_real_features
182
+ self.num_static_categorical_features = num_static_categorical_features
183
+ if cardinality and num_static_categorical_features > 0:
184
+ if len(cardinality) != num_static_categorical_features:
185
+ raise ValueError(
186
+ "The cardinality should be a list of the same length as `num_static_categorical_features`"
187
+ )
188
+ self.cardinality = cardinality
189
+ else:
190
+ self.cardinality = [0]
191
+ if embedding_dimension and num_static_categorical_features > 0:
192
+ if len(embedding_dimension) != num_static_categorical_features:
193
+ raise ValueError(
194
+ "The embedding dimension should be a list of the same length as `num_static_categorical_features`"
195
+ )
196
+ self.embedding_dimension = embedding_dimension
197
+ else:
198
+ self.embedding_dimension = [min(50, (cat + 1) // 2) for cat in self.cardinality]
199
+ self.num_parallel_samples = num_parallel_samples
200
+
201
+ # Transformer architecture configuration
202
+ self.feature_size = input_size * len(lags_sequence) + self._number_of_features
203
+ self.d_model = d_model
204
+ self.encoder_attention_heads = encoder_attention_heads
205
+ self.decoder_attention_heads = decoder_attention_heads
206
+ self.encoder_ffn_dim = encoder_ffn_dim
207
+ self.decoder_ffn_dim = decoder_ffn_dim
208
+ self.encoder_layers = encoder_layers
209
+ self.decoder_layers = decoder_layers
210
+
211
+ self.dropout = dropout
212
+ self.attention_dropout = attention_dropout
213
+ self.activation_dropout = activation_dropout
214
+ self.encoder_layerdrop = encoder_layerdrop
215
+ self.decoder_layerdrop = decoder_layerdrop
216
+
217
+ self.activation_function = activation_function
218
+ self.init_std = init_std
219
+
220
+ self.output_attentions = False
221
+ self.output_hidden_states = False
222
+
223
+ self.use_cache = use_cache
224
+
225
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
226
+
227
+ @property
228
+ def _number_of_features(self) -> int:
229
+ return (
230
+ sum(self.embedding_dimension)
231
+ + self.num_dynamic_real_features
232
+ + self.num_time_features
233
+ + self.num_static_real_features
234
+ + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
235
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/time_series_transformer/modeling_time_series_transformer.py ADDED
@@ -0,0 +1,1827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import random
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch import nn
24
+
25
+ from ...activations import ACT2FN
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 add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
36
+ from .configuration_time_series_transformer import TimeSeriesTransformerConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CONFIG_FOR_DOC = "TimeSeriesTransformerConfig"
42
+
43
+
44
+ TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
45
+ "huggingface/time-series-transformer-tourism-monthly",
46
+ # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
47
+ ]
48
+
49
+
50
+ class TimeSeriesFeatureEmbedder(nn.Module):
51
+ """
52
+ Embed a sequence of categorical features.
53
+
54
+ Args:
55
+ cardinalities (`list[int]`):
56
+ List of cardinalities of the categorical features.
57
+ embedding_dims (`list[int]`):
58
+ List of embedding dimensions of the categorical features.
59
+ """
60
+
61
+ def __init__(self, cardinalities: List[int], embedding_dims: List[int]) -> None:
62
+ super().__init__()
63
+
64
+ self.num_features = len(cardinalities)
65
+ self.embedders = nn.ModuleList([nn.Embedding(c, d) for c, d in zip(cardinalities, embedding_dims)])
66
+
67
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
68
+ if self.num_features > 1:
69
+ # we slice the last dimension, giving an array of length
70
+ # self.num_features with shape (N,T) or (N)
71
+ cat_feature_slices = torch.chunk(features, self.num_features, dim=-1)
72
+ else:
73
+ cat_feature_slices = [features]
74
+
75
+ return torch.cat(
76
+ [
77
+ embed(cat_feature_slice.squeeze(-1))
78
+ for embed, cat_feature_slice in zip(self.embedders, cat_feature_slices)
79
+ ],
80
+ dim=-1,
81
+ )
82
+
83
+
84
+ class TimeSeriesStdScaler(nn.Module):
85
+ """
86
+ Standardize features by calculating the mean and scaling along some given dimension `dim`, and then normalizes it
87
+ by subtracting from the mean and dividing by the standard deviation.
88
+
89
+ Args:
90
+ dim (`int`):
91
+ Dimension along which to calculate the mean and standard deviation.
92
+ keepdim (`bool`, *optional*, defaults to `False`):
93
+ Controls whether to retain dimension `dim` (of length 1) in the scale tensor, or suppress it.
94
+ minimum_scale (`float`, *optional*, defaults to 1e-5):
95
+ Default scale that is used for elements that are constantly zero along dimension `dim`.
96
+ """
97
+
98
+ def __init__(self, dim: int, keepdim: bool = False, minimum_scale: float = 1e-5):
99
+ super().__init__()
100
+ if not dim > 0:
101
+ raise ValueError("Cannot compute scale along dim = 0 (batch dimension), please provide dim > 0")
102
+ self.dim = dim
103
+ self.keepdim = keepdim
104
+ self.minimum_scale = minimum_scale
105
+
106
+ @torch.no_grad()
107
+ def forward(self, data: torch.Tensor, weights: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
108
+ denominator = weights.sum(self.dim, keepdim=self.keepdim)
109
+ denominator = denominator.clamp_min(1.0)
110
+ loc = (data * weights).sum(self.dim, keepdim=self.keepdim) / denominator
111
+
112
+ variance = (((data - loc) * weights) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
113
+ scale = torch.sqrt(variance + self.minimum_scale)
114
+ return (data - loc) / scale, loc, scale
115
+
116
+
117
+ class TimeSeriesMeanScaler(nn.Module):
118
+ """
119
+ Computes a scaling factor as the weighted average absolute value along dimension `dim`, and scales the data
120
+ accordingly.
121
+
122
+ Args:
123
+ dim (`int`):
124
+ Dimension along which to compute the scale.
125
+ keepdim (`bool`, *optional*, defaults to `False`):
126
+ Controls whether to retain dimension `dim` (of length 1) in the scale tensor, or suppress it.
127
+ default_scale (`float`, *optional*, defaults to `None`):
128
+ Default scale that is used for elements that are constantly zero. If `None`, we use the scale of the batch.
129
+ minimum_scale (`float`, *optional*, defaults to 1e-10):
130
+ Default minimum possible scale that is used for any item.
131
+ """
132
+
133
+ def __init__(
134
+ self, dim: int = -1, keepdim: bool = True, default_scale: Optional[float] = None, minimum_scale: float = 1e-10
135
+ ):
136
+ super().__init__()
137
+ self.dim = dim
138
+ self.keepdim = keepdim
139
+ self.minimum_scale = minimum_scale
140
+ self.default_scale = default_scale
141
+
142
+ @torch.no_grad()
143
+ def forward(self, data: torch.Tensor, observed_indicator: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
144
+ # shape: (N, [C], T=1)
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 dimension `dim`, and therefore applies no scaling to the input data.
175
+
176
+ Args:
177
+ dim (`int`):
178
+ Dimension along which to compute the scale.
179
+ keepdim (`bool`, *optional*, defaults to `False`):
180
+ Controls whether to retain dimension `dim` (of length 1) in the scale tensor, or suppress it.
181
+ """
182
+
183
+ def __init__(self, dim: int, keepdim: bool = False):
184
+ super().__init__()
185
+ self.dim = dim
186
+ self.keepdim = keepdim
187
+
188
+ def forward(
189
+ self, data: torch.Tensor, observed_indicator: torch.Tensor
190
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
191
+ scale = torch.ones_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
192
+ loc = torch.zeros_like(data, requires_grad=False).mean(dim=self.dim, keepdim=self.keepdim)
193
+ return data, loc, scale
194
+
195
+
196
+ def nll(input: torch.distributions.Distribution, target: torch.Tensor) -> torch.Tensor:
197
+ """
198
+ Computes the negative log likelihood loss from input distribution with respect to target.
199
+ """
200
+ return -input.log_prob(target)
201
+
202
+
203
+ def weighted_average(input_tensor: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None) -> torch.Tensor:
204
+ """
205
+ Computes the weighted average of a given tensor across a given `dim`, masking values associated with weight zero,
206
+ meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`.
207
+
208
+ Args:
209
+ input_tensor (`torch.FloatTensor`):
210
+ Input tensor, of which the average must be computed.
211
+ weights (`torch.FloatTensor`, *optional*):
212
+ Weights tensor, of the same shape as `input_tensor`.
213
+ dim (`int`, *optional*):
214
+ The dim along which to average `input_tensor`.
215
+
216
+ Returns:
217
+ `torch.FloatTensor`: The tensor with values averaged along the specified `dim`.
218
+ """
219
+ if weights is not None:
220
+ weighted_tensor = torch.where(weights != 0, input_tensor * weights, torch.zeros_like(input_tensor))
221
+ sum_weights = torch.clamp(weights.sum(dim=dim) if dim else weights.sum(), min=1.0)
222
+ return (weighted_tensor.sum(dim=dim) if dim else weighted_tensor.sum()) / sum_weights
223
+ else:
224
+ return input_tensor.mean(dim=dim)
225
+
226
+
227
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
228
+ def _make_causal_mask(
229
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
230
+ ):
231
+ """
232
+ Make causal mask used for bi-directional self-attention.
233
+ """
234
+ bsz, tgt_len = input_ids_shape
235
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
236
+ mask_cond = torch.arange(mask.size(-1), device=device)
237
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
238
+ mask = mask.to(dtype)
239
+
240
+ if past_key_values_length > 0:
241
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
242
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
243
+
244
+
245
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
246
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
247
+ """
248
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
249
+ """
250
+ bsz, src_len = mask.size()
251
+ tgt_len = tgt_len if tgt_len is not None else src_len
252
+
253
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
254
+
255
+ inverted_mask = 1.0 - expanded_mask
256
+
257
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
258
+
259
+
260
+ # Copied from transformers.models.marian.modeling_marian.MarianSinusoidalPositionalEmbedding with Marian->TimeSeries
261
+ class TimeSeriesSinusoidalPositionalEmbedding(nn.Embedding):
262
+ """This module produces sinusoidal positional embeddings of any length."""
263
+
264
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None) -> None:
265
+ super().__init__(num_positions, embedding_dim)
266
+ self.weight = self._init_weight(self.weight)
267
+
268
+ @staticmethod
269
+ def _init_weight(out: nn.Parameter) -> nn.Parameter:
270
+ """
271
+ Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
272
+ the 2nd half of the vector. [dim // 2:]
273
+ """
274
+ n_pos, dim = out.shape
275
+ position_enc = np.array(
276
+ [[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
277
+ )
278
+ out.requires_grad = False # set early to avoid an error in pytorch-1.8+
279
+ sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
280
+ out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
281
+ out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
282
+ out.detach_()
283
+ return out
284
+
285
+ @torch.no_grad()
286
+ def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0) -> torch.Tensor:
287
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
288
+ bsz, seq_len = input_ids_shape[:2]
289
+ positions = torch.arange(
290
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
291
+ )
292
+ return super().forward(positions)
293
+
294
+
295
+ class TimeSeriesValueEmbedding(nn.Module):
296
+ def __init__(self, feature_size, d_model):
297
+ super().__init__()
298
+ self.value_projection = nn.Linear(in_features=feature_size, out_features=d_model, bias=False)
299
+
300
+ def forward(self, x):
301
+ return self.value_projection(x)
302
+
303
+
304
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->TimeSeriesTransformer
305
+ class TimeSeriesTransformerAttention(nn.Module):
306
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
307
+
308
+ def __init__(
309
+ self,
310
+ embed_dim: int,
311
+ num_heads: int,
312
+ dropout: float = 0.0,
313
+ is_decoder: bool = False,
314
+ bias: bool = True,
315
+ ):
316
+ super().__init__()
317
+ self.embed_dim = embed_dim
318
+ self.num_heads = num_heads
319
+ self.dropout = dropout
320
+ self.head_dim = embed_dim // num_heads
321
+
322
+ if (self.head_dim * num_heads) != self.embed_dim:
323
+ raise ValueError(
324
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
325
+ f" and `num_heads`: {num_heads})."
326
+ )
327
+ self.scaling = self.head_dim**-0.5
328
+ self.is_decoder = is_decoder
329
+
330
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
331
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
332
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
333
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
334
+
335
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
336
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
337
+
338
+ def forward(
339
+ self,
340
+ hidden_states: torch.Tensor,
341
+ key_value_states: Optional[torch.Tensor] = None,
342
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
343
+ attention_mask: Optional[torch.Tensor] = None,
344
+ layer_head_mask: Optional[torch.Tensor] = None,
345
+ output_attentions: bool = False,
346
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
347
+ """Input shape: Batch x Time x Channel"""
348
+
349
+ # if key_value_states are provided this layer is used as a cross-attention layer
350
+ # for the decoder
351
+ is_cross_attention = key_value_states is not None
352
+
353
+ bsz, tgt_len, _ = hidden_states.size()
354
+
355
+ # get query proj
356
+ query_states = self.q_proj(hidden_states) * self.scaling
357
+ # get key, value proj
358
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
359
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
360
+ # the provided `key_value_states` to support prefix tuning
361
+ if (
362
+ is_cross_attention
363
+ and past_key_value is not None
364
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
365
+ ):
366
+ # reuse k,v, cross_attentions
367
+ key_states = past_key_value[0]
368
+ value_states = past_key_value[1]
369
+ elif is_cross_attention:
370
+ # cross_attentions
371
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
372
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
373
+ elif past_key_value is not None:
374
+ # reuse k, v, self_attention
375
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
376
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
377
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
378
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
379
+ else:
380
+ # self_attention
381
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
382
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
383
+
384
+ if self.is_decoder:
385
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
386
+ # Further calls to cross_attention layer can then reuse all cross-attention
387
+ # key/value_states (first "if" case)
388
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
389
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
390
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
391
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
392
+ past_key_value = (key_states, value_states)
393
+
394
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
395
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
396
+ key_states = key_states.reshape(*proj_shape)
397
+ value_states = value_states.reshape(*proj_shape)
398
+
399
+ src_len = key_states.size(1)
400
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
401
+
402
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
403
+ raise ValueError(
404
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
405
+ f" {attn_weights.size()}"
406
+ )
407
+
408
+ if attention_mask is not None:
409
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
410
+ raise ValueError(
411
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
412
+ )
413
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
414
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
415
+
416
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
417
+
418
+ if layer_head_mask is not None:
419
+ if layer_head_mask.size() != (self.num_heads,):
420
+ raise ValueError(
421
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
422
+ f" {layer_head_mask.size()}"
423
+ )
424
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
425
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
426
+
427
+ if output_attentions:
428
+ # this operation is a bit awkward, but it's required to
429
+ # make sure that attn_weights keeps its gradient.
430
+ # In order to do so, attn_weights have to be reshaped
431
+ # twice and have to be reused in the following
432
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
433
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
434
+ else:
435
+ attn_weights_reshaped = None
436
+
437
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
438
+
439
+ attn_output = torch.bmm(attn_probs, value_states)
440
+
441
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
442
+ raise ValueError(
443
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
444
+ f" {attn_output.size()}"
445
+ )
446
+
447
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
448
+ attn_output = attn_output.transpose(1, 2)
449
+
450
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
451
+ # partitioned across GPUs when using tensor-parallelism.
452
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
453
+
454
+ attn_output = self.out_proj(attn_output)
455
+
456
+ return attn_output, attn_weights_reshaped, past_key_value
457
+
458
+
459
+ # Copied from transformers.models.bart.modeling_bart.BartEncoderLayer with Bart->TimeSeriesTransformer
460
+ class TimeSeriesTransformerEncoderLayer(nn.Module):
461
+ def __init__(self, config: TimeSeriesTransformerConfig):
462
+ super().__init__()
463
+ self.embed_dim = config.d_model
464
+ self.self_attn = TimeSeriesTransformerAttention(
465
+ embed_dim=self.embed_dim,
466
+ num_heads=config.encoder_attention_heads,
467
+ dropout=config.attention_dropout,
468
+ )
469
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
470
+ self.dropout = config.dropout
471
+ self.activation_fn = ACT2FN[config.activation_function]
472
+ self.activation_dropout = config.activation_dropout
473
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
474
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
475
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
476
+
477
+ def forward(
478
+ self,
479
+ hidden_states: torch.FloatTensor,
480
+ attention_mask: torch.FloatTensor,
481
+ layer_head_mask: torch.FloatTensor,
482
+ output_attentions: Optional[bool] = False,
483
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
484
+ """
485
+ Args:
486
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
487
+ attention_mask (`torch.FloatTensor`): attention mask of size
488
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
489
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
490
+ `(encoder_attention_heads,)`.
491
+ output_attentions (`bool`, *optional*):
492
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
493
+ returned tensors for more detail.
494
+ """
495
+ residual = hidden_states
496
+ hidden_states, attn_weights, _ = self.self_attn(
497
+ hidden_states=hidden_states,
498
+ attention_mask=attention_mask,
499
+ layer_head_mask=layer_head_mask,
500
+ output_attentions=output_attentions,
501
+ )
502
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
503
+ hidden_states = residual + hidden_states
504
+ hidden_states = self.self_attn_layer_norm(hidden_states)
505
+
506
+ residual = hidden_states
507
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
508
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
509
+ hidden_states = self.fc2(hidden_states)
510
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
511
+ hidden_states = residual + hidden_states
512
+ hidden_states = self.final_layer_norm(hidden_states)
513
+
514
+ if hidden_states.dtype == torch.float16 and (
515
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
516
+ ):
517
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
518
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
519
+
520
+ outputs = (hidden_states,)
521
+
522
+ if output_attentions:
523
+ outputs += (attn_weights,)
524
+
525
+ return outputs
526
+
527
+
528
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderLayer with Bart->TimeSeriesTransformer
529
+ class TimeSeriesTransformerDecoderLayer(nn.Module):
530
+ def __init__(self, config: TimeSeriesTransformerConfig):
531
+ super().__init__()
532
+ self.embed_dim = config.d_model
533
+
534
+ self.self_attn = TimeSeriesTransformerAttention(
535
+ embed_dim=self.embed_dim,
536
+ num_heads=config.decoder_attention_heads,
537
+ dropout=config.attention_dropout,
538
+ is_decoder=True,
539
+ )
540
+ self.dropout = config.dropout
541
+ self.activation_fn = ACT2FN[config.activation_function]
542
+ self.activation_dropout = config.activation_dropout
543
+
544
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
545
+ self.encoder_attn = TimeSeriesTransformerAttention(
546
+ self.embed_dim,
547
+ config.decoder_attention_heads,
548
+ dropout=config.attention_dropout,
549
+ is_decoder=True,
550
+ )
551
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
552
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
553
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
554
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
555
+
556
+ def forward(
557
+ self,
558
+ hidden_states: torch.Tensor,
559
+ attention_mask: Optional[torch.Tensor] = None,
560
+ encoder_hidden_states: Optional[torch.Tensor] = None,
561
+ encoder_attention_mask: Optional[torch.Tensor] = None,
562
+ layer_head_mask: Optional[torch.Tensor] = None,
563
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
564
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
565
+ output_attentions: Optional[bool] = False,
566
+ use_cache: Optional[bool] = True,
567
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
568
+ """
569
+ Args:
570
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
571
+ attention_mask (`torch.FloatTensor`): attention mask of size
572
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
573
+ encoder_hidden_states (`torch.FloatTensor`):
574
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
575
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
576
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
577
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
578
+ `(encoder_attention_heads,)`.
579
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
580
+ size `(decoder_attention_heads,)`.
581
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
582
+ output_attentions (`bool`, *optional*):
583
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
584
+ returned tensors for more detail.
585
+ """
586
+ residual = hidden_states
587
+
588
+ # Self Attention
589
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
590
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
591
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
592
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
593
+ hidden_states=hidden_states,
594
+ past_key_value=self_attn_past_key_value,
595
+ attention_mask=attention_mask,
596
+ layer_head_mask=layer_head_mask,
597
+ output_attentions=output_attentions,
598
+ )
599
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
600
+ hidden_states = residual + hidden_states
601
+ hidden_states = self.self_attn_layer_norm(hidden_states)
602
+
603
+ # Cross-Attention Block
604
+ cross_attn_present_key_value = None
605
+ cross_attn_weights = None
606
+ if encoder_hidden_states is not None:
607
+ residual = hidden_states
608
+
609
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
610
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
611
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
612
+ hidden_states=hidden_states,
613
+ key_value_states=encoder_hidden_states,
614
+ attention_mask=encoder_attention_mask,
615
+ layer_head_mask=cross_attn_layer_head_mask,
616
+ past_key_value=cross_attn_past_key_value,
617
+ output_attentions=output_attentions,
618
+ )
619
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
620
+ hidden_states = residual + hidden_states
621
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
622
+
623
+ # add cross-attn to positions 3,4 of present_key_value tuple
624
+ present_key_value = present_key_value + cross_attn_present_key_value
625
+
626
+ # Fully Connected
627
+ residual = hidden_states
628
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
629
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
630
+ hidden_states = self.fc2(hidden_states)
631
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
632
+ hidden_states = residual + hidden_states
633
+ hidden_states = self.final_layer_norm(hidden_states)
634
+
635
+ outputs = (hidden_states,)
636
+
637
+ if output_attentions:
638
+ outputs += (self_attn_weights, cross_attn_weights)
639
+
640
+ if use_cache:
641
+ outputs += (present_key_value,)
642
+
643
+ return outputs
644
+
645
+
646
+ class TimeSeriesTransformerPreTrainedModel(PreTrainedModel):
647
+ config_class = TimeSeriesTransformerConfig
648
+ base_model_prefix = "model"
649
+ main_input_name = "past_values"
650
+ supports_gradient_checkpointing = True
651
+
652
+ def _init_weights(self, module):
653
+ std = self.config.init_std
654
+ if isinstance(module, nn.Linear):
655
+ module.weight.data.normal_(mean=0.0, std=std)
656
+ if module.bias is not None:
657
+ module.bias.data.zero_()
658
+ elif isinstance(module, TimeSeriesSinusoidalPositionalEmbedding):
659
+ pass
660
+ elif isinstance(module, nn.Embedding):
661
+ module.weight.data.normal_(mean=0.0, std=std)
662
+ if module.padding_idx is not None:
663
+ module.weight.data[module.padding_idx].zero_()
664
+
665
+ def _set_gradient_checkpointing(self, module, value=False):
666
+ if isinstance(module, (TimeSeriesTransformerDecoder, TimeSeriesTransformerEncoder)):
667
+ module.gradient_checkpointing = value
668
+
669
+
670
+ TIME_SERIES_TRANSFORMER_START_DOCSTRING = r"""
671
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
672
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
673
+ etc.)
674
+
675
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
676
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
677
+ and behavior.
678
+
679
+ Parameters:
680
+ config ([`TimeSeriesTransformerConfig`]):
681
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
682
+ load the weights associated with the model, only the configuration. Check out the
683
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
684
+ """
685
+
686
+ TIME_SERIES_TRANSFORMER_INPUTS_DOCSTRING = r"""
687
+ Args:
688
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`):
689
+ Past values of the time series, that serve as context in order to predict the future. The sequence size of
690
+ this tensor must be larger than the `context_length` of the model, since the model will use the larger size
691
+ to construct lag features, i.e. additional values from the past which are added in order to serve as "extra
692
+ context".
693
+
694
+ The `sequence_length` here is equal to `config.context_length` + `max(config.lags_sequence)`, which if no
695
+ `lags_sequence` is configured, is equal to `config.context_length` + 7 (as by default, the largest
696
+ look-back index in `config.lags_sequence` is 7). The property `_past_length` returns the actual length of
697
+ the past.
698
+
699
+ The `past_values` is what the Transformer encoder gets as input (with optional additional features, such as
700
+ `static_categorical_features`, `static_real_features`, `past_time_features` and lags).
701
+
702
+ Optionally, missing values need to be replaced with zeros and indicated via the `past_observed_mask`.
703
+
704
+ For multivariate time series, the `input_size` > 1 dimension is required and corresponds to the number of
705
+ variates in the time series per time step.
706
+ past_time_features (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_features)`):
707
+ Required time features, which the model internally will add to `past_values`. These could be things like
708
+ "month of year", "day of the month", etc. encoded as vectors (for instance as Fourier features). These
709
+ could also be so-called "age" features, which basically help the model know "at which point in life" a
710
+ time-series is. Age features have small values for distant past time steps and increase monotonically the
711
+ more we approach the current time step. Holiday features are also a good example of time features.
712
+
713
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT, where
714
+ the position encodings are learned from scratch internally as parameters of the model, the Time Series
715
+ Transformer requires to provide additional time features. The Time Series Transformer only learns
716
+ additional embeddings for `static_categorical_features`.
717
+
718
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these features
719
+ must but known at prediction time.
720
+
721
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
722
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`, *optional*):
723
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected in
724
+ `[0, 1]`:
725
+
726
+ - 1 for values that are **observed**,
727
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
728
+
729
+ static_categorical_features (`torch.LongTensor` of shape `(batch_size, number of static categorical features)`, *optional*):
730
+ Optional static categorical features for which the model will learn an embedding, which it will add to the
731
+ values of the time series.
732
+
733
+ Static categorical features are features which have the same value for all time steps (static over time).
734
+
735
+ A typical example of a static categorical feature is a time series ID.
736
+ static_real_features (`torch.FloatTensor` of shape `(batch_size, number of static real features)`, *optional*):
737
+ Optional static real features which the model will add to the values of the time series.
738
+
739
+ Static real features are features which have the same value for all time steps (static over time).
740
+
741
+ A typical example of a static real feature is promotion information.
742
+ future_values (`torch.FloatTensor` of shape `(batch_size, prediction_length)` or `(batch_size, prediction_length, input_size)`, *optional*):
743
+ Future values of the time series, that serve as labels for the model. The `future_values` is what the
744
+ Transformer needs during training to learn to output, given the `past_values`.
745
+
746
+ The sequence length here is equal to `prediction_length`.
747
+
748
+ See the demo notebook and code snippets for details.
749
+
750
+ Optionally, during training any missing values need to be replaced with zeros and indicated via the
751
+ `future_observed_mask`.
752
+
753
+ For multivariate time series, the `input_size` > 1 dimension is required and corresponds to the number of
754
+ variates in the time series per time step.
755
+ future_time_features (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_features)`):
756
+ Required time features for the prediction window, which the model internally will add to `future_values`.
757
+ These could be things like "month of year", "day of the month", etc. encoded as vectors (for instance as
758
+ Fourier features). These could also be so-called "age" features, which basically help the model know "at
759
+ which point in life" a time-series is. Age features have small values for distant past time steps and
760
+ increase monotonically the more we approach the current time step. Holiday features are also a good example
761
+ of time features.
762
+
763
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT, where
764
+ the position encodings are learned from scratch internally as parameters of the model, the Time Series
765
+ Transformer requires to provide additional time features. The Time Series Transformer only learns
766
+ additional embeddings for `static_categorical_features`.
767
+
768
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these features
769
+ must but known at prediction time.
770
+
771
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
772
+ future_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`, *optional*):
773
+ Boolean mask to indicate which `future_values` were observed and which were missing. Mask values selected
774
+ in `[0, 1]`:
775
+
776
+ - 1 for values that are **observed**,
777
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
778
+
779
+ This mask is used to filter out missing values for the final loss calculation.
780
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
781
+ Mask to avoid performing attention on certain token indices. Mask values selected in `[0, 1]`:
782
+
783
+ - 1 for tokens that are **not masked**,
784
+ - 0 for tokens that are **masked**.
785
+
786
+ [What are attention masks?](../glossary#attention-mask)
787
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
788
+ Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to
789
+ make sure the model can only look at previous inputs in order to predict the future.
790
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
791
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
792
+
793
+ - 1 indicates the head is **not masked**,
794
+ - 0 indicates the head is **masked**.
795
+
796
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
797
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
798
+
799
+ - 1 indicates the head is **not masked**,
800
+ - 0 indicates the head is **masked**.
801
+
802
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
803
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
804
+
805
+ - 1 indicates the head is **not masked**,
806
+ - 0 indicates the head is **masked**.
807
+
808
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
809
+ Tuple consists of `last_hidden_state`, `hidden_states` (*optional*) and `attentions` (*optional*)
810
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` (*optional*) is a sequence of
811
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
812
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
813
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
814
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
815
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
816
+
817
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
818
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
819
+
820
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
821
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
822
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
823
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
824
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
825
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
826
+ model's internal embedding lookup matrix.
827
+ use_cache (`bool`, *optional*):
828
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
829
+ `past_key_values`).
830
+ output_attentions (`bool`, *optional*):
831
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
832
+ tensors for more detail.
833
+ output_hidden_states (`bool`, *optional*):
834
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
835
+ more detail.
836
+ return_dict (`bool`, *optional*):
837
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
838
+ """
839
+
840
+
841
+ class TimeSeriesTransformerEncoder(TimeSeriesTransformerPreTrainedModel):
842
+ """
843
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
844
+ [`TimeSeriesTransformerEncoderLayer`].
845
+
846
+ Args:
847
+ config: TimeSeriesTransformerConfig
848
+ """
849
+
850
+ def __init__(self, config: TimeSeriesTransformerConfig):
851
+ super().__init__(config)
852
+
853
+ self.dropout = config.dropout
854
+ self.layerdrop = config.encoder_layerdrop
855
+ if config.prediction_length is None:
856
+ raise ValueError("The `prediction_length` config needs to be specified.")
857
+
858
+ self.value_embedding = TimeSeriesValueEmbedding(feature_size=config.feature_size, d_model=config.d_model)
859
+ self.embed_positions = TimeSeriesSinusoidalPositionalEmbedding(
860
+ config.context_length + config.prediction_length, config.d_model
861
+ )
862
+ self.layers = nn.ModuleList([TimeSeriesTransformerEncoderLayer(config) for _ in range(config.encoder_layers)])
863
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
864
+
865
+ self.gradient_checkpointing = False
866
+ # Initialize weights and apply final processing
867
+ self.post_init()
868
+
869
+ def forward(
870
+ self,
871
+ attention_mask: Optional[torch.Tensor] = None,
872
+ head_mask: Optional[torch.Tensor] = None,
873
+ inputs_embeds: Optional[torch.FloatTensor] = None,
874
+ output_attentions: Optional[bool] = None,
875
+ output_hidden_states: Optional[bool] = None,
876
+ return_dict: Optional[bool] = None,
877
+ ) -> Union[Tuple, BaseModelOutput]:
878
+ r"""
879
+ Args:
880
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
881
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
882
+
883
+ - 1 for tokens that are **not masked**,
884
+ - 0 for tokens that are **masked**.
885
+
886
+ [What are attention masks?](../glossary#attention-mask)
887
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
888
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
889
+
890
+ - 1 indicates the head is **not masked**,
891
+ - 0 indicates the head is **masked**.
892
+
893
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
894
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
895
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
896
+ than the model's internal embedding lookup matrix.
897
+ output_attentions (`bool`, *optional*):
898
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
899
+ returned tensors for more detail.
900
+ output_hidden_states (`bool`, *optional*):
901
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
902
+ for more detail.
903
+ return_dict (`bool`, *optional*):
904
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
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
+ hidden_states = self.value_embedding(inputs_embeds)
913
+ embed_pos = self.embed_positions(inputs_embeds.size())
914
+
915
+ hidden_states = self.layernorm_embedding(hidden_states + embed_pos)
916
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
917
+
918
+ # expand attention_mask
919
+ if attention_mask is not None:
920
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
921
+ attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
922
+
923
+ encoder_states = () if output_hidden_states else None
924
+ all_attentions = () if output_attentions else None
925
+
926
+ # check if head_mask has a correct number of layers specified if desired
927
+ if head_mask is not None:
928
+ if head_mask.size()[0] != (len(self.layers)):
929
+ raise ValueError(
930
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
931
+ f" {head_mask.size()[0]}."
932
+ )
933
+
934
+ for idx, encoder_layer in enumerate(self.layers):
935
+ if output_hidden_states:
936
+ encoder_states = encoder_states + (hidden_states,)
937
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
938
+ dropout_probability = random.uniform(0, 1)
939
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
940
+ layer_outputs = (None, None)
941
+ else:
942
+ if self.gradient_checkpointing and self.training:
943
+
944
+ def create_custom_forward(module):
945
+ def custom_forward(*inputs):
946
+ return module(*inputs, output_attentions)
947
+
948
+ return custom_forward
949
+
950
+ layer_outputs = torch.utils.checkpoint.checkpoint(
951
+ create_custom_forward(encoder_layer),
952
+ hidden_states,
953
+ attention_mask,
954
+ (head_mask[idx] if head_mask is not None else None),
955
+ )
956
+ else:
957
+ layer_outputs = encoder_layer(
958
+ hidden_states,
959
+ attention_mask,
960
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
961
+ output_attentions=output_attentions,
962
+ )
963
+
964
+ hidden_states = layer_outputs[0]
965
+
966
+ if output_attentions:
967
+ all_attentions = all_attentions + (layer_outputs[1],)
968
+
969
+ if output_hidden_states:
970
+ encoder_states = encoder_states + (hidden_states,)
971
+
972
+ if not return_dict:
973
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
974
+ return BaseModelOutput(
975
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
976
+ )
977
+
978
+
979
+ class TimeSeriesTransformerDecoder(TimeSeriesTransformerPreTrainedModel):
980
+ """
981
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a
982
+ [`TimeSeriesTransformerDecoderLayer`]
983
+
984
+ Args:
985
+ config: TimeSeriesTransformerConfig
986
+ """
987
+
988
+ def __init__(self, config: TimeSeriesTransformerConfig):
989
+ super().__init__(config)
990
+ self.dropout = config.dropout
991
+ self.layerdrop = config.decoder_layerdrop
992
+ if config.prediction_length is None:
993
+ raise ValueError("The `prediction_length` config needs to be specified.")
994
+
995
+ self.value_embedding = TimeSeriesValueEmbedding(feature_size=config.feature_size, d_model=config.d_model)
996
+ self.embed_positions = TimeSeriesSinusoidalPositionalEmbedding(
997
+ config.context_length + config.prediction_length, config.d_model
998
+ )
999
+ self.layers = nn.ModuleList([TimeSeriesTransformerDecoderLayer(config) for _ in range(config.decoder_layers)])
1000
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
1001
+
1002
+ self.gradient_checkpointing = False
1003
+ # Initialize weights and apply final processing
1004
+ self.post_init()
1005
+
1006
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
1007
+ # create causal mask
1008
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1009
+ combined_attention_mask = None
1010
+ if input_shape[-1] > 1:
1011
+ combined_attention_mask = _make_causal_mask(
1012
+ input_shape,
1013
+ inputs_embeds.dtype,
1014
+ device=inputs_embeds.device,
1015
+ past_key_values_length=past_key_values_length,
1016
+ )
1017
+
1018
+ if attention_mask is not None:
1019
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1020
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
1021
+ inputs_embeds.device
1022
+ )
1023
+ combined_attention_mask = (
1024
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
1025
+ )
1026
+
1027
+ return combined_attention_mask
1028
+
1029
+ def forward(
1030
+ self,
1031
+ attention_mask: Optional[torch.Tensor] = None,
1032
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1033
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
1034
+ head_mask: Optional[torch.Tensor] = None,
1035
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1036
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1037
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1038
+ use_cache: Optional[bool] = None,
1039
+ output_attentions: Optional[bool] = None,
1040
+ output_hidden_states: Optional[bool] = None,
1041
+ return_dict: Optional[bool] = None,
1042
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
1043
+ r"""
1044
+ Args:
1045
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1046
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1047
+
1048
+ - 1 for tokens that are **not masked**,
1049
+ - 0 for tokens that are **masked**.
1050
+
1051
+ [What are attention masks?](../glossary#attention-mask)
1052
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1053
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1054
+ of the decoder.
1055
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1056
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
1057
+ selected in `[0, 1]`:
1058
+
1059
+ - 1 for tokens that are **not masked**,
1060
+ - 0 for tokens that are **masked**.
1061
+
1062
+ [What are attention masks?](../glossary#attention-mask)
1063
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1064
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1065
+
1066
+ - 1 indicates the head is **not masked**,
1067
+ - 0 indicates the head is **masked**.
1068
+
1069
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1070
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
1071
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
1072
+
1073
+ - 1 indicates the head is **not masked**,
1074
+ - 0 indicates the head is **masked**.
1075
+
1076
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1077
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1078
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1079
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1080
+
1081
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1082
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1083
+
1084
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1085
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1086
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1087
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1088
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1089
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1090
+ than the model's internal embedding lookup matrix.
1091
+ output_attentions (`bool`, *optional*):
1092
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1093
+ returned tensors for more detail.
1094
+ output_hidden_states (`bool`, *optional*):
1095
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1096
+ for more detail.
1097
+ return_dict (`bool`, *optional*):
1098
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1099
+ """
1100
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1101
+ output_hidden_states = (
1102
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1103
+ )
1104
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1105
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1106
+
1107
+ input_shape = inputs_embeds.size()[:-1]
1108
+
1109
+ # past_key_values_length
1110
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1111
+
1112
+ attention_mask = self._prepare_decoder_attention_mask(
1113
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1114
+ )
1115
+
1116
+ # expand encoder attention mask
1117
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1118
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1119
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
1120
+
1121
+ hidden_states = self.value_embedding(inputs_embeds)
1122
+ embed_pos = self.embed_positions(inputs_embeds.size(), past_key_values_length=self.config.context_length)
1123
+ hidden_states = self.layernorm_embedding(hidden_states + embed_pos)
1124
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1125
+
1126
+ if self.gradient_checkpointing and self.training:
1127
+ if use_cache:
1128
+ logger.warning_once(
1129
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1130
+ )
1131
+ use_cache = False
1132
+
1133
+ # decoder layers
1134
+ all_hidden_states = () if output_hidden_states else None
1135
+ all_self_attns = () if output_attentions else None
1136
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1137
+ next_decoder_cache = () if use_cache else None
1138
+
1139
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1140
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1141
+ if attn_mask is not None:
1142
+ if attn_mask.size()[0] != (len(self.layers)):
1143
+ raise ValueError(
1144
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1145
+ f" {head_mask.size()[0]}."
1146
+ )
1147
+
1148
+ for idx, decoder_layer in enumerate(self.layers):
1149
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1150
+ if output_hidden_states:
1151
+ all_hidden_states += (hidden_states,)
1152
+ dropout_probability = random.uniform(0, 1)
1153
+ if self.training and (dropout_probability < self.layerdrop):
1154
+ continue
1155
+
1156
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1157
+
1158
+ if self.gradient_checkpointing and self.training:
1159
+
1160
+ def create_custom_forward(module):
1161
+ def custom_forward(*inputs):
1162
+ # None for past_key_value
1163
+ return module(*inputs, output_attentions, use_cache)
1164
+
1165
+ return custom_forward
1166
+
1167
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1168
+ create_custom_forward(decoder_layer),
1169
+ hidden_states,
1170
+ attention_mask,
1171
+ encoder_hidden_states,
1172
+ encoder_attention_mask,
1173
+ head_mask[idx] if head_mask is not None else None,
1174
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1175
+ None,
1176
+ )
1177
+ else:
1178
+ layer_outputs = decoder_layer(
1179
+ hidden_states,
1180
+ attention_mask=attention_mask,
1181
+ encoder_hidden_states=encoder_hidden_states,
1182
+ encoder_attention_mask=encoder_attention_mask,
1183
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1184
+ cross_attn_layer_head_mask=(
1185
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1186
+ ),
1187
+ past_key_value=past_key_value,
1188
+ output_attentions=output_attentions,
1189
+ use_cache=use_cache,
1190
+ )
1191
+ hidden_states = layer_outputs[0]
1192
+
1193
+ if use_cache:
1194
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1195
+
1196
+ if output_attentions:
1197
+ all_self_attns += (layer_outputs[1],)
1198
+
1199
+ if encoder_hidden_states is not None:
1200
+ all_cross_attentions += (layer_outputs[2],)
1201
+
1202
+ # add hidden states from the last decoder layer
1203
+ if output_hidden_states:
1204
+ all_hidden_states += (hidden_states,)
1205
+
1206
+ next_cache = next_decoder_cache if use_cache else None
1207
+ if not return_dict:
1208
+ return tuple(
1209
+ v
1210
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1211
+ if v is not None
1212
+ )
1213
+ return BaseModelOutputWithPastAndCrossAttentions(
1214
+ last_hidden_state=hidden_states,
1215
+ past_key_values=next_cache,
1216
+ hidden_states=all_hidden_states,
1217
+ attentions=all_self_attns,
1218
+ cross_attentions=all_cross_attentions,
1219
+ )
1220
+
1221
+
1222
+ @add_start_docstrings(
1223
+ "The bare Time Series Transformer Model outputting raw hidden-states without any specific head on top.",
1224
+ TIME_SERIES_TRANSFORMER_START_DOCSTRING,
1225
+ )
1226
+ class TimeSeriesTransformerModel(TimeSeriesTransformerPreTrainedModel):
1227
+ def __init__(self, config: TimeSeriesTransformerConfig):
1228
+ super().__init__(config)
1229
+
1230
+ if config.scaling == "mean" or config.scaling:
1231
+ self.scaler = TimeSeriesMeanScaler(dim=1, keepdim=True)
1232
+ elif config.scaling == "std":
1233
+ self.scaler = TimeSeriesStdScaler(dim=1, keepdim=True)
1234
+ else:
1235
+ self.scaler = TimeSeriesNOPScaler(dim=1, keepdim=True)
1236
+
1237
+ if config.num_static_categorical_features > 0:
1238
+ self.embedder = TimeSeriesFeatureEmbedder(
1239
+ cardinalities=config.cardinality,
1240
+ embedding_dims=config.embedding_dimension,
1241
+ )
1242
+
1243
+ # transformer encoder-decoder and mask initializer
1244
+ self.encoder = TimeSeriesTransformerEncoder(config)
1245
+ self.decoder = TimeSeriesTransformerDecoder(config)
1246
+
1247
+ # Initialize weights and apply final processing
1248
+ self.post_init()
1249
+
1250
+ @property
1251
+ def _past_length(self) -> int:
1252
+ return self.config.context_length + max(self.config.lags_sequence)
1253
+
1254
+ def get_lagged_subsequences(
1255
+ self, sequence: torch.Tensor, subsequences_length: int, shift: int = 0
1256
+ ) -> torch.Tensor:
1257
+ """
1258
+ Returns lagged subsequences of a given sequence. Returns a tensor of shape (N, S, C, I),
1259
+ where S = subsequences_length and I = len(indices), containing lagged subsequences. Specifically, lagged[i,
1260
+ j, :, k] = sequence[i, -indices[k]-S+j, :].
1261
+
1262
+ Args:
1263
+ sequence: Tensor
1264
+ The sequence from which lagged subsequences should be extracted. Shape: (N, T, C).
1265
+ subsequences_length : int
1266
+ Length of the subsequences to be extracted.
1267
+ shift: int
1268
+ Shift the lags by this amount back.
1269
+ """
1270
+ sequence_length = sequence.shape[1]
1271
+ indices = [lag - shift for lag in self.config.lags_sequence]
1272
+
1273
+ if max(indices) + subsequences_length > sequence_length:
1274
+ raise ValueError(
1275
+ f"lags cannot go further than history length, found lag {max(indices)} "
1276
+ f"while history length is only {sequence_length}"
1277
+ )
1278
+
1279
+ lagged_values = []
1280
+ for lag_index in indices:
1281
+ begin_index = -lag_index - subsequences_length
1282
+ end_index = -lag_index if lag_index > 0 else None
1283
+ lagged_values.append(sequence[:, begin_index:end_index, ...])
1284
+ return torch.stack(lagged_values, dim=-1)
1285
+
1286
+ def create_network_inputs(
1287
+ self,
1288
+ past_values: torch.Tensor,
1289
+ past_time_features: torch.Tensor,
1290
+ static_categorical_features: Optional[torch.Tensor] = None,
1291
+ static_real_features: Optional[torch.Tensor] = None,
1292
+ past_observed_mask: Optional[torch.Tensor] = None,
1293
+ future_values: Optional[torch.Tensor] = None,
1294
+ future_time_features: Optional[torch.Tensor] = None,
1295
+ ):
1296
+ # time feature
1297
+ time_feat = (
1298
+ torch.cat(
1299
+ (
1300
+ past_time_features[:, self._past_length - self.config.context_length :, ...],
1301
+ future_time_features,
1302
+ ),
1303
+ dim=1,
1304
+ )
1305
+ if future_values is not None
1306
+ else past_time_features[:, self._past_length - self.config.context_length :, ...]
1307
+ )
1308
+
1309
+ # target
1310
+ if past_observed_mask is None:
1311
+ past_observed_mask = torch.ones_like(past_values)
1312
+
1313
+ context = past_values[:, -self.config.context_length :]
1314
+ observed_context = past_observed_mask[:, -self.config.context_length :]
1315
+ _, loc, scale = self.scaler(context, observed_context)
1316
+
1317
+ inputs = (
1318
+ (torch.cat((past_values, future_values), dim=1) - loc) / scale
1319
+ if future_values is not None
1320
+ else (past_values - loc) / scale
1321
+ )
1322
+
1323
+ # static features
1324
+ log_abs_loc = loc.abs().log1p() if self.config.input_size == 1 else loc.squeeze(1).abs().log1p()
1325
+ log_scale = scale.log() if self.config.input_size == 1 else scale.squeeze(1).log()
1326
+ static_feat = torch.cat((log_abs_loc, log_scale), dim=1)
1327
+
1328
+ if static_real_features is not None:
1329
+ static_feat = torch.cat((static_real_features, static_feat), dim=1)
1330
+ if static_categorical_features is not None:
1331
+ embedded_cat = self.embedder(static_categorical_features)
1332
+ static_feat = torch.cat((embedded_cat, static_feat), dim=1)
1333
+ expanded_static_feat = static_feat.unsqueeze(1).expand(-1, time_feat.shape[1], -1)
1334
+
1335
+ # all features
1336
+ features = torch.cat((expanded_static_feat, time_feat), dim=-1)
1337
+
1338
+ # lagged features
1339
+ subsequences_length = (
1340
+ self.config.context_length + self.config.prediction_length
1341
+ if future_values is not None
1342
+ else self.config.context_length
1343
+ )
1344
+ lagged_sequence = self.get_lagged_subsequences(sequence=inputs, subsequences_length=subsequences_length)
1345
+ lags_shape = lagged_sequence.shape
1346
+ reshaped_lagged_sequence = lagged_sequence.reshape(lags_shape[0], lags_shape[1], -1)
1347
+
1348
+ if reshaped_lagged_sequence.shape[1] != time_feat.shape[1]:
1349
+ raise ValueError(
1350
+ f"input length {reshaped_lagged_sequence.shape[1]} and time feature lengths {time_feat.shape[1]} does not match"
1351
+ )
1352
+
1353
+ # transformer inputs
1354
+ transformer_inputs = torch.cat((reshaped_lagged_sequence, features), dim=-1)
1355
+
1356
+ return transformer_inputs, loc, scale, static_feat
1357
+
1358
+ def get_encoder(self):
1359
+ return self.encoder
1360
+
1361
+ def get_decoder(self):
1362
+ return self.decoder
1363
+
1364
+ @add_start_docstrings_to_model_forward(TIME_SERIES_TRANSFORMER_INPUTS_DOCSTRING)
1365
+ @replace_return_docstrings(output_type=Seq2SeqTSModelOutput, config_class=_CONFIG_FOR_DOC)
1366
+ def forward(
1367
+ self,
1368
+ past_values: torch.Tensor,
1369
+ past_time_features: torch.Tensor,
1370
+ past_observed_mask: torch.Tensor,
1371
+ static_categorical_features: Optional[torch.Tensor] = None,
1372
+ static_real_features: Optional[torch.Tensor] = None,
1373
+ future_values: Optional[torch.Tensor] = None,
1374
+ future_time_features: Optional[torch.Tensor] = None,
1375
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1376
+ head_mask: Optional[torch.Tensor] = None,
1377
+ decoder_head_mask: Optional[torch.Tensor] = None,
1378
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1379
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1380
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1381
+ output_hidden_states: Optional[bool] = None,
1382
+ output_attentions: Optional[bool] = None,
1383
+ use_cache: Optional[bool] = None,
1384
+ return_dict: Optional[bool] = None,
1385
+ ) -> Union[Seq2SeqTSModelOutput, Tuple]:
1386
+ r"""
1387
+ Returns:
1388
+
1389
+ Examples:
1390
+
1391
+ ```python
1392
+ >>> from huggingface_hub import hf_hub_download
1393
+ >>> import torch
1394
+ >>> from transformers import TimeSeriesTransformerModel
1395
+
1396
+ >>> file = hf_hub_download(
1397
+ ... repo_id="kashif/tourism-monthly-batch", filename="train-batch.pt", repo_type="dataset"
1398
+ ... )
1399
+ >>> batch = torch.load(file)
1400
+
1401
+ >>> model = TimeSeriesTransformerModel.from_pretrained("huggingface/time-series-transformer-tourism-monthly")
1402
+
1403
+ >>> # during training, one provides both past and future values
1404
+ >>> # as well as possible additional features
1405
+ >>> outputs = model(
1406
+ ... past_values=batch["past_values"],
1407
+ ... past_time_features=batch["past_time_features"],
1408
+ ... past_observed_mask=batch["past_observed_mask"],
1409
+ ... static_categorical_features=batch["static_categorical_features"],
1410
+ ... static_real_features=batch["static_real_features"],
1411
+ ... future_values=batch["future_values"],
1412
+ ... future_time_features=batch["future_time_features"],
1413
+ ... )
1414
+
1415
+ >>> last_hidden_state = outputs.last_hidden_state
1416
+ ```"""
1417
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1418
+ output_hidden_states = (
1419
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1420
+ )
1421
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1422
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1423
+
1424
+ transformer_inputs, loc, scale, static_feat = self.create_network_inputs(
1425
+ past_values=past_values,
1426
+ past_time_features=past_time_features,
1427
+ past_observed_mask=past_observed_mask,
1428
+ static_categorical_features=static_categorical_features,
1429
+ static_real_features=static_real_features,
1430
+ future_values=future_values,
1431
+ future_time_features=future_time_features,
1432
+ )
1433
+
1434
+ if encoder_outputs is None:
1435
+ enc_input = transformer_inputs[:, : self.config.context_length, ...]
1436
+ encoder_outputs = self.encoder(
1437
+ inputs_embeds=enc_input,
1438
+ head_mask=head_mask,
1439
+ output_attentions=output_attentions,
1440
+ output_hidden_states=output_hidden_states,
1441
+ return_dict=return_dict,
1442
+ )
1443
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1444
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1445
+ encoder_outputs = BaseModelOutput(
1446
+ last_hidden_state=encoder_outputs[0],
1447
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1448
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1449
+ )
1450
+
1451
+ dec_input = transformer_inputs[:, self.config.context_length :, ...]
1452
+ decoder_outputs = self.decoder(
1453
+ inputs_embeds=dec_input,
1454
+ attention_mask=decoder_attention_mask,
1455
+ encoder_hidden_states=encoder_outputs[0],
1456
+ head_mask=decoder_head_mask,
1457
+ cross_attn_head_mask=cross_attn_head_mask,
1458
+ past_key_values=past_key_values,
1459
+ use_cache=use_cache,
1460
+ output_attentions=output_attentions,
1461
+ output_hidden_states=output_hidden_states,
1462
+ return_dict=return_dict,
1463
+ )
1464
+
1465
+ if not return_dict:
1466
+ return decoder_outputs + encoder_outputs + (loc, scale, static_feat)
1467
+
1468
+ return Seq2SeqTSModelOutput(
1469
+ last_hidden_state=decoder_outputs.last_hidden_state,
1470
+ past_key_values=decoder_outputs.past_key_values,
1471
+ decoder_hidden_states=decoder_outputs.hidden_states,
1472
+ decoder_attentions=decoder_outputs.attentions,
1473
+ cross_attentions=decoder_outputs.cross_attentions,
1474
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1475
+ encoder_hidden_states=encoder_outputs.hidden_states,
1476
+ encoder_attentions=encoder_outputs.attentions,
1477
+ loc=loc,
1478
+ scale=scale,
1479
+ static_features=static_feat,
1480
+ )
1481
+
1482
+
1483
+ @add_start_docstrings(
1484
+ "The Time Series Transformer Model with a distribution head on top for time-series forecasting.",
1485
+ TIME_SERIES_TRANSFORMER_START_DOCSTRING,
1486
+ )
1487
+ class TimeSeriesTransformerForPrediction(TimeSeriesTransformerPreTrainedModel):
1488
+ def __init__(self, config: TimeSeriesTransformerConfig):
1489
+ super().__init__(config)
1490
+ self.model = TimeSeriesTransformerModel(config)
1491
+ if config.distribution_output == "student_t":
1492
+ self.distribution_output = StudentTOutput(dim=config.input_size)
1493
+ elif config.distribution_output == "normal":
1494
+ self.distribution_output = NormalOutput(dim=config.input_size)
1495
+ elif config.distribution_output == "negative_binomial":
1496
+ self.distribution_output = NegativeBinomialOutput(dim=config.input_size)
1497
+ else:
1498
+ raise ValueError(f"Unknown distribution output {config.distribution_output}")
1499
+
1500
+ self.parameter_projection = self.distribution_output.get_parameter_projection(self.model.config.d_model)
1501
+ self.target_shape = self.distribution_output.event_shape
1502
+
1503
+ if config.loss == "nll":
1504
+ self.loss = nll
1505
+ else:
1506
+ raise ValueError(f"Unknown loss function {config.loss}")
1507
+
1508
+ # Initialize weights of distribution_output and apply final processing
1509
+ self.post_init()
1510
+
1511
+ def output_params(self, dec_output):
1512
+ return self.parameter_projection(dec_output)
1513
+
1514
+ def get_encoder(self):
1515
+ return self.model.get_encoder()
1516
+
1517
+ def get_decoder(self):
1518
+ return self.model.get_decoder()
1519
+
1520
+ @torch.jit.ignore
1521
+ def output_distribution(self, params, loc=None, scale=None, trailing_n=None) -> torch.distributions.Distribution:
1522
+ sliced_params = params
1523
+ if trailing_n is not None:
1524
+ sliced_params = [p[:, -trailing_n:] for p in params]
1525
+ return self.distribution_output.distribution(sliced_params, loc=loc, scale=scale)
1526
+
1527
+ @add_start_docstrings_to_model_forward(TIME_SERIES_TRANSFORMER_INPUTS_DOCSTRING)
1528
+ @replace_return_docstrings(output_type=Seq2SeqTSModelOutput, config_class=_CONFIG_FOR_DOC)
1529
+ def forward(
1530
+ self,
1531
+ past_values: torch.Tensor,
1532
+ past_time_features: torch.Tensor,
1533
+ past_observed_mask: torch.Tensor,
1534
+ static_categorical_features: Optional[torch.Tensor] = None,
1535
+ static_real_features: Optional[torch.Tensor] = None,
1536
+ future_values: Optional[torch.Tensor] = None,
1537
+ future_time_features: Optional[torch.Tensor] = None,
1538
+ future_observed_mask: Optional[torch.Tensor] = None,
1539
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1540
+ head_mask: Optional[torch.Tensor] = None,
1541
+ decoder_head_mask: Optional[torch.Tensor] = None,
1542
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1543
+ encoder_outputs: Optional[List[torch.FloatTensor]] = None,
1544
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1545
+ output_hidden_states: Optional[bool] = None,
1546
+ output_attentions: Optional[bool] = None,
1547
+ use_cache: Optional[bool] = None,
1548
+ return_dict: Optional[bool] = None,
1549
+ ) -> Union[Seq2SeqTSModelOutput, Tuple]:
1550
+ r"""
1551
+ Returns:
1552
+
1553
+ Examples:
1554
+
1555
+ ```python
1556
+ >>> from huggingface_hub import hf_hub_download
1557
+ >>> import torch
1558
+ >>> from transformers import TimeSeriesTransformerForPrediction
1559
+
1560
+ >>> file = hf_hub_download(
1561
+ ... repo_id="kashif/tourism-monthly-batch", filename="train-batch.pt", repo_type="dataset"
1562
+ ... )
1563
+ >>> batch = torch.load(file)
1564
+
1565
+ >>> model = TimeSeriesTransformerForPrediction.from_pretrained(
1566
+ ... "huggingface/time-series-transformer-tourism-monthly"
1567
+ ... )
1568
+
1569
+ >>> # during training, one provides both past and future values
1570
+ >>> # as well as possible additional features
1571
+ >>> outputs = model(
1572
+ ... past_values=batch["past_values"],
1573
+ ... past_time_features=batch["past_time_features"],
1574
+ ... past_observed_mask=batch["past_observed_mask"],
1575
+ ... static_categorical_features=batch["static_categorical_features"],
1576
+ ... static_real_features=batch["static_real_features"],
1577
+ ... future_values=batch["future_values"],
1578
+ ... future_time_features=batch["future_time_features"],
1579
+ ... )
1580
+
1581
+ >>> loss = outputs.loss
1582
+ >>> loss.backward()
1583
+
1584
+ >>> # during inference, one only provides past values
1585
+ >>> # as well as possible additional features
1586
+ >>> # the model autoregressively generates future values
1587
+ >>> outputs = model.generate(
1588
+ ... past_values=batch["past_values"],
1589
+ ... past_time_features=batch["past_time_features"],
1590
+ ... past_observed_mask=batch["past_observed_mask"],
1591
+ ... static_categorical_features=batch["static_categorical_features"],
1592
+ ... static_real_features=batch["static_real_features"],
1593
+ ... future_time_features=batch["future_time_features"],
1594
+ ... )
1595
+
1596
+ >>> mean_prediction = outputs.sequences.mean(dim=1)
1597
+ ```"""
1598
+
1599
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1600
+ if future_values is not None:
1601
+ use_cache = False
1602
+
1603
+ outputs = self.model(
1604
+ past_values=past_values,
1605
+ past_time_features=past_time_features,
1606
+ past_observed_mask=past_observed_mask,
1607
+ static_categorical_features=static_categorical_features,
1608
+ static_real_features=static_real_features,
1609
+ future_values=future_values,
1610
+ future_time_features=future_time_features,
1611
+ decoder_attention_mask=decoder_attention_mask,
1612
+ head_mask=head_mask,
1613
+ decoder_head_mask=decoder_head_mask,
1614
+ cross_attn_head_mask=cross_attn_head_mask,
1615
+ encoder_outputs=encoder_outputs,
1616
+ past_key_values=past_key_values,
1617
+ output_hidden_states=output_hidden_states,
1618
+ output_attentions=output_attentions,
1619
+ use_cache=use_cache,
1620
+ return_dict=return_dict,
1621
+ )
1622
+
1623
+ prediction_loss = None
1624
+ params = None
1625
+ if future_values is not None:
1626
+ params = self.output_params(outputs[0]) # outputs.last_hidden_state
1627
+ # loc is 3rd last and scale is 2nd last output
1628
+ distribution = self.output_distribution(params, loc=outputs[-3], scale=outputs[-2])
1629
+
1630
+ loss = self.loss(distribution, future_values)
1631
+
1632
+ if future_observed_mask is None:
1633
+ future_observed_mask = torch.ones_like(future_values)
1634
+
1635
+ if len(self.target_shape) == 0:
1636
+ loss_weights = future_observed_mask
1637
+ else:
1638
+ loss_weights, _ = future_observed_mask.min(dim=-1, keepdim=False)
1639
+
1640
+ prediction_loss = weighted_average(loss, weights=loss_weights)
1641
+
1642
+ if not return_dict:
1643
+ outputs = ((params,) + outputs[1:]) if params is not None else outputs[1:]
1644
+ return ((prediction_loss,) + outputs) if prediction_loss is not None else outputs
1645
+
1646
+ return Seq2SeqTSPredictionOutput(
1647
+ loss=prediction_loss,
1648
+ params=params,
1649
+ past_key_values=outputs.past_key_values,
1650
+ decoder_hidden_states=outputs.decoder_hidden_states,
1651
+ decoder_attentions=outputs.decoder_attentions,
1652
+ cross_attentions=outputs.cross_attentions,
1653
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1654
+ encoder_hidden_states=outputs.encoder_hidden_states,
1655
+ encoder_attentions=outputs.encoder_attentions,
1656
+ loc=outputs.loc,
1657
+ scale=outputs.scale,
1658
+ static_features=outputs.static_features,
1659
+ )
1660
+
1661
+ @torch.no_grad()
1662
+ def generate(
1663
+ self,
1664
+ past_values: torch.Tensor,
1665
+ past_time_features: torch.Tensor,
1666
+ future_time_features: torch.Tensor,
1667
+ past_observed_mask: Optional[torch.Tensor] = None,
1668
+ static_categorical_features: Optional[torch.Tensor] = None,
1669
+ static_real_features: Optional[torch.Tensor] = None,
1670
+ output_attentions: Optional[bool] = None,
1671
+ output_hidden_states: Optional[bool] = None,
1672
+ ) -> SampleTSPredictionOutput:
1673
+ r"""
1674
+ Greedily generate sequences of sample predictions from a model with a probability distribution head.
1675
+
1676
+ Parameters:
1677
+ past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`):
1678
+ Past values of the time series, that serve as context in order to predict the future. The sequence size
1679
+ of this tensor must be larger than the `context_length` of the model, since the model will use the
1680
+ larger size to construct lag features, i.e. additional values from the past which are added in order to
1681
+ serve as "extra context".
1682
+
1683
+ The `sequence_length` here is equal to `config.context_length` + `max(config.lags_sequence)`, which if
1684
+ no `lags_sequence` is configured, is equal to `config.context_length` + 7 (as by default, the largest
1685
+ look-back index in `config.lags_sequence` is 7). The property `_past_length` returns the actual length
1686
+ of the past.
1687
+
1688
+ The `past_values` is what the Transformer encoder gets as input (with optional additional features,
1689
+ such as `static_categorical_features`, `static_real_features`, `past_time_features` and lags).
1690
+
1691
+ Optionally, missing values need to be replaced with zeros and indicated via the `past_observed_mask`.
1692
+
1693
+ For multivariate time series, the `input_size` > 1 dimension is required and corresponds to the number
1694
+ of variates in the time series per time step.
1695
+ past_time_features (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_features)`):
1696
+ Required time features, which the model internally will add to `past_values`. These could be things
1697
+ like "month of year", "day of the month", etc. encoded as vectors (for instance as Fourier features).
1698
+ These could also be so-called "age" features, which basically help the model know "at which point in
1699
+ life" a time-series is. Age features have small values for distant past time steps and increase
1700
+ monotonically the more we approach the current time step. Holiday features are also a good example of
1701
+ time features.
1702
+
1703
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT,
1704
+ where the position encodings are learned from scratch internally as parameters of the model, the Time
1705
+ Series Transformer requires to provide additional time features. The Time Series Transformer only
1706
+ learns additional embeddings for `static_categorical_features`.
1707
+
1708
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these
1709
+ features must but known at prediction time.
1710
+
1711
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
1712
+ future_time_features (`torch.FloatTensor` of shape `(batch_size, prediction_length, num_features)`):
1713
+ Required time features for the prediction window, which the model internally will add to sampled
1714
+ predictions. These could be things like "month of year", "day of the month", etc. encoded as vectors
1715
+ (for instance as Fourier features). These could also be so-called "age" features, which basically help
1716
+ the model know "at which point in life" a time-series is. Age features have small values for distant
1717
+ past time steps and increase monotonically the more we approach the current time step. Holiday features
1718
+ are also a good example of time features.
1719
+
1720
+ These features serve as the "positional encodings" of the inputs. So contrary to a model like BERT,
1721
+ where the position encodings are learned from scratch internally as parameters of the model, the Time
1722
+ Series Transformer requires to provide additional time features. The Time Series Transformer only
1723
+ learns additional embeddings for `static_categorical_features`.
1724
+
1725
+ Additional dynamic real covariates can be concatenated to this tensor, with the caveat that these
1726
+ features must but known at prediction time.
1727
+
1728
+ The `num_features` here is equal to `config.`num_time_features` + `config.num_dynamic_real_features`.
1729
+ past_observed_mask (`torch.BoolTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`, *optional*):
1730
+ Boolean mask to indicate which `past_values` were observed and which were missing. Mask values selected
1731
+ in `[0, 1]`:
1732
+
1733
+ - 1 for values that are **observed**,
1734
+ - 0 for values that are **missing** (i.e. NaNs that were replaced by zeros).
1735
+
1736
+ static_categorical_features (`torch.LongTensor` of shape `(batch_size, number of static categorical features)`, *optional*):
1737
+ Optional static categorical features for which the model will learn an embedding, which it will add to
1738
+ the values of the time series.
1739
+
1740
+ Static categorical features are features which have the same value for all time steps (static over
1741
+ time).
1742
+
1743
+ A typical example of a static categorical feature is a time series ID.
1744
+ static_real_features (`torch.FloatTensor` of shape `(batch_size, number of static real features)`, *optional*):
1745
+ Optional static real features which the model will add to the values of the time series.
1746
+
1747
+ Static real features are features which have the same value for all time steps (static over time).
1748
+
1749
+ A typical example of a static real feature is promotion information.
1750
+ output_attentions (`bool`, *optional*):
1751
+ Whether or not to return the attentions tensors of all attention layers.
1752
+ output_hidden_states (`bool`, *optional*):
1753
+ Whether or not to return the hidden states of all layers.
1754
+
1755
+ Return:
1756
+ [`SampleTSPredictionOutput`] where the outputs `sequences` tensor will have shape `(batch_size, number of
1757
+ samples, prediction_length)` or `(batch_size, number of samples, prediction_length, input_size)` for
1758
+ multivariate predictions.
1759
+ """
1760
+ outputs = self(
1761
+ static_categorical_features=static_categorical_features,
1762
+ static_real_features=static_real_features,
1763
+ past_time_features=past_time_features,
1764
+ past_values=past_values,
1765
+ past_observed_mask=past_observed_mask,
1766
+ future_time_features=future_time_features,
1767
+ future_values=None,
1768
+ output_attentions=output_attentions,
1769
+ output_hidden_states=output_hidden_states,
1770
+ return_dict=True,
1771
+ use_cache=True,
1772
+ )
1773
+
1774
+ decoder = self.model.get_decoder()
1775
+ enc_last_hidden = outputs.encoder_last_hidden_state
1776
+ loc = outputs.loc
1777
+ scale = outputs.scale
1778
+ static_feat = outputs.static_features
1779
+
1780
+ num_parallel_samples = self.config.num_parallel_samples
1781
+ repeated_loc = loc.repeat_interleave(repeats=num_parallel_samples, dim=0)
1782
+ repeated_scale = scale.repeat_interleave(repeats=num_parallel_samples, dim=0)
1783
+
1784
+ repeated_past_values = (
1785
+ past_values.repeat_interleave(repeats=num_parallel_samples, dim=0) - repeated_loc
1786
+ ) / repeated_scale
1787
+
1788
+ expanded_static_feat = static_feat.unsqueeze(1).expand(-1, future_time_features.shape[1], -1)
1789
+ features = torch.cat((expanded_static_feat, future_time_features), dim=-1)
1790
+ repeated_features = features.repeat_interleave(repeats=num_parallel_samples, dim=0)
1791
+
1792
+ repeated_enc_last_hidden = enc_last_hidden.repeat_interleave(repeats=num_parallel_samples, dim=0)
1793
+
1794
+ future_samples = []
1795
+
1796
+ # greedy decoding
1797
+ for k in range(self.config.prediction_length):
1798
+ lagged_sequence = self.model.get_lagged_subsequences(
1799
+ sequence=repeated_past_values,
1800
+ subsequences_length=1 + k,
1801
+ shift=1,
1802
+ )
1803
+
1804
+ lags_shape = lagged_sequence.shape
1805
+ reshaped_lagged_sequence = lagged_sequence.reshape(lags_shape[0], lags_shape[1], -1)
1806
+
1807
+ decoder_input = torch.cat((reshaped_lagged_sequence, repeated_features[:, : k + 1]), dim=-1)
1808
+
1809
+ dec_output = decoder(inputs_embeds=decoder_input, encoder_hidden_states=repeated_enc_last_hidden)
1810
+ dec_last_hidden = dec_output.last_hidden_state
1811
+
1812
+ params = self.parameter_projection(dec_last_hidden[:, -1:])
1813
+ distr = self.output_distribution(params, loc=repeated_loc, scale=repeated_scale)
1814
+ next_sample = distr.sample()
1815
+
1816
+ repeated_past_values = torch.cat(
1817
+ (repeated_past_values, (next_sample - repeated_loc) / repeated_scale), dim=1
1818
+ )
1819
+ future_samples.append(next_sample)
1820
+
1821
+ concat_future_samples = torch.cat(future_samples, dim=1)
1822
+
1823
+ return SampleTSPredictionOutput(
1824
+ sequences=concat_future_samples.reshape(
1825
+ (-1, num_parallel_samples, self.config.prediction_length) + self.target_shape,
1826
+ )
1827
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/timesformer/__init__.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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 OptionalDependencyNotAvailable, _LazyModule, is_torch_available
17
+
18
+
19
+ _import_structure = {
20
+ "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"],
21
+ }
22
+
23
+ try:
24
+ if not is_torch_available():
25
+ raise OptionalDependencyNotAvailable()
26
+ except OptionalDependencyNotAvailable:
27
+ pass
28
+ else:
29
+ _import_structure["modeling_timesformer"] = [
30
+ "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
31
+ "TimesformerModel",
32
+ "TimesformerForVideoClassification",
33
+ "TimesformerPreTrainedModel",
34
+ ]
35
+
36
+ if TYPE_CHECKING:
37
+ from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig
38
+
39
+ try:
40
+ if not is_torch_available():
41
+ raise OptionalDependencyNotAvailable()
42
+ except OptionalDependencyNotAvailable:
43
+ pass
44
+ else:
45
+ from .modeling_timesformer import (
46
+ TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
47
+ TimesformerForVideoClassification,
48
+ TimesformerModel,
49
+ TimesformerPreTrainedModel,
50
+ )
51
+
52
+ else:
53
+ import sys
54
+
55
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/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
+ TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "facebook/timesformer": "https://huggingface.co/facebook/timesformer/resolve/main/config.json",
25
+ }
26
+
27
+
28
+ class TimesformerConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`TimesformerModel`]. It is used to instantiate a
31
+ TimeSformer model according to the specified arguments, defining the model architecture. Instantiating a
32
+ configuration with the defaults will yield a similar configuration to that of the TimeSformer
33
+ [facebook/timesformer-base-finetuned-k600](https://huggingface.co/facebook/timesformer-base-finetuned-k600)
34
+ architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+ Args:
40
+ image_size (`int`, *optional*, defaults to 224):
41
+ The size (resolution) of each image.
42
+ patch_size (`int`, *optional*, defaults to 16):
43
+ The size (resolution) of each patch.
44
+ num_channels (`int`, *optional*, defaults to 3):
45
+ The number of input channels.
46
+ num_frames (`int`, *optional*, defaults to 8):
47
+ The number of frames in each video.
48
+ hidden_size (`int`, *optional*, defaults to 768):
49
+ Dimensionality of the encoder layers and the pooler layer.
50
+ num_hidden_layers (`int`, *optional*, defaults to 12):
51
+ Number of hidden layers in the Transformer encoder.
52
+ num_attention_heads (`int`, *optional*, defaults to 12):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ intermediate_size (`int`, *optional*, defaults to 3072):
55
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
57
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
58
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
59
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
60
+ The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
61
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
62
+ The dropout ratio for the attention probabilities.
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
66
+ The epsilon used by the layer normalization layers.
67
+ qkv_bias (`bool`, *optional*, defaults to `True`):
68
+ Whether to add a bias to the queries, keys and values.
69
+ attention_type (`str`, *optional*, defaults to `"divided_space_time"`):
70
+ The attention type to use. Must be one of `"divided_space_time"`, `"space_only"`, `"joint_space_time"`.
71
+ drop_path_rate (`float`, *optional*, defaults to 0):
72
+ The dropout ratio for stochastic depth.
73
+
74
+ Example:
75
+
76
+ ```python
77
+ >>> from transformers import TimesformerConfig, TimesformerModel
78
+
79
+ >>> # Initializing a TimeSformer timesformer-base style configuration
80
+ >>> configuration = TimesformerConfig()
81
+
82
+ >>> # Initializing a model from the configuration
83
+ >>> model = TimesformerModel(configuration)
84
+
85
+ >>> # Accessing the model configuration
86
+ >>> configuration = model.config
87
+ ```"""
88
+ model_type = "timesformer"
89
+
90
+ def __init__(
91
+ self,
92
+ image_size=224,
93
+ patch_size=16,
94
+ num_channels=3,
95
+ num_frames=8,
96
+ hidden_size=768,
97
+ num_hidden_layers=12,
98
+ num_attention_heads=12,
99
+ intermediate_size=3072,
100
+ hidden_act="gelu",
101
+ hidden_dropout_prob=0.0,
102
+ attention_probs_dropout_prob=0.0,
103
+ initializer_range=0.02,
104
+ layer_norm_eps=1e-6,
105
+ qkv_bias=True,
106
+ attention_type="divided_space_time",
107
+ drop_path_rate=0,
108
+ **kwargs,
109
+ ):
110
+ super().__init__(**kwargs)
111
+
112
+ self.image_size = image_size
113
+ self.patch_size = patch_size
114
+ self.num_channels = num_channels
115
+ self.num_frames = num_frames
116
+
117
+ self.hidden_size = hidden_size
118
+ self.num_hidden_layers = num_hidden_layers
119
+ self.num_attention_heads = num_attention_heads
120
+ self.intermediate_size = intermediate_size
121
+ self.hidden_act = hidden_act
122
+ self.hidden_dropout_prob = hidden_dropout_prob
123
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
124
+ self.initializer_range = initializer_range
125
+ self.layer_norm_eps = layer_norm_eps
126
+ self.qkv_bias = qkv_bias
127
+
128
+ self.attention_type = attention_type
129
+ self.drop_path_rate = drop_path_rate
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/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, VideoMAEFeatureExtractor
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
+ feature_extractor = VideoMAEFeatureExtractor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5])
160
+ video = prepare_video()
161
+ inputs = feature_extractor(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 feature extractor to {pytorch_dump_folder_path}")
219
+ feature_extractor.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
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/timesformer/modeling_timesformer.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ import collections
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn.functional
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
31
+ from .configuration_timesformer import TimesformerConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ _CONFIG_FOR_DOC = "TimesformerConfig"
37
+ _CHECKPOINT_FOR_DOC = "facebook/timesformer"
38
+
39
+ TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
40
+ "facebook/timesformer-base-finetuned-k400",
41
+ # See all TimeSformer models at https://huggingface.co/models?filter=timesformer
42
+ ]
43
+
44
+
45
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L155
46
+ class TimesformerPatchEmbeddings(nn.Module):
47
+ """Image to Patch Embedding"""
48
+
49
+ def __init__(self, config):
50
+ super().__init__()
51
+
52
+ image_size = config.image_size
53
+ patch_size = config.patch_size
54
+
55
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
56
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
57
+
58
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
59
+ self.image_size = image_size
60
+ self.patch_size = patch_size
61
+ self.num_patches = num_patches
62
+
63
+ self.projection = nn.Conv2d(config.num_channels, config.hidden_size, kernel_size=patch_size, stride=patch_size)
64
+
65
+ def forward(self, pixel_values):
66
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
67
+ pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
68
+
69
+ embeddings = self.projection(pixel_values)
70
+ patch_width = embeddings.size(-1)
71
+ embeddings = embeddings.flatten(2).transpose(1, 2)
72
+ return embeddings, num_frames, patch_width
73
+
74
+
75
+ class TimesformerEmbeddings(nn.Module):
76
+ """
77
+ Construct the patch and position embeddings.
78
+ """
79
+
80
+ def __init__(self, config):
81
+ super().__init__()
82
+
83
+ embed_dim = config.hidden_size
84
+ num_frames = config.num_frames
85
+ drop_rate = config.hidden_dropout_prob
86
+ attention_type = config.attention_type
87
+
88
+ self.attention_type = attention_type
89
+ self.patch_embeddings = TimesformerPatchEmbeddings(config)
90
+ self.num_patches = self.patch_embeddings.num_patches
91
+
92
+ # Positional Embeddings
93
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
94
+ self.position_embeddings = nn.Parameter(torch.zeros(1, self.num_patches + 1, embed_dim))
95
+ self.pos_drop = nn.Dropout(p=drop_rate)
96
+ if attention_type != "space_only":
97
+ self.time_embeddings = nn.Parameter(torch.zeros(1, num_frames, embed_dim))
98
+ self.time_drop = nn.Dropout(p=drop_rate)
99
+
100
+ def forward(self, pixel_values):
101
+ batch_size = pixel_values.shape[0]
102
+
103
+ # create patch embeddings
104
+ embeddings, num_frames, patch_width = self.patch_embeddings(pixel_values)
105
+
106
+ cls_tokens = self.cls_token.expand(embeddings.size(0), -1, -1)
107
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
108
+
109
+ # resizing the positional embeddings in case they don't match the input at inference
110
+ if embeddings.size(1) != self.position_embeddings.size(1):
111
+ position_embeddings = self.position_embeddings
112
+ cls_pos_embed = position_embeddings[0, 0, :].unsqueeze(0).unsqueeze(1)
113
+ other_pos_embed = position_embeddings[0, 1:, :].unsqueeze(0).transpose(1, 2)
114
+ patch_num = int(other_pos_embed.size(2) ** 0.5)
115
+ patch_height = embeddings.size(1) // patch_width
116
+ other_pos_embed = other_pos_embed.reshape(1, embeddings.size(2), patch_num, patch_num)
117
+ new_pos_embed = nn.functional.interpolate(
118
+ other_pos_embed, size=(patch_height, patch_width), mode="nearest"
119
+ )
120
+ new_pos_embed = new_pos_embed.flatten(2)
121
+ new_pos_embed = new_pos_embed.transpose(1, 2)
122
+ new_pos_embed = torch.cat((cls_pos_embed, new_pos_embed), 1)
123
+ embeddings = embeddings + new_pos_embed
124
+ else:
125
+ embeddings = embeddings + self.position_embeddings
126
+ embeddings = self.pos_drop(embeddings)
127
+
128
+ # Time Embeddings
129
+ if self.attention_type != "space_only":
130
+ cls_tokens = embeddings[:batch_size, 0, :].unsqueeze(1)
131
+ embeddings = embeddings[:, 1:]
132
+ _, patch_height, patch_width = embeddings.shape
133
+ embeddings = (
134
+ embeddings.reshape(batch_size, num_frames, patch_height, patch_width)
135
+ .permute(0, 2, 1, 3)
136
+ .reshape(batch_size * patch_height, num_frames, patch_width)
137
+ )
138
+ # Resizing time embeddings in case they don't match
139
+ if num_frames != self.time_embeddings.size(1):
140
+ time_embeddings = self.time_embeddings.transpose(1, 2)
141
+ new_time_embeddings = nn.functional.interpolate(time_embeddings, size=(num_frames), mode="nearest")
142
+ new_time_embeddings = new_time_embeddings.transpose(1, 2)
143
+ embeddings = embeddings + new_time_embeddings
144
+ else:
145
+ embeddings = embeddings + self.time_embeddings
146
+ embeddings = self.time_drop(embeddings)
147
+ embeddings = embeddings.view(batch_size, patch_height, num_frames, patch_width).reshape(
148
+ batch_size, patch_height * num_frames, patch_width
149
+ )
150
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
151
+
152
+ return embeddings
153
+
154
+
155
+ # Copied from transformers.models.beit.modeling_beit.drop_path
156
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
157
+ """
158
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
159
+
160
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
161
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
162
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
163
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
164
+ argument.
165
+ """
166
+ if drop_prob == 0.0 or not training:
167
+ return input
168
+ keep_prob = 1 - drop_prob
169
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
170
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
171
+ random_tensor.floor_() # binarize
172
+ output = input.div(keep_prob) * random_tensor
173
+ return output
174
+
175
+
176
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->TimeSformer
177
+ class TimeSformerDropPath(nn.Module):
178
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
179
+
180
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
181
+ super().__init__()
182
+ self.drop_prob = drop_prob
183
+
184
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
185
+ return drop_path(hidden_states, self.drop_prob, self.training)
186
+
187
+ def extra_repr(self) -> str:
188
+ return "p={}".format(self.drop_prob)
189
+
190
+
191
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L57
192
+ class TimesformerSelfAttention(nn.Module):
193
+ def __init__(self, config: TimesformerConfig):
194
+ super().__init__()
195
+
196
+ num_heads = config.num_attention_heads
197
+ qkv_bias = config.qkv_bias
198
+ attention_dropout_prob = config.attention_probs_dropout_prob
199
+
200
+ self.num_heads = num_heads
201
+ head_dim = config.hidden_size // num_heads
202
+ self.scale = head_dim**-0.5
203
+ self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=qkv_bias)
204
+ self.attn_drop = nn.Dropout(attention_dropout_prob)
205
+
206
+ def forward(self, hidden_states, output_attentions: bool = False):
207
+ batch_size, hidden_size, num_channels = hidden_states.shape
208
+ qkv = (
209
+ self.qkv(hidden_states)
210
+ .reshape(batch_size, hidden_size, 3, self.num_heads, num_channels // self.num_heads)
211
+ .permute(2, 0, 3, 1, 4)
212
+ )
213
+ query, key, value = qkv[0], qkv[1], qkv[2]
214
+
215
+ attention_probs = (query @ key.transpose(-2, -1)) * self.scale
216
+ attention_probs = attention_probs.softmax(dim=-1)
217
+ attention_probs = self.attn_drop(attention_probs)
218
+
219
+ context_layer = (attention_probs @ value).transpose(1, 2).reshape(batch_size, hidden_size, num_channels)
220
+
221
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
222
+
223
+ return outputs
224
+
225
+
226
+ class TimesformerSelfOutput(nn.Module):
227
+ """
228
+ The residual connection is defined in TimesformerLayer instead of here (as is the case with other models), due to
229
+ the layernorm applied before each block.
230
+ """
231
+
232
+ def __init__(self, config: TimesformerConfig) -> None:
233
+ super().__init__()
234
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
235
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
236
+
237
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
238
+ hidden_states = self.dense(hidden_states)
239
+ hidden_states = self.dropout(hidden_states)
240
+
241
+ return hidden_states
242
+
243
+
244
+ class TimeSformerAttention(nn.Module):
245
+ def __init__(self, config: TimesformerConfig) -> None:
246
+ super().__init__()
247
+ self.attention = TimesformerSelfAttention(config)
248
+ self.output = TimesformerSelfOutput(config)
249
+
250
+ def forward(
251
+ self,
252
+ hidden_states: torch.Tensor,
253
+ output_attentions: bool = False,
254
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
255
+ self_outputs = self.attention(hidden_states, output_attentions)
256
+
257
+ attention_output = self.output(self_outputs[0])
258
+
259
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
260
+ return outputs
261
+
262
+
263
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L39
264
+ class TimesformerIntermediate(nn.Module):
265
+ def __init__(self, config: TimesformerConfig) -> None:
266
+ super().__init__()
267
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
268
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
269
+
270
+ if isinstance(config.hidden_act, str):
271
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
272
+ else:
273
+ self.intermediate_act_fn = config.hidden_act
274
+
275
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
276
+ hidden_states = self.dense(hidden_states)
277
+ hidden_states = self.intermediate_act_fn(hidden_states)
278
+ hidden_states = self.dropout(hidden_states)
279
+
280
+ return hidden_states
281
+
282
+
283
+ class TimesformerOutput(nn.Module):
284
+ def __init__(self, config: TimesformerConfig) -> None:
285
+ super().__init__()
286
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
287
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
288
+
289
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
290
+ hidden_states = self.dense(hidden_states)
291
+ hidden_states = self.dropout(hidden_states)
292
+
293
+ return hidden_states
294
+
295
+
296
+ # Adapted from https://github.com/facebookresearch/TimeSformer/blob/a5ef29a7b7264baff199a30b3306ac27de901133/timesformer/models/vit.py#L89
297
+ class TimesformerLayer(nn.Module):
298
+ def __init__(self, config: TimesformerConfig, layer_index: int) -> None:
299
+ super().__init__()
300
+
301
+ attention_type = config.attention_type
302
+
303
+ drop_path_rates = [
304
+ x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)
305
+ ] # stochastic depth decay rule
306
+ drop_path_rate = drop_path_rates[layer_index]
307
+
308
+ self.drop_path = TimeSformerDropPath(config.drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
309
+ self.attention = TimeSformerAttention(config)
310
+ self.intermediate = TimesformerIntermediate(config)
311
+ self.output = TimesformerOutput(config)
312
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
313
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
314
+
315
+ self.config = config
316
+ self.attention_type = attention_type
317
+ if attention_type not in ["divided_space_time", "space_only", "joint_space_time"]:
318
+ raise ValueError("Unknown attention type: {}".format(attention_type))
319
+
320
+ # Temporal Attention Parameters
321
+ if self.attention_type == "divided_space_time":
322
+ self.temporal_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
323
+ self.temporal_attention = TimeSformerAttention(config)
324
+ self.temporal_dense = nn.Linear(config.hidden_size, config.hidden_size)
325
+
326
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False):
327
+ num_frames = self.config.num_frames
328
+ num_patch_width = self.config.image_size // self.config.patch_size
329
+ batch_size = hidden_states.shape[0]
330
+ num_spatial_tokens = (hidden_states.size(1) - 1) // num_frames
331
+ num_patch_height = num_spatial_tokens // num_patch_width
332
+
333
+ if self.attention_type in ["space_only", "joint_space_time"]:
334
+ self_attention_outputs = self.attention(
335
+ self.layernorm_before(hidden_states), output_attentions=output_attentions
336
+ )
337
+ attention_output = self_attention_outputs[0]
338
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
339
+
340
+ hidden_states = hidden_states + self.drop_path(attention_output)
341
+
342
+ layer_output = self.layernorm_after(hidden_states)
343
+ layer_output = self.intermediate(layer_output)
344
+ layer_output = self.output(layer_output)
345
+ layer_output = hidden_states + self.drop_path(layer_output)
346
+
347
+ outputs = (layer_output,) + outputs
348
+
349
+ return outputs
350
+
351
+ elif self.attention_type == "divided_space_time":
352
+ # Temporal
353
+ temporal_embedding = hidden_states[:, 1:, :]
354
+ temporal_embedding = temporal_embedding.reshape(
355
+ batch_size, num_patch_height, num_patch_width, num_frames, temporal_embedding.shape[2]
356
+ ).reshape(batch_size * num_patch_height * num_patch_width, num_frames, temporal_embedding.shape[2])
357
+
358
+ temporal_attention_outputs = self.temporal_attention(
359
+ self.temporal_layernorm(temporal_embedding),
360
+ )
361
+ attention_output = temporal_attention_outputs[0]
362
+
363
+ residual_temporal = self.drop_path(attention_output)
364
+
365
+ residual_temporal = residual_temporal.reshape(
366
+ batch_size, num_patch_height, num_patch_width, num_frames, residual_temporal.shape[2]
367
+ ).reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_temporal.shape[2])
368
+ residual_temporal = self.temporal_dense(residual_temporal)
369
+ temporal_embedding = hidden_states[:, 1:, :] + residual_temporal
370
+
371
+ # Spatial
372
+ init_cls_token = hidden_states[:, 0, :].unsqueeze(1)
373
+ cls_token = init_cls_token.repeat(1, num_frames, 1)
374
+ cls_token = cls_token.reshape(batch_size * num_frames, 1, cls_token.shape[2])
375
+ spatial_embedding = temporal_embedding
376
+ spatial_embedding = (
377
+ spatial_embedding.reshape(
378
+ batch_size, num_patch_height, num_patch_width, num_frames, spatial_embedding.shape[2]
379
+ )
380
+ .permute(0, 3, 1, 2, 4)
381
+ .reshape(batch_size * num_frames, num_patch_height * num_patch_width, spatial_embedding.shape[2])
382
+ )
383
+ spatial_embedding = torch.cat((cls_token, spatial_embedding), 1)
384
+
385
+ spatial_attention_outputs = self.attention(
386
+ self.layernorm_before(spatial_embedding), output_attentions=output_attentions
387
+ )
388
+ attention_output = spatial_attention_outputs[0]
389
+ outputs = spatial_attention_outputs[1:] # add self attentions if we output attention weights
390
+
391
+ residual_spatial = self.drop_path(attention_output)
392
+
393
+ # Taking care of CLS token
394
+ cls_token = residual_spatial[:, 0, :]
395
+ cls_token = cls_token.reshape(batch_size, num_frames, cls_token.shape[1])
396
+ cls_token = torch.mean(cls_token, 1, True) # averaging for every frame
397
+ residual_spatial = residual_spatial[:, 1:, :]
398
+ residual_spatial = (
399
+ residual_spatial.reshape(
400
+ batch_size, num_frames, num_patch_height, num_patch_width, residual_spatial.shape[2]
401
+ )
402
+ .permute(0, 2, 3, 1, 4)
403
+ .reshape(batch_size, num_patch_height * num_patch_width * num_frames, residual_spatial.shape[2])
404
+ )
405
+ residual = residual_spatial
406
+ hidden_states = temporal_embedding
407
+
408
+ # Mlp
409
+ hidden_states = torch.cat((init_cls_token, hidden_states), 1) + torch.cat((cls_token, residual), 1)
410
+ layer_output = self.layernorm_after(hidden_states)
411
+ layer_output = self.intermediate(layer_output)
412
+ layer_output = self.output(layer_output)
413
+ layer_output = hidden_states + self.drop_path(layer_output)
414
+
415
+ outputs = (layer_output,) + outputs
416
+
417
+ return outputs
418
+
419
+
420
+ class TimesformerEncoder(nn.Module):
421
+ def __init__(self, config: TimesformerConfig) -> None:
422
+ super().__init__()
423
+ self.config = config
424
+ self.layer = nn.ModuleList([TimesformerLayer(config, ind) for ind in range(config.num_hidden_layers)])
425
+ self.gradient_checkpointing = False
426
+
427
+ def forward(
428
+ self,
429
+ hidden_states: torch.Tensor,
430
+ output_attentions: bool = False,
431
+ output_hidden_states: bool = False,
432
+ return_dict: bool = True,
433
+ ) -> Union[tuple, BaseModelOutput]:
434
+ all_hidden_states = () if output_hidden_states else None
435
+ all_self_attentions = () if output_attentions else None
436
+
437
+ for i, layer_module in enumerate(self.layer):
438
+ if output_hidden_states:
439
+ all_hidden_states = all_hidden_states + (hidden_states,)
440
+
441
+ if self.gradient_checkpointing and self.training:
442
+
443
+ def create_custom_forward(module):
444
+ def custom_forward(*inputs):
445
+ return module(*inputs, output_attentions)
446
+
447
+ return custom_forward
448
+
449
+ layer_outputs = torch.utils.checkpoint.checkpoint(
450
+ create_custom_forward(layer_module),
451
+ hidden_states,
452
+ )
453
+ else:
454
+ layer_outputs = layer_module(hidden_states, output_attentions)
455
+
456
+ hidden_states = layer_outputs[0]
457
+
458
+ if output_attentions:
459
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
460
+
461
+ if output_hidden_states:
462
+ all_hidden_states = all_hidden_states + (hidden_states,)
463
+
464
+ if not return_dict:
465
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
466
+ return BaseModelOutput(
467
+ last_hidden_state=hidden_states,
468
+ hidden_states=all_hidden_states,
469
+ attentions=all_self_attentions,
470
+ )
471
+
472
+
473
+ class TimesformerPreTrainedModel(PreTrainedModel):
474
+ """
475
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
476
+ models.
477
+ """
478
+
479
+ config_class = TimesformerConfig
480
+ base_model_prefix = "timesformer"
481
+ main_input_name = "pixel_values"
482
+ supports_gradient_checkpointing = True
483
+
484
+ def _init_weights(self, module):
485
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
486
+ nn.init.trunc_normal_(module.weight, std=self.config.initializer_range)
487
+ if module.bias is not None:
488
+ nn.init.constant_(module.bias, 0)
489
+ elif isinstance(module, nn.LayerNorm):
490
+ nn.init.constant_(module.bias, 0)
491
+ nn.init.constant_(module.weight, 1.0)
492
+ elif isinstance(module, TimesformerEmbeddings):
493
+ nn.init.trunc_normal_(module.cls_token, std=self.config.initializer_range)
494
+ nn.init.trunc_normal_(module.position_embeddings, std=self.config.initializer_range)
495
+ module.patch_embeddings.apply(self._init_weights)
496
+
497
+ def _set_gradient_checkpointing(self, module, value=False):
498
+ if isinstance(module, TimesformerEncoder):
499
+ module.gradient_checkpointing = value
500
+
501
+
502
+ TIMESFORMER_START_DOCSTRING = r"""
503
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
504
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
505
+ behavior.
506
+
507
+ Parameters:
508
+ config ([`TimesformerConfig`]): Model configuration class with all the parameters of the model.
509
+ Initializing with a config file does not load the weights associated with the model, only the
510
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
511
+ """
512
+
513
+ TIMESFORMER_INPUTS_DOCSTRING = r"""
514
+ Args:
515
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
516
+ Pixel values. Pixel values can be obtained using [`AutoFeatureExtractor`]. See
517
+ [`VideoMAEFeatureExtractor.__call__`] for details.
518
+
519
+ output_attentions (`bool`, *optional*):
520
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
521
+ tensors for more detail.
522
+ output_hidden_states (`bool`, *optional*):
523
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
524
+ more detail.
525
+ return_dict (`bool`, *optional*):
526
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
527
+ """
528
+
529
+
530
+ @add_start_docstrings(
531
+ "The bare TimeSformer Model transformer outputting raw hidden-states without any specific head on top.",
532
+ TIMESFORMER_START_DOCSTRING,
533
+ )
534
+ class TimesformerModel(TimesformerPreTrainedModel):
535
+ def __init__(self, config):
536
+ super().__init__(config)
537
+ self.config = config
538
+
539
+ self.embeddings = TimesformerEmbeddings(config)
540
+ self.encoder = TimesformerEncoder(config)
541
+
542
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
543
+
544
+ # Initialize weights and apply final processing
545
+ self.post_init()
546
+
547
+ def get_input_embeddings(self):
548
+ return self.embeddings.patch_embeddings
549
+
550
+ def _prune_heads(self, heads_to_prune):
551
+ """
552
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
553
+ class PreTrainedModel
554
+ """
555
+ for layer, heads in heads_to_prune.items():
556
+ self.encoder.layer[layer].attention.prune_heads(heads)
557
+
558
+ @add_start_docstrings_to_model_forward(TIMESFORMER_INPUTS_DOCSTRING)
559
+ @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
560
+ def forward(
561
+ self,
562
+ pixel_values,
563
+ output_attentions=None,
564
+ output_hidden_states=None,
565
+ return_dict=None,
566
+ ):
567
+ r"""
568
+ Returns:
569
+
570
+ Examples:
571
+
572
+ ```python
573
+ >>> import av
574
+ >>> import numpy as np
575
+
576
+ >>> from transformers import AutoImageProcessor, TimesformerModel
577
+ >>> from huggingface_hub import hf_hub_download
578
+
579
+ >>> np.random.seed(0)
580
+
581
+
582
+ >>> def read_video_pyav(container, indices):
583
+ ... '''
584
+ ... Decode the video with PyAV decoder.
585
+ ... Args:
586
+ ... container (`av.container.input.InputContainer`): PyAV container.
587
+ ... indices (`List[int]`): List of frame indices to decode.
588
+ ... Returns:
589
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
590
+ ... '''
591
+ ... frames = []
592
+ ... container.seek(0)
593
+ ... start_index = indices[0]
594
+ ... end_index = indices[-1]
595
+ ... for i, frame in enumerate(container.decode(video=0)):
596
+ ... if i > end_index:
597
+ ... break
598
+ ... if i >= start_index and i in indices:
599
+ ... frames.append(frame)
600
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
601
+
602
+
603
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
604
+ ... converted_len = int(clip_len * frame_sample_rate)
605
+ ... end_idx = np.random.randint(converted_len, seg_len)
606
+ ... start_idx = end_idx - converted_len
607
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
608
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
609
+ ... return indices
610
+
611
+
612
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
613
+ >>> file_path = hf_hub_download(
614
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
615
+ ... )
616
+ >>> container = av.open(file_path)
617
+
618
+ >>> # sample 8 frames
619
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames)
620
+ >>> video = read_video_pyav(container, indices)
621
+
622
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
623
+ >>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400")
624
+
625
+ >>> # prepare video for the model
626
+ >>> inputs = image_processor(list(video), return_tensors="pt")
627
+
628
+ >>> # forward pass
629
+ >>> outputs = model(**inputs)
630
+ >>> last_hidden_states = outputs.last_hidden_state
631
+ >>> list(last_hidden_states.shape)
632
+ [1, 1569, 768]
633
+ ```"""
634
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
635
+ output_hidden_states = (
636
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
637
+ )
638
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
639
+
640
+ embedding_output = self.embeddings(pixel_values)
641
+
642
+ encoder_outputs = self.encoder(
643
+ embedding_output,
644
+ output_attentions=output_attentions,
645
+ output_hidden_states=output_hidden_states,
646
+ return_dict=return_dict,
647
+ )
648
+ sequence_output = encoder_outputs[0]
649
+ if self.layernorm is not None:
650
+ sequence_output = self.layernorm(sequence_output)
651
+
652
+ if not return_dict:
653
+ return (sequence_output,) + encoder_outputs[1:]
654
+
655
+ return BaseModelOutput(
656
+ last_hidden_state=sequence_output,
657
+ hidden_states=encoder_outputs.hidden_states,
658
+ attentions=encoder_outputs.attentions,
659
+ )
660
+
661
+
662
+ @add_start_docstrings(
663
+ """TimeSformer Model transformer with a video classification head on top (a linear layer on top of the final hidden state
664
+ of the [CLS] token) e.g. for ImageNet.""",
665
+ TIMESFORMER_START_DOCSTRING,
666
+ )
667
+ class TimesformerForVideoClassification(TimesformerPreTrainedModel):
668
+ def __init__(self, config):
669
+ super().__init__(config)
670
+
671
+ self.num_labels = config.num_labels
672
+ self.timesformer = TimesformerModel(config)
673
+
674
+ # Classifier head
675
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
676
+
677
+ # Initialize weights and apply final processing
678
+ self.post_init()
679
+
680
+ @add_start_docstrings_to_model_forward(TIMESFORMER_INPUTS_DOCSTRING)
681
+ @replace_return_docstrings(output_type=ImageClassifierOutput, config_class=_CONFIG_FOR_DOC)
682
+ def forward(
683
+ self,
684
+ pixel_values: Optional[torch.Tensor] = None,
685
+ labels: Optional[torch.Tensor] = None,
686
+ output_attentions: Optional[bool] = None,
687
+ output_hidden_states: Optional[bool] = None,
688
+ return_dict: Optional[bool] = None,
689
+ ) -> Union[Tuple, ImageClassifierOutput]:
690
+ r"""
691
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
692
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
693
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
694
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
695
+
696
+ Returns:
697
+
698
+ Examples:
699
+
700
+ ```python
701
+ >>> import av
702
+ >>> import torch
703
+ >>> import numpy as np
704
+
705
+ >>> from transformers import AutoImageProcessor, TimesformerForVideoClassification
706
+ >>> from huggingface_hub import hf_hub_download
707
+
708
+ >>> np.random.seed(0)
709
+
710
+
711
+ >>> def read_video_pyav(container, indices):
712
+ ... '''
713
+ ... Decode the video with PyAV decoder.
714
+ ... Args:
715
+ ... container (`av.container.input.InputContainer`): PyAV container.
716
+ ... indices (`List[int]`): List of frame indices to decode.
717
+ ... Returns:
718
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
719
+ ... '''
720
+ ... frames = []
721
+ ... container.seek(0)
722
+ ... start_index = indices[0]
723
+ ... end_index = indices[-1]
724
+ ... for i, frame in enumerate(container.decode(video=0)):
725
+ ... if i > end_index:
726
+ ... break
727
+ ... if i >= start_index and i in indices:
728
+ ... frames.append(frame)
729
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
730
+
731
+
732
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
733
+ ... converted_len = int(clip_len * frame_sample_rate)
734
+ ... end_idx = np.random.randint(converted_len, seg_len)
735
+ ... start_idx = end_idx - converted_len
736
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
737
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
738
+ ... return indices
739
+
740
+
741
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
742
+ >>> file_path = hf_hub_download(
743
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
744
+ ... )
745
+ >>> container = av.open(file_path)
746
+
747
+ >>> # sample 8 frames
748
+ >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
749
+ >>> video = read_video_pyav(container, indices)
750
+
751
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
752
+ >>> model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400")
753
+
754
+ >>> inputs = image_processor(list(video), return_tensors="pt")
755
+
756
+ >>> with torch.no_grad():
757
+ ... outputs = model(**inputs)
758
+ ... logits = outputs.logits
759
+
760
+ >>> # model predicts one of the 400 Kinetics-400 classes
761
+ >>> predicted_label = logits.argmax(-1).item()
762
+ >>> print(model.config.id2label[predicted_label])
763
+ eating spaghetti
764
+ ```"""
765
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
766
+
767
+ outputs = self.timesformer(
768
+ pixel_values,
769
+ output_attentions=output_attentions,
770
+ output_hidden_states=output_hidden_states,
771
+ return_dict=return_dict,
772
+ )
773
+
774
+ sequence_output = outputs[0][:, 0]
775
+
776
+ logits = self.classifier(sequence_output)
777
+
778
+ loss = None
779
+ if labels is not None:
780
+ if self.config.problem_type is None:
781
+ if self.num_labels == 1:
782
+ self.config.problem_type = "regression"
783
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
784
+ self.config.problem_type = "single_label_classification"
785
+ else:
786
+ self.config.problem_type = "multi_label_classification"
787
+
788
+ if self.config.problem_type == "regression":
789
+ loss_fct = MSELoss()
790
+ if self.num_labels == 1:
791
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
792
+ else:
793
+ loss = loss_fct(logits, labels)
794
+ elif self.config.problem_type == "single_label_classification":
795
+ loss_fct = CrossEntropyLoss()
796
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
797
+ elif self.config.problem_type == "multi_label_classification":
798
+ loss_fct = BCEWithLogitsLoss()
799
+ loss = loss_fct(logits, labels)
800
+
801
+ if not return_dict:
802
+ output = (logits,) + outputs[1:]
803
+ return ((loss,) + output) if loss is not None else output
804
+
805
+ return ImageClassifierOutput(
806
+ loss=loss,
807
+ logits=logits,
808
+ hidden_states=outputs.hidden_states,
809
+ attentions=outputs.attentions,
810
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trajectory_transformer/configuration_trajectory_transformer.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Trajectory Transformers paper 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
+ """ TrajectoryTransformer model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": (
25
+ "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json"
26
+ ),
27
+ # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer
28
+ }
29
+
30
+
31
+ class TrajectoryTransformerConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`TrajectoryTransformerModel`]. It is used to
34
+ instantiate an TrajectoryTransformer model according to the specified arguments, defining the model architecture.
35
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the
36
+ TrajectoryTransformer
37
+ [CarlCochet/trajectory-transformer-halfcheetah-medium-v2](https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2)
38
+ architecture.
39
+
40
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
41
+ documentation from [`PretrainedConfig`] for more information.
42
+
43
+
44
+ Args:
45
+ vocab_size (`int`, *optional*, defaults to 100):
46
+ Vocabulary size of the TrajectoryTransformer model. Defines the number of different tokens that can be
47
+ represented by the `trajectories` passed when calling [`TrajectoryTransformerModel`]
48
+ action_weight (`int`, *optional*, defaults to 5):
49
+ Weight of the action in the loss function
50
+ reward_weight (`int`, *optional*, defaults to 1):
51
+ Weight of the reward in the loss function
52
+ value_weight (`int`, *optional*, defaults to 1):
53
+ Weight of the value in the loss function
54
+ block_size (`int`, *optional*, defaults to 249):
55
+ Size of the blocks in the trajectory transformer.
56
+ action_dim (`int`, *optional*, defaults to 6):
57
+ Dimension of the action space.
58
+ observation_dim (`int`, *optional*, defaults to 17):
59
+ Dimension of the observation space.
60
+ transition_dim (`int`, *optional*, defaults to 25):
61
+ Dimension of the transition space.
62
+ n_layer (`int`, *optional*, defaults to 4):
63
+ Number of hidden layers in the Transformer encoder.
64
+ n_head (`int`, *optional*, defaults to 4):
65
+ Number of attention heads for each attention layer in the Transformer encoder.
66
+ n_embd (`int`, *optional*, defaults to 128):
67
+ Dimensionality of the embeddings and hidden states.
68
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
69
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
70
+ embd_pdrop (`int`, *optional*, defaults to 0.1):
71
+ The dropout ratio for the embeddings.
72
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
73
+ The dropout ratio for the attention.
74
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
75
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
76
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
77
+ max_position_embeddings (`int`, *optional*, defaults to 512):
78
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
79
+ just in case (e.g., 512 or 1024 or 2048).
80
+ initializer_range (`float`, *optional*, defaults to 0.02):
81
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
82
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
83
+ The epsilon used by the layer normalization layers.
84
+ kaiming_initializer_range (`float, *optional*, defaults to 1):
85
+ A coefficient scaling the negative slope of the kaiming initializer rectifier for EinLinear layers.
86
+ use_cache (`bool`, *optional*, defaults to `True`):
87
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
88
+ relevant if `config.is_decoder=True`.
89
+ Example:
90
+
91
+ ```python
92
+ >>> from transformers import TrajectoryTransformerConfig, TrajectoryTransformerModel
93
+
94
+ >>> # Initializing a TrajectoryTransformer CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
95
+ >>> configuration = TrajectoryTransformerConfig()
96
+
97
+ >>> # Initializing a model (with random weights) from the CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
98
+ >>> model = TrajectoryTransformerModel(configuration)
99
+
100
+ >>> # Accessing the model configuration
101
+ >>> configuration = model.config
102
+ ```"""
103
+ model_type = "trajectory_transformer"
104
+ keys_to_ignore_at_inference = ["past_key_values"]
105
+ attribute_map = {
106
+ "hidden_size": "n_embd",
107
+ "num_attention_heads": "n_head",
108
+ "num_hidden_layers": "n_layer",
109
+ }
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=100,
114
+ action_weight=5,
115
+ reward_weight=1,
116
+ value_weight=1,
117
+ block_size=249,
118
+ action_dim=6,
119
+ observation_dim=17,
120
+ transition_dim=25,
121
+ n_layer=4,
122
+ n_head=4,
123
+ n_embd=128,
124
+ embd_pdrop=0.1,
125
+ attn_pdrop=0.1,
126
+ resid_pdrop=0.1,
127
+ learning_rate=0.0006,
128
+ max_position_embeddings=512,
129
+ initializer_range=0.02,
130
+ layer_norm_eps=1e-12,
131
+ kaiming_initializer_range=1,
132
+ use_cache=True,
133
+ pad_token_id=1,
134
+ bos_token_id=50256,
135
+ eos_token_id=50256,
136
+ **kwargs,
137
+ ):
138
+ self.vocab_size = vocab_size
139
+ self.action_weight = action_weight
140
+ self.reward_weight = reward_weight
141
+ self.value_weight = value_weight
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.block_size = block_size
144
+ self.action_dim = action_dim
145
+ self.observation_dim = observation_dim
146
+ self.transition_dim = transition_dim
147
+ self.learning_rate = learning_rate
148
+ self.n_layer = n_layer
149
+ self.n_head = n_head
150
+ self.n_embd = n_embd
151
+ self.embd_pdrop = embd_pdrop
152
+ self.attn_pdrop = attn_pdrop
153
+ self.resid_pdrop = resid_pdrop
154
+ self.initializer_range = initializer_range
155
+ self.layer_norm_eps = layer_norm_eps
156
+ self.kaiming_initializer_range = kaiming_initializer_range
157
+ self.use_cache = use_cache
158
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Trajectory Transformers paper 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
+ """ TrajectoryTransformer pytorch checkpoint conversion"""
16
+
17
+ import torch
18
+ import trajectory.utils as utils
19
+
20
+ from transformers import TrajectoryTransformerModel
21
+
22
+
23
+ class Parser(utils.Parser):
24
+ dataset: str = "halfcheetah-medium-expert-v2"
25
+ config: str = "config.offline"
26
+
27
+
28
+ def convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch(logbase, dataset, loadpath, epoch, device):
29
+ """Converting Sequential blocks to ModuleList"""
30
+
31
+ gpt, gpt_epoch = utils.load_model(logbase, dataset, loadpath, epoch=epoch, device=device)
32
+ trajectory_transformer = TrajectoryTransformerModel(gpt.config)
33
+
34
+ trajectory_transformer.tok_emb.load_state_dict(gpt.tok_emb.state_dict())
35
+ trajectory_transformer.pos_emb = gpt.pos_emb
36
+ trajectory_transformer.drop.load_state_dict(gpt.drop.state_dict())
37
+ trajectory_transformer.ln_f.load_state_dict(gpt.ln_f.state_dict())
38
+ trajectory_transformer.head.load_state_dict(gpt.head.state_dict())
39
+
40
+ for i, block in enumerate(gpt.blocks):
41
+ trajectory_transformer.blocks[i].ln1.load_state_dict(gpt.blocks[i].ln1.state_dict())
42
+ trajectory_transformer.blocks[i].ln2.load_state_dict(gpt.blocks[i].ln2.state_dict())
43
+ trajectory_transformer.blocks[i].attn.load_state_dict(gpt.blocks[i].attn.state_dict())
44
+
45
+ trajectory_transformer.blocks[i].l1.load_state_dict(gpt.blocks[i].mlp[0].state_dict())
46
+ trajectory_transformer.blocks[i].act.load_state_dict(gpt.blocks[i].mlp[1].state_dict())
47
+ trajectory_transformer.blocks[i].l2.load_state_dict(gpt.blocks[i].mlp[2].state_dict())
48
+ trajectory_transformer.blocks[i].drop.load_state_dict(gpt.blocks[i].mlp[3].state_dict())
49
+
50
+ torch.save(trajectory_transformer.state_dict(), "pytorch_model.bin")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ """
55
+ To run this script you will need to install the original repository to run the original model. You can find it
56
+ here: https://github.com/jannerm/trajectory-transformer From this repository code you can also download the
57
+ original pytorch checkpoints.
58
+
59
+ Run with the command:
60
+
61
+ ```sh
62
+ >>> python convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py --dataset <dataset_name>
63
+ ... --gpt_loadpath <path_to_original_pytorch_checkpoint>
64
+ ```
65
+ """
66
+
67
+ args = Parser().parse_args("plan")
68
+ convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch(
69
+ args.logbase, args.dataset, args.gpt_loadpath, args.gpt_epoch, args.device
70
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trajectory_transformer/modeling_trajectory_transformer.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Trajectory Transformers paper 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 TrajectoryTransformer model."""
16
+
17
+ import math
18
+ import os
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 functional as F
27
+
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ logging,
34
+ replace_return_docstrings,
35
+ )
36
+ from .configuration_trajectory_transformer import TrajectoryTransformerConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CHECKPOINT_FOR_DOC = "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
42
+ _CONFIG_FOR_DOC = "TrajectoryTransformerConfig"
43
+
44
+ TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
45
+ "CarlCochet/trajectory-transformer-halfcheetah-medium-v2",
46
+ # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer
47
+ ]
48
+
49
+
50
+ def load_tf_weights_in_trajectory_transformer(model, config, tf_checkpoint_path):
51
+ """Load tf checkpoints in a pytorch model."""
52
+ try:
53
+ import re
54
+
55
+ import numpy as np
56
+ import tensorflow as tf
57
+ except ImportError:
58
+ logger.error(
59
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
60
+ "https://www.tensorflow.org/install/ for installation instructions."
61
+ )
62
+ raise
63
+ tf_path = os.path.abspath(tf_checkpoint_path)
64
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
65
+ # Load weights from TF model
66
+ init_vars = tf.train.list_variables(tf_path)
67
+ names = []
68
+ arrays = []
69
+ for name, shape in init_vars:
70
+ logger.info(f"Loading TF weight {name} with shape {shape}")
71
+ array = tf.train.load_variable(tf_path, name)
72
+ names.append(name)
73
+ arrays.append(array)
74
+
75
+ for name, array in zip(names, arrays):
76
+ name = name.split("/")
77
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
78
+ # which are not required for using pretrained model
79
+ if any(
80
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
81
+ for n in name
82
+ ):
83
+ logger.info(f"Skipping {'/'.join(name)}")
84
+ continue
85
+ pointer = model
86
+ for m_name in name:
87
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
88
+ scope_names = re.split(r"_(\d+)", m_name)
89
+ else:
90
+ scope_names = [m_name]
91
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
92
+ pointer = getattr(pointer, "weight")
93
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
94
+ pointer = getattr(pointer, "bias")
95
+ elif scope_names[0] == "output_weights":
96
+ pointer = getattr(pointer, "weight")
97
+ elif scope_names[0] == "squad":
98
+ pointer = getattr(pointer, "classifier")
99
+ else:
100
+ try:
101
+ pointer = getattr(pointer, scope_names[0])
102
+ except AttributeError:
103
+ logger.info(f"Skipping {'/'.join(name)}")
104
+ continue
105
+ if len(scope_names) >= 2:
106
+ num = int(scope_names[1])
107
+ pointer = pointer[num]
108
+ if m_name[-11:] == "_embeddings":
109
+ pointer = getattr(pointer, "weight")
110
+ elif m_name == "kernel":
111
+ array = np.transpose(array)
112
+ try:
113
+ if pointer.shape != array.shape:
114
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
115
+ except AssertionError as e:
116
+ e.args += (pointer.shape, array.shape)
117
+ raise
118
+ logger.info(f"Initialize PyTorch weight {name}")
119
+ pointer.data = torch.from_numpy(array)
120
+ return model
121
+
122
+
123
+ @dataclass
124
+ class TrajectoryTransformerOutput(ModelOutput):
125
+ """
126
+ Base class for model's outputs that also contains a pooling of the last hidden states.
127
+
128
+ Args:
129
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
130
+ Language modeling loss.
131
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
132
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
133
+ past_key_values (`Tuple[Tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
134
+ Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
135
+ sequence_length, embed_size_per_head)`). Contains pre-computed hidden-states (key and values in the
136
+ attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
137
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
138
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
139
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
140
+ plus the initial embedding outputs.
141
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
142
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
143
+ sequence_length)`. GPT2Attentions weights after the attention softmax, used to compute the weighted average
144
+ in the self-attention heads.
145
+ """
146
+
147
+ loss: Optional[torch.FloatTensor] = None
148
+ logits: torch.FloatTensor = None
149
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
150
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
151
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
152
+
153
+
154
+ class TrajectoryTransformerPreTrainedModel(PreTrainedModel):
155
+ """
156
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
157
+ models.
158
+ """
159
+
160
+ config_class = TrajectoryTransformerConfig
161
+ load_tf_weights = load_tf_weights_in_trajectory_transformer
162
+ base_model_prefix = "trajectory_transformer"
163
+ main_input_name = "trajectories"
164
+ supports_gradient_checkpointing = True
165
+
166
+ def _set_gradient_checkpointing(self, module, value=False):
167
+ if isinstance(module, TrajectoryTransformerModel):
168
+ module.gradient_checkpointing = value
169
+
170
+ def _init_weights(self, module):
171
+ if isinstance(module, (nn.Linear, nn.Embedding)):
172
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
173
+ if isinstance(module, nn.Linear) and module.bias is not None:
174
+ module.bias.data.zero_()
175
+ elif isinstance(module, nn.LayerNorm):
176
+ module.bias.data.zero_()
177
+ module.weight.data.fill_(1.0)
178
+ elif isinstance(module, EinLinear):
179
+ for i in range(module.n_models):
180
+ nn.init.kaiming_uniform_(module.weight[i], a=math.sqrt(5) / self.config.kaiming_initializer_range)
181
+ if module.bias is not None:
182
+ fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight[i])
183
+ bound = (1 / math.sqrt(fan_in)) * self.config.initializer_range
184
+ nn.init.uniform_(module.bias[i], -bound, bound)
185
+
186
+
187
+ TRAJECTORY_TRANSFORMER_START_DOCSTRING = r"""
188
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
189
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
190
+ behavior.
191
+
192
+ Parameters:
193
+ config ([`TrajectoryTransformerConfig`]): Model configuration class with all the parameters of the model.
194
+ Initializing with a config file does not load the weights associated with the model, only the
195
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
196
+ """
197
+
198
+ TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING = r"""
199
+ Args:
200
+ trajectories (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
201
+ Batch of trajectories, where a trajectory is a sequence of states, actions and rewards.
202
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`, *optional*):
203
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
204
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
205
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
206
+ targets (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
207
+ Desired targets used to compute the loss.
208
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
209
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
210
+
211
+ - 1 for tokens that are **not masked**,
212
+ - 0 for tokens that are **masked**.
213
+
214
+ [What are attention masks?](../glossary#attention-mask)
215
+ use_cache (`bool`, *optional*):
216
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
217
+ `past_key_values`).
218
+ output_attentions (`bool`, *optional*):
219
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
220
+ tensors for more detail.
221
+ output_hidden_states (`bool`, *optional*):
222
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
223
+ more detail.
224
+ return_dict (`bool`, *optional*):
225
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
226
+ """
227
+
228
+
229
+ class EinLinear(nn.Module):
230
+ def __init__(self, n_models, in_features, out_features, bias):
231
+ super().__init__()
232
+ self.n_models = n_models
233
+ self.out_features = out_features
234
+ self.in_features = in_features
235
+ self.weight = nn.Parameter(torch.Tensor(n_models, out_features, in_features))
236
+ if bias:
237
+ self.bias = nn.Parameter(torch.Tensor(n_models, out_features))
238
+ else:
239
+ self.register_parameter("bias", None)
240
+
241
+ def reset_parameters(self):
242
+ for i in range(self.n_models):
243
+ nn.init.kaiming_uniform_(self.weight[i], a=math.sqrt(5))
244
+ if self.bias is not None:
245
+ fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight[i])
246
+ bound = 1 / math.sqrt(fan_in)
247
+ nn.init.uniform_(self.bias[i], -bound, bound)
248
+
249
+ def forward(self, input):
250
+ """
251
+ Args:
252
+ input (`torch.FloatTensor` of shape `(B, n_models, input_dim)`):
253
+ The input to the layer.
254
+ """
255
+ # [ batch_size x n_models x output_dim ]
256
+ output = torch.einsum("eoi,bei->beo", self.weight, input)
257
+ if self.bias is not None:
258
+ raise RuntimeError()
259
+ return output
260
+
261
+
262
+ class CausalSelfAttention(nn.Module):
263
+ def __init__(self, config):
264
+ super().__init__()
265
+
266
+ if config.n_embd % config.n_head != 0:
267
+ raise ValueError(f"n_head ({config.n_head}) should be a divisor of n_embd ({config.n_embd})")
268
+
269
+ # key, query, value projections for all heads
270
+ self.key = nn.Linear(config.n_embd, config.n_embd)
271
+ self.query = nn.Linear(config.n_embd, config.n_embd)
272
+ self.value = nn.Linear(config.n_embd, config.n_embd)
273
+
274
+ # regularization
275
+ self.attn_drop = nn.Dropout(config.attn_pdrop)
276
+ self.resid_drop = nn.Dropout(config.resid_pdrop)
277
+
278
+ # output projection
279
+ self.proj = nn.Linear(config.n_embd, config.n_embd)
280
+
281
+ # causal mask to ensure that attention is only applied to the left in the input sequence
282
+ self.register_buffer(
283
+ "mask",
284
+ torch.tril(torch.ones(config.block_size, config.block_size)).view(
285
+ 1, 1, config.block_size, config.block_size
286
+ ),
287
+ )
288
+
289
+ # mask previous value estimates
290
+ joined_dim = config.observation_dim + config.action_dim + 2
291
+ self.mask.squeeze()[:, joined_dim - 1 :: joined_dim] = 0
292
+
293
+ self.n_head = config.n_head
294
+
295
+ def forward(
296
+ self,
297
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
298
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
299
+ use_cache: Optional[bool] = False,
300
+ output_attentions: Optional[bool] = False,
301
+ ):
302
+ batch_size, sequence_length, embedding_dim = hidden_states.size()
303
+
304
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
305
+ # [ batch_size x n_heads x sequence_length x head_dim ]
306
+ key = (
307
+ self.key(hidden_states)
308
+ .view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
309
+ .transpose(1, 2)
310
+ )
311
+ query = (
312
+ self.query(hidden_states)
313
+ .view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
314
+ .transpose(1, 2)
315
+ )
316
+ value = (
317
+ self.value(hidden_states)
318
+ .view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
319
+ .transpose(1, 2)
320
+ )
321
+
322
+ if layer_past is not None:
323
+ past_key, past_value = layer_past
324
+ key = torch.cat((past_key, key), dim=-2)
325
+ value = torch.cat((past_value, value), dim=-2)
326
+
327
+ if use_cache is True:
328
+ present = (key, value)
329
+ else:
330
+ present = None
331
+
332
+ # causal self-attention
333
+ # [ batch_size x n_heads x sequence_length x sequence_length ]
334
+ attn_weights = (torch.matmul(query, key.transpose(-2, -1))) * (1.0 / math.sqrt(key.size(-1)))
335
+ attn_weights = attn_weights.masked_fill(
336
+ self.mask[:, :, :sequence_length, :sequence_length] == 0, torch.finfo(attn_weights.dtype).min
337
+ )
338
+ attn_weights = F.softmax(attn_weights, dim=-1)
339
+ self._attn_map = attn_weights.clone()
340
+ attn_weights = self.attn_drop(attn_weights)
341
+
342
+ output = torch.matmul(attn_weights, value)
343
+ # [ batch_size x sequence_length x embedding_dim ]
344
+ # re-assemble all head outputs side by side
345
+ output = output.transpose(1, 2).contiguous().view(batch_size, sequence_length, embedding_dim)
346
+
347
+ # output projection
348
+ output = self.resid_drop(self.proj(output))
349
+
350
+ outputs = (output, present)
351
+ if output_attentions:
352
+ outputs += (attn_weights,)
353
+
354
+ return outputs
355
+
356
+
357
+ class Block(nn.Module):
358
+ def __init__(self, config):
359
+ super().__init__()
360
+ self.ln1 = nn.LayerNorm(config.n_embd)
361
+ self.ln2 = nn.LayerNorm(config.n_embd)
362
+ self.attn = CausalSelfAttention(config)
363
+
364
+ # MLP
365
+ self.l1 = nn.Linear(config.n_embd, 4 * config.n_embd)
366
+ self.act = nn.GELU()
367
+ self.l2 = nn.Linear(4 * config.n_embd, config.n_embd)
368
+ self.drop = nn.Dropout(config.resid_pdrop)
369
+
370
+ def forward(
371
+ self,
372
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
373
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
374
+ use_cache: Optional[bool] = False,
375
+ output_attentions: Optional[bool] = False,
376
+ ):
377
+ residual = hidden_states
378
+ hidden_states = self.ln1(hidden_states)
379
+
380
+ attn_outputs = self.attn(
381
+ hidden_states, layer_past=layer_past, use_cache=use_cache, output_attentions=output_attentions
382
+ )
383
+ attn_output = attn_outputs[0]
384
+ outputs = attn_outputs[1:]
385
+ hidden_states = attn_output + residual
386
+
387
+ residual = hidden_states
388
+ hidden_states = self.ln2(hidden_states)
389
+ hidden_states = self.l1(hidden_states)
390
+ hidden_states = self.act(hidden_states)
391
+ hidden_states = self.l2(hidden_states)
392
+ hidden_states = residual + self.drop(hidden_states)
393
+
394
+ if use_cache:
395
+ outputs = (hidden_states,) + outputs
396
+ else:
397
+ outputs = (hidden_states,) + outputs[1:]
398
+
399
+ return outputs
400
+
401
+
402
+ @add_start_docstrings(
403
+ "The bare TrajectoryTransformer Model transformer outputting raw hidden-states without any specific head on top.",
404
+ TRAJECTORY_TRANSFORMER_START_DOCSTRING,
405
+ )
406
+ class TrajectoryTransformerModel(TrajectoryTransformerPreTrainedModel):
407
+ """the full GPT language model, with a context size of block_size"""
408
+
409
+ def __init__(self, config):
410
+ super().__init__(config)
411
+
412
+ # input embedding stem (+1 for stop token)
413
+ self.tok_emb = nn.Embedding(config.vocab_size * config.transition_dim + 1, config.n_embd)
414
+
415
+ self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))
416
+ self.drop = nn.Dropout(config.embd_pdrop)
417
+ # transformer
418
+ self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
419
+ # decoder head
420
+ self.ln_f = nn.LayerNorm(config.n_embd)
421
+ self.head = EinLinear(config.transition_dim, config.n_embd, config.vocab_size + 1, bias=False)
422
+
423
+ self.vocab_size = config.vocab_size
424
+ self.stop_token = config.vocab_size * config.transition_dim
425
+ self.block_size = config.block_size
426
+
427
+ self.observation_dim = config.observation_dim
428
+ self.action_dim = config.action_dim
429
+ self.transition_dim = config.transition_dim
430
+ self.embedding_dim = config.n_embd
431
+
432
+ self.action_weight = config.action_weight
433
+ self.reward_weight = config.reward_weight
434
+ self.value_weight = config.value_weight
435
+
436
+ self.gradient_checkpointing = False
437
+
438
+ self.post_init()
439
+
440
+ def get_block_size(self):
441
+ return self.block_size
442
+
443
+ def offset_tokens(self, trajectories):
444
+ _, sequence_length = trajectories.shape
445
+
446
+ n_states = int(np.ceil(sequence_length / self.transition_dim))
447
+
448
+ offsets = torch.arange(self.transition_dim) * self.vocab_size
449
+ offsets = offsets.repeat(n_states).to(trajectories.device)
450
+
451
+ offset_trajectories = trajectories + offsets[:sequence_length]
452
+ offset_trajectories[trajectories == self.vocab_size] = self.stop_token
453
+ return offset_trajectories
454
+
455
+ def pad_to_full_observation(self, hidden_states):
456
+ batch_size, sequence_length, _ = hidden_states.shape
457
+
458
+ n_pad = (self.transition_dim - sequence_length % self.transition_dim) % self.transition_dim
459
+ padding = torch.zeros(batch_size, n_pad, self.embedding_dim, device=hidden_states.device)
460
+
461
+ # [ batch_size x padded_sequence_length' x embedding_dim ]
462
+ hidden_states_pad = torch.cat([hidden_states, padding], dim=1)
463
+ hidden_states_pad = hidden_states_pad.view(-1, self.transition_dim, self.embedding_dim)
464
+
465
+ return hidden_states_pad, n_pad
466
+
467
+ @add_start_docstrings_to_model_forward(
468
+ TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING.format("batch_size, sequence_length")
469
+ )
470
+ @replace_return_docstrings(output_type=TrajectoryTransformerOutput, config_class=_CONFIG_FOR_DOC)
471
+ def forward(
472
+ self,
473
+ trajectories: Optional[torch.LongTensor] = None,
474
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
475
+ targets: Optional[torch.FloatTensor] = None,
476
+ attention_mask: Optional[torch.FloatTensor] = None,
477
+ use_cache: Optional[bool] = None,
478
+ output_attentions: Optional[bool] = None,
479
+ output_hidden_states: Optional[bool] = None,
480
+ return_dict: Optional[bool] = None,
481
+ ) -> Union[Tuple[torch.Tensor], TrajectoryTransformerOutput]:
482
+ r"""
483
+ Returns:
484
+
485
+ Examples:
486
+
487
+ ```python
488
+ >>> from transformers import TrajectoryTransformerModel
489
+ >>> import torch
490
+
491
+ >>> model = TrajectoryTransformerModel.from_pretrained(
492
+ ... "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
493
+ ... )
494
+ >>> model.to(device)
495
+ >>> model.eval()
496
+
497
+ >>> observations_dim, action_dim, batch_size = 17, 6, 256
498
+ >>> seq_length = observations_dim + action_dim + 1
499
+
500
+ >>> trajectories = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(
501
+ ... device
502
+ ... )
503
+ >>> targets = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(device)
504
+
505
+ >>> outputs = model(
506
+ ... trajectories,
507
+ ... targets=targets,
508
+ ... use_cache=True,
509
+ ... output_attentions=True,
510
+ ... output_hidden_states=True,
511
+ ... return_dict=True,
512
+ ... )
513
+ ```
514
+ """
515
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
516
+ output_hidden_states = (
517
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
518
+ )
519
+
520
+ if past_key_values is None:
521
+ past_key_values = tuple([None] * len(self.blocks))
522
+
523
+ batch_size, sequence_length = trajectories.size()
524
+
525
+ if sequence_length > self.block_size:
526
+ raise ValueError("Cannot forward, model block size is exhausted.")
527
+
528
+ offset_trajectories = self.offset_tokens(trajectories)
529
+ # [ batch_size x sequence_length x embedding_dim ]
530
+ # forward the GPT model
531
+ token_embeddings = self.tok_emb(offset_trajectories) # each index maps to a (learnable) vector
532
+ position_embeddings = self.pos_emb[:, :sequence_length, :] # each position maps to a (learnable) vector
533
+
534
+ hidden_states = self.drop(token_embeddings + position_embeddings)
535
+
536
+ if self.gradient_checkpointing and self.training:
537
+ if use_cache:
538
+ logger.warning_once(
539
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
540
+ )
541
+ use_cache = False
542
+
543
+ presents = () if use_cache else None
544
+ all_self_attentions = () if output_attentions else None
545
+ all_hidden_states = () if output_hidden_states else None
546
+
547
+ for i, (block, layer_past) in enumerate(zip(self.blocks, past_key_values)):
548
+ if output_hidden_states:
549
+ all_hidden_states = all_hidden_states + (hidden_states,)
550
+
551
+ if self.gradient_checkpointing and self.training:
552
+
553
+ def create_custom_forward(module):
554
+ def custom_forward(*inputs):
555
+ return module(*inputs)
556
+
557
+ return custom_forward
558
+
559
+ outputs = torch.utils.checkpoint.checkpoint(
560
+ create_custom_forward(block),
561
+ hidden_states,
562
+ layer_past,
563
+ use_cache,
564
+ output_attentions,
565
+ )
566
+ else:
567
+ outputs = block(hidden_states, layer_past, use_cache, output_attentions)
568
+
569
+ hidden_states = outputs[0]
570
+ if use_cache is True:
571
+ presents = presents + (outputs[1],)
572
+
573
+ if output_attentions:
574
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
575
+
576
+ # [ batch_size x sequence_length x embedding_dim ]
577
+ hidden_state = self.ln_f(hidden_states)
578
+
579
+ if output_hidden_states:
580
+ all_hidden_states = all_hidden_states + (hidden_states,)
581
+
582
+ hidden_states_pad, n_pad = self.pad_to_full_observation(hidden_state)
583
+
584
+ logits = self.head(hidden_states_pad)
585
+ logits = logits.reshape(batch_size, sequence_length + n_pad, self.vocab_size + 1)
586
+ logits = logits[:, :sequence_length]
587
+
588
+ # if we are given some desired targets also calculate the loss
589
+ if targets is not None:
590
+ loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.view(-1), reduction="none")
591
+ if self.action_weight != 1 or self.reward_weight != 1 or self.value_weight != 1:
592
+ # make weights
593
+ n_states = int(np.ceil(sequence_length / self.transition_dim))
594
+ weights = torch.cat(
595
+ [
596
+ torch.ones(self.observation_dim, device=trajectories.device),
597
+ torch.ones(self.action_dim, device=trajectories.device) * self.action_weight,
598
+ torch.ones(1, device=trajectories.device) * self.reward_weight,
599
+ torch.ones(1, device=trajectories.device) * self.value_weight,
600
+ ]
601
+ )
602
+ weights = weights.repeat(n_states)
603
+ weights = weights[1:].repeat(batch_size, 1)
604
+ loss = loss * weights.view(-1)
605
+ loss = (loss * attention_mask.view(-1)).mean()
606
+ else:
607
+ loss = None
608
+
609
+ if not return_dict:
610
+ return tuple(v for v in [loss, logits, presents, all_hidden_states, all_self_attentions] if v is not None)
611
+
612
+ return TrajectoryTransformerOutput(
613
+ loss=loss,
614
+ logits=logits,
615
+ past_key_values=presents,
616
+ hidden_states=all_hidden_states,
617
+ attentions=all_self_attentions,
618
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 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
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
18
+
19
+
20
+ _import_structure = {
21
+ "configuration_transfo_xl": ["TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "TransfoXLConfig"],
22
+ "tokenization_transfo_xl": ["TransfoXLCorpus", "TransfoXLTokenizer"],
23
+ }
24
+
25
+ try:
26
+ if not is_torch_available():
27
+ raise OptionalDependencyNotAvailable()
28
+ except OptionalDependencyNotAvailable:
29
+ pass
30
+ else:
31
+ _import_structure["modeling_transfo_xl"] = [
32
+ "TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
33
+ "AdaptiveEmbedding",
34
+ "TransfoXLForSequenceClassification",
35
+ "TransfoXLLMHeadModel",
36
+ "TransfoXLModel",
37
+ "TransfoXLPreTrainedModel",
38
+ "load_tf_weights_in_transfo_xl",
39
+ ]
40
+
41
+ try:
42
+ if not is_tf_available():
43
+ raise OptionalDependencyNotAvailable()
44
+ except OptionalDependencyNotAvailable:
45
+ pass
46
+ else:
47
+ _import_structure["modeling_tf_transfo_xl"] = [
48
+ "TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
49
+ "TFAdaptiveEmbedding",
50
+ "TFTransfoXLForSequenceClassification",
51
+ "TFTransfoXLLMHeadModel",
52
+ "TFTransfoXLMainLayer",
53
+ "TFTransfoXLModel",
54
+ "TFTransfoXLPreTrainedModel",
55
+ ]
56
+
57
+
58
+ if TYPE_CHECKING:
59
+ from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig
60
+ from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer
61
+
62
+ try:
63
+ if not is_torch_available():
64
+ raise OptionalDependencyNotAvailable()
65
+ except OptionalDependencyNotAvailable:
66
+ pass
67
+ else:
68
+ from .modeling_transfo_xl import (
69
+ TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
70
+ AdaptiveEmbedding,
71
+ TransfoXLForSequenceClassification,
72
+ TransfoXLLMHeadModel,
73
+ TransfoXLModel,
74
+ TransfoXLPreTrainedModel,
75
+ load_tf_weights_in_transfo_xl,
76
+ )
77
+
78
+ try:
79
+ if not is_tf_available():
80
+ raise OptionalDependencyNotAvailable()
81
+ except OptionalDependencyNotAvailable:
82
+ pass
83
+ else:
84
+ from .modeling_tf_transfo_xl import (
85
+ TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
86
+ TFAdaptiveEmbedding,
87
+ TFTransfoXLForSequenceClassification,
88
+ TFTransfoXLLMHeadModel,
89
+ TFTransfoXLMainLayer,
90
+ TFTransfoXLModel,
91
+ TFTransfoXLPreTrainedModel,
92
+ )
93
+
94
+ else:
95
+ import sys
96
+
97
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/configuration_transfo_xl.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. 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
+ """ Transformer XL configuration"""
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
25
+ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json",
26
+ }
27
+
28
+
29
+ class TransfoXLConfig(PretrainedConfig):
30
+ """
31
+ This is the configuration class to store the configuration of a [`TransfoXLModel`] or a [`TFTransfoXLModel`]. It is
32
+ used to instantiate a Transformer-XL model according to the specified arguments, defining the model architecture.
33
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the TransfoXL
34
+ [transfo-xl-wt103](https://huggingface.co/transfo-xl-wt103) architecture.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 267735):
41
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`TransfoXLModel`] or [`TFTransfoXLModel`].
43
+ cutoffs (`List[int]`, *optional*, defaults to `[20000, 40000, 200000]`):
44
+ Cutoffs for the adaptive softmax.
45
+ d_model (`int`, *optional*, defaults to 1024):
46
+ Dimensionality of the model's hidden states.
47
+ d_embed (`int`, *optional*, defaults to 1024):
48
+ Dimensionality of the embeddings
49
+ n_head (`int`, *optional*, defaults to 16):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ d_head (`int`, *optional*, defaults to 64):
52
+ Dimensionality of the model's heads.
53
+ d_inner (`int`, *optional*, defaults to 4096):
54
+ Inner dimension in FF
55
+ div_val (`int`, *optional*, defaults to 4):
56
+ Divident value for adapative input and softmax
57
+ pre_lnorm (`boolean`, *optional*, defaults to `False`):
58
+ Whether or not to apply LayerNorm to the input instead of the output in the blocks.
59
+ n_layer (`int`, *optional*, defaults to 18):
60
+ Number of hidden layers in the Transformer encoder.
61
+ mem_len (`int`, *optional*, defaults to 1600):
62
+ Length of the retained previous heads.
63
+ clamp_len (`int`, *optional*, defaults to 1000):
64
+ Use the same pos embeddings after clamp_len.
65
+ same_length (`boolean`, *optional*, defaults to `True`):
66
+ Whether or not to use the same attn length for all tokens
67
+ proj_share_all_but_first (`boolean`, *optional*, defaults to `True`):
68
+ True to share all but first projs, False not to share.
69
+ attn_type (`int`, *optional*, defaults to 0):
70
+ Attention type. 0 for Transformer-XL, 1 for Shaw et al, 2 for Vaswani et al, 3 for Al Rfou et al.
71
+ sample_softmax (`int`, *optional*, defaults to -1):
72
+ Number of samples in the sampled softmax.
73
+ adaptive (`boolean`, *optional*, defaults to `True`):
74
+ Whether or not to use adaptive softmax.
75
+ dropout (`float`, *optional*, defaults to 0.1):
76
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
77
+ dropatt (`float`, *optional*, defaults to 0):
78
+ The dropout ratio for the attention probabilities.
79
+ untie_r (`boolean`, *optional*, defaults to `True`):
80
+ Whether ot not to untie relative position biases.
81
+ init (`str`, *optional*, defaults to `"normal"`):
82
+ Parameter initializer to use.
83
+ init_range (`float`, *optional*, defaults to 0.01):
84
+ Parameters initialized by U(-init_range, init_range).
85
+ proj_init_std (`float`, *optional*, defaults to 0.01):
86
+ Parameters initialized by N(0, init_std)
87
+ init_std (`float`, *optional*, defaults to 0.02):
88
+ Parameters initialized by N(0, init_std)
89
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
90
+ The epsilon to use in the layer normalization layers
91
+
92
+ Examples:
93
+
94
+ ```python
95
+ >>> from transformers import TransfoXLConfig, TransfoXLModel
96
+
97
+ >>> # Initializing a Transformer XL configuration
98
+ >>> configuration = TransfoXLConfig()
99
+
100
+ >>> # Initializing a model (with random weights) from the configuration
101
+ >>> model = TransfoXLModel(configuration)
102
+
103
+ >>> # Accessing the model configuration
104
+ >>> configuration = model.config
105
+ ```"""
106
+
107
+ model_type = "transfo-xl"
108
+ keys_to_ignore_at_inference = ["mems"]
109
+ attribute_map = {
110
+ "n_token": "vocab_size",
111
+ "hidden_size": "d_model",
112
+ "num_attention_heads": "n_head",
113
+ "num_hidden_layers": "n_layer",
114
+ }
115
+
116
+ def __init__(
117
+ self,
118
+ vocab_size=267735,
119
+ cutoffs=[20000, 40000, 200000],
120
+ d_model=1024,
121
+ d_embed=1024,
122
+ n_head=16,
123
+ d_head=64,
124
+ d_inner=4096,
125
+ div_val=4,
126
+ pre_lnorm=False,
127
+ n_layer=18,
128
+ mem_len=1600,
129
+ clamp_len=1000,
130
+ same_length=True,
131
+ proj_share_all_but_first=True,
132
+ attn_type=0,
133
+ sample_softmax=-1,
134
+ adaptive=True,
135
+ dropout=0.1,
136
+ dropatt=0.0,
137
+ untie_r=True,
138
+ init="normal",
139
+ init_range=0.01,
140
+ proj_init_std=0.01,
141
+ init_std=0.02,
142
+ layer_norm_epsilon=1e-5,
143
+ eos_token_id=0,
144
+ **kwargs,
145
+ ):
146
+ self.vocab_size = vocab_size
147
+ self.cutoffs = []
148
+ self.cutoffs.extend(cutoffs)
149
+ if proj_share_all_but_first:
150
+ self.tie_projs = [False] + [True] * len(self.cutoffs)
151
+ else:
152
+ self.tie_projs = [False] + [False] * len(self.cutoffs)
153
+ self.d_model = d_model
154
+ self.d_embed = d_embed
155
+ self.d_head = d_head
156
+ self.d_inner = d_inner
157
+ self.div_val = div_val
158
+ self.pre_lnorm = pre_lnorm
159
+ self.n_layer = n_layer
160
+ self.n_head = n_head
161
+ self.mem_len = mem_len
162
+ self.same_length = same_length
163
+ self.attn_type = attn_type
164
+ self.clamp_len = clamp_len
165
+ self.sample_softmax = sample_softmax
166
+ self.adaptive = adaptive
167
+ self.dropout = dropout
168
+ self.dropatt = dropatt
169
+ self.untie_r = untie_r
170
+ self.init = init
171
+ self.init_range = init_range
172
+ self.proj_init_std = proj_init_std
173
+ self.init_std = init_std
174
+ self.layer_norm_epsilon = layer_norm_epsilon
175
+ super().__init__(eos_token_id=eos_token_id, **kwargs)
176
+
177
+ @property
178
+ def max_position_embeddings(self):
179
+ # Message copied from Transformer-XL documentation
180
+ logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
181
+ return -1
182
+
183
+ @max_position_embeddings.setter
184
+ def max_position_embeddings(self, value):
185
+ # Message copied from Transformer-XL documentation
186
+ raise NotImplementedError(
187
+ f"The model {self.model_type} is one of the few models that has no sequence length limit."
188
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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 Transformer XL checkpoint and datasets."""
16
+
17
+
18
+ import argparse
19
+ import os
20
+ import pickle
21
+ import sys
22
+
23
+ import torch
24
+
25
+ from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
26
+ from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
27
+ from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
28
+ from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
29
+
30
+
31
+ logging.set_verbosity_info()
32
+
33
+ # We do this to be able to load python 2 datasets pickles
34
+ # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
35
+ data_utils.Vocab = data_utils.TransfoXLTokenizer
36
+ data_utils.Corpus = data_utils.TransfoXLCorpus
37
+ sys.modules["data_utils"] = data_utils
38
+ sys.modules["vocabulary"] = data_utils
39
+
40
+
41
+ def convert_transfo_xl_checkpoint_to_pytorch(
42
+ tf_checkpoint_path, transfo_xl_config_file, pytorch_dump_folder_path, transfo_xl_dataset_file
43
+ ):
44
+ if transfo_xl_dataset_file:
45
+ # Convert a pre-processed corpus (see original TensorFlow repo)
46
+ with open(transfo_xl_dataset_file, "rb") as fp:
47
+ corpus = pickle.load(fp, encoding="latin1")
48
+ # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
49
+ pytorch_vocab_dump_path = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
50
+ print(f"Save vocabulary to {pytorch_vocab_dump_path}")
51
+ corpus_vocab_dict = corpus.vocab.__dict__
52
+ torch.save(corpus_vocab_dict, pytorch_vocab_dump_path)
53
+
54
+ corpus_dict_no_vocab = corpus.__dict__
55
+ corpus_dict_no_vocab.pop("vocab", None)
56
+ pytorch_dataset_dump_path = pytorch_dump_folder_path + "/" + CORPUS_NAME
57
+ print(f"Save dataset to {pytorch_dataset_dump_path}")
58
+ torch.save(corpus_dict_no_vocab, pytorch_dataset_dump_path)
59
+
60
+ if tf_checkpoint_path:
61
+ # Convert a pre-trained TensorFlow model
62
+ config_path = os.path.abspath(transfo_xl_config_file)
63
+ tf_path = os.path.abspath(tf_checkpoint_path)
64
+
65
+ print(f"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.")
66
+ # Initialise PyTorch model
67
+ if transfo_xl_config_file == "":
68
+ config = TransfoXLConfig()
69
+ else:
70
+ config = TransfoXLConfig.from_json_file(transfo_xl_config_file)
71
+ print(f"Building PyTorch model from configuration: {config}")
72
+ model = TransfoXLLMHeadModel(config)
73
+
74
+ model = load_tf_weights_in_transfo_xl(model, config, tf_path)
75
+ # Save pytorch-model
76
+ pytorch_weights_dump_path = os.path.join(pytorch_dump_folder_path, WEIGHTS_NAME)
77
+ pytorch_config_dump_path = os.path.join(pytorch_dump_folder_path, CONFIG_NAME)
78
+ print(f"Save PyTorch model to {os.path.abspath(pytorch_weights_dump_path)}")
79
+ torch.save(model.state_dict(), pytorch_weights_dump_path)
80
+ print(f"Save configuration file to {os.path.abspath(pytorch_config_dump_path)}")
81
+ with open(pytorch_config_dump_path, "w", encoding="utf-8") as f:
82
+ f.write(config.to_json_string())
83
+
84
+
85
+ if __name__ == "__main__":
86
+ parser = argparse.ArgumentParser()
87
+ parser.add_argument(
88
+ "--pytorch_dump_folder_path",
89
+ default=None,
90
+ type=str,
91
+ required=True,
92
+ help="Path to the folder to store the PyTorch model or dataset/vocab.",
93
+ )
94
+ parser.add_argument(
95
+ "--tf_checkpoint_path",
96
+ default="",
97
+ type=str,
98
+ help="An optional path to a TensorFlow checkpoint path to be converted.",
99
+ )
100
+ parser.add_argument(
101
+ "--transfo_xl_config_file",
102
+ default="",
103
+ type=str,
104
+ help=(
105
+ "An optional config json file corresponding to the pre-trained BERT model. \n"
106
+ "This specifies the model architecture."
107
+ ),
108
+ )
109
+ parser.add_argument(
110
+ "--transfo_xl_dataset_file",
111
+ default="",
112
+ type=str,
113
+ help="An optional dataset file to be converted in a vocabulary.",
114
+ )
115
+ args = parser.parse_args()
116
+ convert_transfo_xl_checkpoint_to_pytorch(
117
+ args.tf_checkpoint_path,
118
+ args.transfo_xl_config_file,
119
+ args.pytorch_dump_folder_path,
120
+ args.transfo_xl_dataset_file,
121
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_tf_transfo_xl.py ADDED
@@ -0,0 +1,1165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. 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
+ """
17
+ TF 2.0 Transformer XL model.
18
+ """
19
+
20
+ from dataclasses import dataclass
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import numpy as np
24
+ import tensorflow as tf
25
+
26
+ from ...modeling_tf_utils import (
27
+ TFModelInputType,
28
+ TFPreTrainedModel,
29
+ TFSequenceClassificationLoss,
30
+ get_initializer,
31
+ keras_serializable,
32
+ unpack_inputs,
33
+ )
34
+ from ...tf_utils import shape_list, stable_softmax
35
+ from ...utils import (
36
+ ModelOutput,
37
+ add_code_sample_docstrings,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ logging,
41
+ )
42
+ from .configuration_transfo_xl import TransfoXLConfig
43
+ from .modeling_tf_transfo_xl_utilities import TFAdaptiveSoftmaxMask
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+ _CHECKPOINT_FOR_DOC = "transfo-xl-wt103"
49
+ _CONFIG_FOR_DOC = "TransfoXLConfig"
50
+
51
+ TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [
52
+ "transfo-xl-wt103",
53
+ # See all Transformer XL models at https://huggingface.co/models?filter=transfo-xl
54
+ ]
55
+
56
+
57
+ class TFPositionalEmbedding(tf.keras.layers.Layer):
58
+ def __init__(self, demb, **kwargs):
59
+ super().__init__(**kwargs)
60
+
61
+ self.inv_freq = 1 / (10000 ** (tf.range(0, demb, 2.0) / demb))
62
+
63
+ def call(self, pos_seq, bsz=None):
64
+ self.inv_freq = tf.cast(self.inv_freq, dtype=pos_seq.dtype)
65
+ sinusoid_inp = tf.einsum("i,j->ij", pos_seq, self.inv_freq)
66
+ pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1)
67
+
68
+ if bsz is not None:
69
+ return tf.tile(pos_emb[:, None, :], [1, bsz, 1])
70
+ else:
71
+ return pos_emb[:, None, :]
72
+
73
+
74
+ class TFPositionwiseFF(tf.keras.layers.Layer):
75
+ def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5, init_std=0.02, **kwargs):
76
+ super().__init__(**kwargs)
77
+
78
+ self.d_model = d_model
79
+ self.d_inner = d_inner
80
+ self.dropout = dropout
81
+
82
+ self.layer_1 = tf.keras.layers.Dense(
83
+ d_inner, kernel_initializer=get_initializer(init_std), activation=tf.nn.relu, name="CoreNet_._0"
84
+ )
85
+ self.drop_1 = tf.keras.layers.Dropout(dropout)
86
+ self.layer_2 = tf.keras.layers.Dense(d_model, kernel_initializer=get_initializer(init_std), name="CoreNet_._3")
87
+ self.drop_2 = tf.keras.layers.Dropout(dropout)
88
+
89
+ self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
90
+
91
+ self.pre_lnorm = pre_lnorm
92
+
93
+ def call(self, inp, training=False):
94
+ if self.pre_lnorm:
95
+ # layer normalization + positionwise feed-forward
96
+ core_out = self.layer_norm(inp)
97
+ core_out = self.layer_1(core_out)
98
+ core_out = self.drop_1(core_out, training=training)
99
+ core_out = self.layer_2(core_out)
100
+ core_out = self.drop_2(core_out, training=training)
101
+
102
+ # residual connection
103
+ output = core_out + inp
104
+ else:
105
+ # positionwise feed-forward
106
+ core_out = self.layer_1(inp)
107
+ core_out = self.drop_1(core_out, training=training)
108
+ core_out = self.layer_2(core_out)
109
+ core_out = self.drop_2(core_out, training=training)
110
+
111
+ # residual connection + layer normalization
112
+ output = self.layer_norm(inp + core_out)
113
+
114
+ return output
115
+
116
+
117
+ class TFRelPartialLearnableMultiHeadAttn(tf.keras.layers.Layer):
118
+ def __init__(
119
+ self,
120
+ n_head,
121
+ d_model,
122
+ d_head,
123
+ dropout,
124
+ dropatt=0.0,
125
+ pre_lnorm=False,
126
+ r_r_bias=None,
127
+ r_w_bias=None,
128
+ layer_norm_epsilon=1e-5,
129
+ init_std=0.02,
130
+ output_attentions=False,
131
+ **kwargs,
132
+ ):
133
+ super().__init__(**kwargs)
134
+
135
+ self.n_head = n_head
136
+ self.d_model = d_model
137
+ self.d_head = d_head
138
+ self.dropout = dropout
139
+ self.output_attentions = output_attentions
140
+
141
+ self.qkv_net = tf.keras.layers.Dense(
142
+ 3 * n_head * d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="qkv_net"
143
+ )
144
+
145
+ self.drop = tf.keras.layers.Dropout(dropout)
146
+ self.dropatt = tf.keras.layers.Dropout(dropatt)
147
+ self.o_net = tf.keras.layers.Dense(
148
+ d_model, kernel_initializer=get_initializer(init_std), use_bias=False, name="o_net"
149
+ )
150
+
151
+ self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
152
+
153
+ self.scale = 1 / (d_head**0.5)
154
+
155
+ self.pre_lnorm = pre_lnorm
156
+
157
+ if r_r_bias is not None and r_w_bias is not None: # Biases are shared
158
+ self.r_r_bias = r_r_bias
159
+ self.r_w_bias = r_w_bias
160
+ else:
161
+ self.r_r_bias = None
162
+ self.r_w_bias = None
163
+
164
+ self.r_net = tf.keras.layers.Dense(
165
+ self.n_head * self.d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="r_net"
166
+ )
167
+
168
+ def build(self, input_shape):
169
+ if self.r_r_bias is None or self.r_w_bias is None: # Biases are not shared
170
+ self.r_r_bias = self.add_weight(
171
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
172
+ )
173
+ self.r_w_bias = self.add_weight(
174
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
175
+ )
176
+ super().build(input_shape)
177
+
178
+ def _rel_shift(self, x):
179
+ x_size = shape_list(x)
180
+
181
+ x = tf.pad(x, [[0, 0], [1, 0], [0, 0], [0, 0]])
182
+ x = tf.reshape(x, [x_size[1] + 1, x_size[0], x_size[2], x_size[3]])
183
+ x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1])
184
+ x = tf.reshape(x, x_size)
185
+
186
+ return x
187
+
188
+ def call(self, w, r, attn_mask, mems, head_mask, output_attentions, training=False):
189
+ qlen, rlen, bsz = shape_list(w)[0], shape_list(r)[0], shape_list(w)[1]
190
+
191
+ if mems is not None:
192
+ mems = tf.cast(mems, dtype=w.dtype)
193
+ cat = tf.concat([mems, w], 0)
194
+ if self.pre_lnorm:
195
+ w_heads = self.qkv_net(self.layer_norm(cat))
196
+ else:
197
+ w_heads = self.qkv_net(cat)
198
+ r_head_k = self.r_net(r)
199
+
200
+ w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
201
+ w_head_q = w_head_q[-qlen:]
202
+ else:
203
+ if self.pre_lnorm:
204
+ w_heads = self.qkv_net(self.layer_norm(w))
205
+ else:
206
+ w_heads = self.qkv_net(w)
207
+ r_head_k = self.r_net(r)
208
+
209
+ w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
210
+
211
+ klen = shape_list(w_head_k)[0]
212
+
213
+ w_head_q = tf.reshape(w_head_q, (qlen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
214
+ w_head_k = tf.reshape(w_head_k, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
215
+ w_head_v = tf.reshape(w_head_v, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
216
+
217
+ r_head_k = tf.reshape(r_head_k, (rlen, self.n_head, self.d_head)) # qlen x n_head x d_head
218
+
219
+ # compute attention score
220
+ rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
221
+ AC = tf.einsum("ibnd,jbnd->ijbn", rw_head_q, w_head_k) # qlen x klen x bsz x n_head
222
+
223
+ rr_head_q = w_head_q + self.r_r_bias
224
+ BD = tf.einsum("ibnd,jnd->ijbn", rr_head_q, r_head_k) # qlen x klen x bsz x n_head
225
+ BD = self._rel_shift(BD)
226
+
227
+ # [qlen x klen x bsz x n_head]
228
+ attn_score = AC + BD
229
+ attn_score = attn_score * self.scale
230
+
231
+ # compute attention probability
232
+ if attn_mask is not None:
233
+ attn_mask_t = attn_mask[:, :, None, None]
234
+ attn_mask_t = tf.cast(attn_mask_t, dtype=attn_score.dtype)
235
+ attn_score = attn_score * (1.0 - attn_mask_t) - 1e30 * attn_mask_t
236
+
237
+ # [qlen x klen x bsz x n_head]
238
+ attn_prob = stable_softmax(attn_score, axis=1)
239
+ attn_prob = self.dropatt(attn_prob, training=training)
240
+
241
+ # Mask heads if we want to
242
+ if head_mask is not None:
243
+ attn_prob = attn_prob * head_mask
244
+
245
+ # compute attention vector
246
+ attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, w_head_v)
247
+
248
+ # [qlen x bsz x n_head x d_head]
249
+ attn_vec_sizes = shape_list(attn_vec)
250
+ attn_vec = tf.reshape(attn_vec, (attn_vec_sizes[0], attn_vec_sizes[1], self.n_head * self.d_head))
251
+
252
+ # linear projection
253
+ attn_out = self.o_net(attn_vec)
254
+ attn_out = self.drop(attn_out, training=training)
255
+
256
+ if self.pre_lnorm:
257
+ # residual connection
258
+ outputs = [w + attn_out]
259
+ else:
260
+ # residual connection + layer normalization
261
+ outputs = [self.layer_norm(w + attn_out)]
262
+
263
+ if output_attentions:
264
+ outputs.append(attn_prob)
265
+
266
+ return outputs
267
+
268
+
269
+ class TFRelPartialLearnableDecoderLayer(tf.keras.layers.Layer):
270
+ def __init__(
271
+ self,
272
+ n_head,
273
+ d_model,
274
+ d_head,
275
+ d_inner,
276
+ dropout,
277
+ dropatt=0.0,
278
+ pre_lnorm=False,
279
+ r_w_bias=None,
280
+ r_r_bias=None,
281
+ layer_norm_epsilon=1e-5,
282
+ init_std=0.02,
283
+ output_attentions=False,
284
+ **kwargs,
285
+ ):
286
+ super().__init__(**kwargs)
287
+
288
+ self.dec_attn = TFRelPartialLearnableMultiHeadAttn(
289
+ n_head,
290
+ d_model,
291
+ d_head,
292
+ dropout,
293
+ dropatt=dropatt,
294
+ pre_lnorm=pre_lnorm,
295
+ r_w_bias=r_w_bias,
296
+ r_r_bias=r_r_bias,
297
+ init_std=init_std,
298
+ layer_norm_epsilon=layer_norm_epsilon,
299
+ output_attentions=output_attentions,
300
+ name="dec_attn",
301
+ )
302
+ self.pos_ff = TFPositionwiseFF(
303
+ d_model,
304
+ d_inner,
305
+ dropout,
306
+ pre_lnorm=pre_lnorm,
307
+ init_std=init_std,
308
+ layer_norm_epsilon=layer_norm_epsilon,
309
+ name="pos_ff",
310
+ )
311
+
312
+ def call(self, dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=False):
313
+ attn_outputs = self.dec_attn(dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=training)
314
+ ff_output = self.pos_ff(attn_outputs[0], training=training)
315
+
316
+ outputs = [ff_output] + attn_outputs[1:]
317
+
318
+ return outputs
319
+
320
+
321
+ class TFTransfoEmbeddings(tf.keras.layers.Layer):
322
+ def __init__(self, vocab_size, emb_size, init_std, **kwargs):
323
+ super().__init__(**kwargs)
324
+
325
+ self.vocab_size = vocab_size
326
+ self.emb_size = emb_size
327
+ self.init_std = init_std
328
+
329
+ def build(self, input_shape):
330
+ self.weight = self.add_weight(
331
+ shape=(self.vocab_size, self.emb_size),
332
+ initializer=get_initializer(self.init_std),
333
+ name="embeddings",
334
+ )
335
+
336
+ super().build(input_shape)
337
+
338
+ def call(self, inputs):
339
+ return tf.gather(self.weight, inputs)
340
+
341
+
342
+ class TFAdaptiveEmbedding(tf.keras.layers.Layer):
343
+ def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, init_std=0.02, sample_softmax=False, **kwargs):
344
+ super().__init__(**kwargs)
345
+
346
+ self.n_token = n_token
347
+ self.d_embed = d_embed
348
+ self.init_std = init_std
349
+
350
+ self.cutoffs = cutoffs + [n_token]
351
+ self.div_val = div_val
352
+ self.d_proj = d_proj
353
+
354
+ self.emb_scale = d_proj**0.5
355
+
356
+ self.cutoff_ends = [0] + self.cutoffs
357
+
358
+ self.emb_layers = []
359
+ self.emb_projs = []
360
+
361
+ if div_val == 1:
362
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
363
+ else:
364
+ for i in range(len(self.cutoffs)):
365
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
366
+ d_emb_i = d_embed // (div_val**i)
367
+ self.emb_layers.append(
368
+ TFTransfoEmbeddings(
369
+ r_idx - l_idx,
370
+ d_emb_i,
371
+ init_std,
372
+ name=f"emb_layers_._{i}",
373
+ )
374
+ )
375
+
376
+ def build(self, input_shape):
377
+ for i in range(len(self.cutoffs)):
378
+ d_emb_i = self.d_embed // (self.div_val**i)
379
+ self.emb_projs.append(
380
+ self.add_weight(
381
+ shape=(d_emb_i, self.d_proj),
382
+ initializer=get_initializer(self.init_std),
383
+ trainable=True,
384
+ name=f"emb_projs_._{i}",
385
+ )
386
+ )
387
+
388
+ super().build(input_shape)
389
+
390
+ def call(self, inp):
391
+ if self.div_val == 1:
392
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
393
+ else:
394
+ inp_flat = tf.reshape(inp, (-1,))
395
+ emb_flat = tf.zeros([shape_list(inp_flat)[0], self.d_proj])
396
+ for i in range(len(self.cutoffs)):
397
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
398
+
399
+ mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
400
+
401
+ inp_i = tf.boolean_mask(inp_flat, mask_i) - l_idx
402
+ emb_i = self.emb_layers[i](inp_i)
403
+ emb_i = tf.einsum("id,de->ie", emb_i, self.emb_projs[i])
404
+
405
+ mask_idx = tf.where(mask_i)
406
+ scatter = tf.scatter_nd(mask_idx, emb_i, shape_list(emb_flat))
407
+ emb_flat = tf.cast(emb_flat, dtype=scatter.dtype)
408
+ emb_flat += scatter
409
+
410
+ embed_shape = shape_list(inp) + [self.d_proj]
411
+ embed = tf.reshape(emb_flat, embed_shape)
412
+
413
+ embed *= self.emb_scale
414
+
415
+ return embed
416
+
417
+
418
+ @keras_serializable
419
+ class TFTransfoXLMainLayer(tf.keras.layers.Layer):
420
+ config_class = TransfoXLConfig
421
+
422
+ def __init__(self, config, **kwargs):
423
+ super().__init__(**kwargs)
424
+
425
+ self.config = config
426
+ self.output_hidden_states = config.output_hidden_states
427
+ self.output_attentions = config.output_attentions
428
+ self.return_dict = config.use_return_dict
429
+
430
+ self.n_token = config.vocab_size
431
+
432
+ self.d_embed = config.d_embed
433
+ self.d_model = config.d_model
434
+ self.n_head = config.n_head
435
+ self.d_head = config.d_head
436
+ self.untie_r = config.untie_r
437
+
438
+ self.word_emb = TFAdaptiveEmbedding(
439
+ config.vocab_size,
440
+ config.d_embed,
441
+ config.d_model,
442
+ config.cutoffs,
443
+ div_val=config.div_val,
444
+ init_std=config.init_std,
445
+ name="word_emb",
446
+ )
447
+
448
+ self.drop = tf.keras.layers.Dropout(config.dropout)
449
+
450
+ self.n_layer = config.n_layer
451
+ self.mem_len = config.mem_len
452
+ self.attn_type = config.attn_type
453
+
454
+ self.layers = []
455
+ if config.attn_type == 0: # the default attention
456
+ for i in range(config.n_layer):
457
+ self.layers.append(
458
+ TFRelPartialLearnableDecoderLayer(
459
+ config.n_head,
460
+ config.d_model,
461
+ config.d_head,
462
+ config.d_inner,
463
+ config.dropout,
464
+ dropatt=config.dropatt,
465
+ pre_lnorm=config.pre_lnorm,
466
+ r_w_bias=None if self.untie_r else self.r_w_bias,
467
+ r_r_bias=None if self.untie_r else self.r_r_bias,
468
+ layer_norm_epsilon=config.layer_norm_epsilon,
469
+ init_std=config.init_std,
470
+ output_attentions=self.output_attentions,
471
+ name=f"layers_._{i}",
472
+ )
473
+ )
474
+ else: # learnable embeddings and absolute embeddings
475
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
476
+
477
+ self.same_length = config.same_length
478
+ self.clamp_len = config.clamp_len
479
+
480
+ if self.attn_type == 0: # default attention
481
+ self.pos_emb = TFPositionalEmbedding(self.d_model, name="pos_emb")
482
+ else: # learnable embeddings and absolute embeddings
483
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
484
+
485
+ def build(self, input_shape):
486
+ if not self.untie_r:
487
+ self.r_w_bias = self.add_weight(
488
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
489
+ )
490
+ self.r_r_bias = self.add_weight(
491
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
492
+ )
493
+ super().build(input_shape)
494
+
495
+ def get_input_embeddings(self):
496
+ return self.word_emb
497
+
498
+ def set_input_embeddings(self, value):
499
+ raise NotImplementedError
500
+
501
+ def backward_compatible(self):
502
+ self.sample_softmax = -1
503
+
504
+ def reset_memory_length(self, mem_len):
505
+ self.mem_len = mem_len
506
+
507
+ def _prune_heads(self, heads):
508
+ raise NotImplementedError
509
+
510
+ def init_mems(self, bsz):
511
+ if self.mem_len > 0:
512
+ mems = []
513
+ for i in range(self.n_layer):
514
+ empty = tf.zeros([self.mem_len, bsz, self.d_model])
515
+ mems.append(empty)
516
+
517
+ return mems
518
+ else:
519
+ return None
520
+
521
+ def _update_mems(self, hids, mems, mlen, qlen):
522
+ # does not deal with None
523
+ if mems is None:
524
+ return None
525
+
526
+ # mems is not None
527
+ assert len(hids) == len(mems), "len(hids) != len(mems)"
528
+
529
+ # There are `mlen + qlen` steps that can be cached into mems
530
+ new_mems = []
531
+ end_idx = mlen + tf.math.maximum(0, qlen)
532
+ beg_idx = tf.math.maximum(0, end_idx - tf.convert_to_tensor(self.mem_len))
533
+ for i in range(len(hids)):
534
+ mems[i] = tf.cast(mems[i], dtype=hids[i].dtype)
535
+ cat = tf.concat([mems[i], hids[i]], axis=0)
536
+ tf.stop_gradient(cat)
537
+ new_mems.append(cat[beg_idx:end_idx])
538
+
539
+ return new_mems
540
+
541
+ @unpack_inputs
542
+ def call(
543
+ self,
544
+ input_ids: Optional[TFModelInputType] = None,
545
+ mems: Optional[List[tf.Tensor]] = None,
546
+ head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
547
+ inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
548
+ output_attentions: Optional[bool] = None,
549
+ output_hidden_states: Optional[bool] = None,
550
+ return_dict: Optional[bool] = None,
551
+ labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
552
+ training: bool = False,
553
+ ):
554
+ # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
555
+ # so we transpose here from shape [bsz, len] to shape [len, bsz]
556
+ if input_ids is not None and inputs_embeds is not None:
557
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
558
+ elif input_ids is not None:
559
+ input_ids = tf.transpose(input_ids, perm=(1, 0))
560
+ qlen, bsz = shape_list(input_ids)
561
+ elif inputs_embeds is not None:
562
+ inputs_embeds = tf.transpose(inputs_embeds, perm=(1, 0, 2))
563
+ qlen, bsz = shape_list(inputs_embeds)[:2]
564
+ else:
565
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
566
+
567
+ if mems is None:
568
+ mems = self.init_mems(bsz)
569
+
570
+ # Prepare head mask if needed
571
+ # 1.0 in head_mask indicate we keep the head
572
+ # attention_probs has shape bsz x n_heads x N x N
573
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
574
+ # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
575
+ if head_mask is not None:
576
+ raise NotImplementedError
577
+ else:
578
+ head_mask = [None] * self.n_layer
579
+
580
+ if inputs_embeds is not None:
581
+ word_emb = inputs_embeds
582
+ else:
583
+ word_emb = self.word_emb(input_ids)
584
+
585
+ mlen = shape_list(mems[0])[0] if mems is not None else 0
586
+ klen = mlen + qlen
587
+
588
+ # Compute decoder attention mask
589
+
590
+ # ::: PyTorch masking code for reference :::
591
+ # if self.same_length:
592
+ # all_ones = word_emb.new_ones((qlen, klen), dtype=torch.uint8)
593
+ # mask_len = klen - self.mem_len
594
+ # if mask_len > 0:
595
+ # mask_shift_len = qlen - mask_len
596
+ # else:
597
+ # mask_shift_len = qlen
598
+ # dec_attn_mask = (torch.triu(all_ones, 1+mlen)
599
+ # + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1
600
+ # else:
601
+ # dec_attn_mask = torch.triu(
602
+ # word_emb.new_ones((qlen, klen), dtype=torch.uint8), diagonal=1+mlen)[:,:,None]
603
+
604
+ # TensorFlow version
605
+ dec_attn_mask = 1 - tf.linalg.band_part(
606
+ tf.ones([qlen, klen], dtype=tf.int32), -1, mlen
607
+ ) # (q, q): diagonal with 1's
608
+ if self.same_length:
609
+ mask_len = klen - self.mem_len
610
+ if mask_len > 0:
611
+ mask_shift_len = qlen - mask_len
612
+ else:
613
+ mask_shift_len = qlen
614
+ if mask_shift_len >= 1:
615
+ dec_attn_mask += 1 - tf.linalg.band_part(tf.ones([qlen, klen], dtype=tf.int32), mask_shift_len - 1, -1)
616
+ else:
617
+ dec_attn_mask += tf.linalg.band_part(tf.ones([qlen, klen], dtype=tf.int32), -1, -mask_shift_len)
618
+
619
+ hids = []
620
+ attentions = [] if output_attentions else None
621
+ if self.attn_type == 0: # default
622
+ pos_seq = tf.range(klen - 1, -1, -1.0)
623
+ if self.clamp_len > 0:
624
+ pos_seq = tf.minimum(pos_seq, self.clamp_len)
625
+ pos_emb = self.pos_emb(pos_seq)
626
+
627
+ core_out = self.drop(word_emb, training=training)
628
+ pos_emb = self.drop(pos_emb, training=training)
629
+
630
+ for i, layer in enumerate(self.layers):
631
+ hids.append(core_out)
632
+ mems_i = None if mems is None else mems[i]
633
+ layer_outputs = layer(
634
+ core_out,
635
+ pos_emb,
636
+ dec_attn_mask,
637
+ mems_i,
638
+ head_mask[i],
639
+ output_attentions,
640
+ training=training,
641
+ )
642
+ core_out = layer_outputs[0]
643
+ if output_attentions:
644
+ attentions.append(layer_outputs[1])
645
+ else: # learnable embeddings and absolute embeddings
646
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
647
+
648
+ core_out = self.drop(core_out, training=training)
649
+
650
+ new_mems = self._update_mems(hids, mems, mlen, qlen)
651
+
652
+ # We transpose back here to shape [bsz, len, hidden_dim]
653
+ core_out = tf.transpose(core_out, perm=(1, 0, 2))
654
+
655
+ if output_hidden_states:
656
+ # Transpose to library standard shape [bsz, len, hidden_dim] and add last layer
657
+ hids = tuple(tf.transpose(t, perm=(1, 0, 2)) for t in hids)
658
+ hids = hids + (core_out,)
659
+ else:
660
+ hids = None
661
+ if output_attentions:
662
+ # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
663
+ attentions = tuple(tf.transpose(t, perm=(2, 3, 0, 1)) for t in attentions)
664
+
665
+ if not return_dict:
666
+ return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
667
+
668
+ return TFTransfoXLModelOutput(
669
+ last_hidden_state=core_out,
670
+ mems=new_mems,
671
+ hidden_states=hids,
672
+ attentions=attentions,
673
+ )
674
+
675
+
676
+ class TFTransfoXLPreTrainedModel(TFPreTrainedModel):
677
+ """
678
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
679
+ models.
680
+ """
681
+
682
+ config_class = TransfoXLConfig
683
+ base_model_prefix = "transformer"
684
+
685
+ @tf.function(
686
+ input_signature=[
687
+ {
688
+ "input_ids": tf.TensorSpec((None, None), tf.int32, name="input_ids"),
689
+ }
690
+ ]
691
+ )
692
+ def serving(self, inputs):
693
+ output = self.call(inputs)
694
+
695
+ return self.serving_output(output)
696
+
697
+
698
+ @dataclass
699
+ class TFTransfoXLModelOutput(ModelOutput):
700
+ """
701
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
702
+
703
+ Args:
704
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
705
+ Sequence of hidden-states at the output of the last layer of the model.
706
+ mems (`List[tf.Tensor]` of length `config.n_layers`):
707
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
708
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
709
+ be passed as input ids as they have already been computed.
710
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
711
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
712
+ `(batch_size, sequence_length, hidden_size)`.
713
+
714
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
715
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
716
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
717
+ sequence_length)`.
718
+
719
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
720
+ heads.
721
+ """
722
+
723
+ last_hidden_state: tf.Tensor = None
724
+ mems: List[tf.Tensor] = None
725
+ hidden_states: Optional[Tuple[tf.Tensor]] = None
726
+ attentions: Optional[Tuple[tf.Tensor]] = None
727
+
728
+
729
+ @dataclass
730
+ class TFTransfoXLLMHeadModelOutput(ModelOutput):
731
+ """
732
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
733
+
734
+ Args:
735
+ losses (`tf.Tensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
736
+ Language modeling losses (not reduced).
737
+ prediction_scores (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
738
+ Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
739
+ mems (`List[tf.Tensor]` of length `config.n_layers`):
740
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
741
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
742
+ be passed as input ids as they have already been computed.
743
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
744
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
745
+ `(batch_size, sequence_length, hidden_size)`.
746
+
747
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
748
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
749
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
750
+ sequence_length)`.
751
+
752
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
753
+ heads.
754
+ """
755
+
756
+ prediction_scores: tf.Tensor = None
757
+ mems: List[tf.Tensor] = None
758
+ hidden_states: Optional[Tuple[tf.Tensor]] = None
759
+ attentions: Optional[Tuple[tf.Tensor]] = None
760
+
761
+
762
+ @dataclass
763
+ class TFTransfoXLSequenceClassifierOutputWithPast(ModelOutput):
764
+ """
765
+ Base class for outputs of sentence classification models.
766
+
767
+ Args:
768
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
769
+ Classification (or regression if config.num_labels==1) loss.
770
+ logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
771
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
772
+ mems (`List[tf.Tensor]` of length `config.n_layers`):
773
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
774
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
775
+ be passed as input ids as they have already been computed.
776
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
777
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
778
+ `(batch_size, sequence_length, hidden_size)`.
779
+
780
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
781
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
782
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
783
+ sequence_length)`.
784
+
785
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
786
+ heads.
787
+ """
788
+
789
+ loss: Optional[tf.Tensor] = None
790
+ logits: tf.Tensor = None
791
+ mems: List[tf.Tensor] = None
792
+ hidden_states: Optional[Tuple[tf.Tensor]] = None
793
+ attentions: Optional[Tuple[tf.Tensor]] = None
794
+
795
+
796
+ TRANSFO_XL_START_DOCSTRING = r"""
797
+
798
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
799
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
800
+ etc.)
801
+
802
+ This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
803
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
804
+ behavior.
805
+
806
+ <Tip>
807
+
808
+ TensorFlow models and layers in `transformers` accept two formats as input:
809
+
810
+ - having all inputs as keyword arguments (like PyTorch models), or
811
+ - having all inputs as a list, tuple or dict in the first positional argument.
812
+
813
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
814
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
815
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
816
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
817
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
818
+ positional argument:
819
+
820
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
821
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
822
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
823
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
824
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
825
+
826
+ Note that when creating models and layers with
827
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
828
+ about any of this, as you can just pass inputs like you would to any other Python function!
829
+
830
+ </Tip>
831
+
832
+ Parameters:
833
+ config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
834
+ Initializing with a config file does not load the weights associated with the model, only the
835
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
836
+ """
837
+
838
+ TRANSFO_XL_INPUTS_DOCSTRING = r"""
839
+ Args:
840
+ input_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`):
841
+ Indices of input sequence tokens in the vocabulary.
842
+
843
+ Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
844
+ [`PreTrainedTokenizer.encode`] for details.
845
+
846
+ [What are input IDs?](../glossary#input-ids)
847
+ mems (`List[tf.Tensor]` of length `config.n_layers`):
848
+ Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
849
+ `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
850
+ given to this model should not be passed as `input_ids` as they have already been computed.
851
+ head_mask (`tf.Tensor` or `Numpy array` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
852
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
853
+
854
+ - 1 indicates the head is **not masked**,
855
+ - 0 indicates the head is **masked**.
856
+ inputs_embeds (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
857
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
858
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
859
+ model's internal embedding lookup matrix.
860
+ output_attentions (`bool`, *optional*):
861
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
862
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
863
+ config will be used instead.
864
+ output_hidden_states (`bool`, *optional*):
865
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
866
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
867
+ used instead.
868
+ return_dict (`bool`, *optional*):
869
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
870
+ eager mode, in graph mode the value will always be set to True.
871
+ training (`bool`, *optional*, defaults to `False`):
872
+ Whether or not to use the model in training mode (some modules like dropout modules have different
873
+ behaviors between training and evaluation).
874
+ """
875
+
876
+
877
+ @add_start_docstrings(
878
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
879
+ TRANSFO_XL_START_DOCSTRING,
880
+ )
881
+ class TFTransfoXLModel(TFTransfoXLPreTrainedModel):
882
+ def __init__(self, config, *inputs, **kwargs):
883
+ super().__init__(config, *inputs, **kwargs)
884
+ self.transformer = TFTransfoXLMainLayer(config, name="transformer")
885
+
886
+ @unpack_inputs
887
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
888
+ @add_code_sample_docstrings(
889
+ checkpoint=_CHECKPOINT_FOR_DOC,
890
+ output_type=TFTransfoXLModelOutput,
891
+ config_class=_CONFIG_FOR_DOC,
892
+ )
893
+ def call(
894
+ self,
895
+ input_ids: Optional[TFModelInputType] = None,
896
+ mems: Optional[List[tf.Tensor]] = None,
897
+ head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
898
+ inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
899
+ output_attentions: Optional[bool] = None,
900
+ output_hidden_states: Optional[bool] = None,
901
+ return_dict: Optional[bool] = None,
902
+ training: bool = False,
903
+ ):
904
+ outputs = self.transformer(
905
+ input_ids=input_ids,
906
+ mems=mems,
907
+ head_mask=head_mask,
908
+ inputs_embeds=inputs_embeds,
909
+ output_attentions=output_attentions,
910
+ output_hidden_states=output_hidden_states,
911
+ return_dict=return_dict,
912
+ training=training,
913
+ )
914
+
915
+ return outputs
916
+
917
+ def serving_output(self, output):
918
+ hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
919
+ attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
920
+
921
+ return TFTransfoXLModelOutput(
922
+ last_hidden_state=output.last_hidden_state,
923
+ mems=tf.convert_to_tensor(output.mems),
924
+ hidden_states=hs,
925
+ attentions=attns,
926
+ )
927
+
928
+
929
+ @add_start_docstrings(
930
+ """
931
+ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
932
+ input embeddings)
933
+ """,
934
+ TRANSFO_XL_START_DOCSTRING,
935
+ )
936
+ class TFTransfoXLLMHeadModel(TFTransfoXLPreTrainedModel):
937
+ def __init__(self, config):
938
+ super().__init__(config)
939
+ self.transformer = TFTransfoXLMainLayer(config, name="transformer")
940
+ self.sample_softmax = config.sample_softmax
941
+ assert self.sample_softmax <= 0, (
942
+ "Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
943
+ " https://github.com/huggingface/transformers/issues/3310"
944
+ )
945
+
946
+ self.crit = TFAdaptiveSoftmaxMask(
947
+ config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val, name="crit"
948
+ )
949
+
950
+ def _resize_token_embeddings(self, new_num_tokens):
951
+ raise NotImplementedError()
952
+
953
+ def get_output_embeddings(self):
954
+ """Double-check if you are using adaptive softmax."""
955
+ if len(self.crit.out_layers) > 0:
956
+ return self.crit.out_layers[-1]
957
+ return None
958
+
959
+ def reset_memory_length(self, mem_len):
960
+ self.transformer.reset_memory_length(mem_len)
961
+
962
+ def init_mems(self, bsz):
963
+ return self.transformer.init_mems(bsz)
964
+
965
+ @unpack_inputs
966
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
967
+ @add_code_sample_docstrings(
968
+ checkpoint=_CHECKPOINT_FOR_DOC,
969
+ output_type=TFTransfoXLLMHeadModelOutput,
970
+ config_class=_CONFIG_FOR_DOC,
971
+ )
972
+ def call(
973
+ self,
974
+ input_ids: Optional[TFModelInputType] = None,
975
+ mems: Optional[List[tf.Tensor]] = None,
976
+ head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
977
+ inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
978
+ output_attentions: Optional[bool] = None,
979
+ output_hidden_states: Optional[bool] = None,
980
+ return_dict: Optional[bool] = None,
981
+ labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
982
+ training: bool = False,
983
+ ):
984
+ if input_ids is not None:
985
+ bsz, tgt_len = shape_list(input_ids)[:2]
986
+ else:
987
+ bsz, tgt_len = shape_list(inputs_embeds)[:2]
988
+
989
+ transformer_outputs = self.transformer(
990
+ input_ids,
991
+ mems,
992
+ head_mask,
993
+ inputs_embeds,
994
+ output_attentions,
995
+ output_hidden_states,
996
+ return_dict,
997
+ training=training,
998
+ )
999
+
1000
+ last_hidden = transformer_outputs[0]
1001
+ pred_hid = last_hidden[:, -tgt_len:]
1002
+
1003
+ softmax_output = self.crit(pred_hid, labels, training=training)
1004
+ prediction_scores = softmax_output if labels is None else ()
1005
+
1006
+ if not return_dict:
1007
+ return (prediction_scores,) + transformer_outputs[1:]
1008
+
1009
+ return TFTransfoXLLMHeadModelOutput(
1010
+ prediction_scores=prediction_scores,
1011
+ mems=transformer_outputs.mems,
1012
+ hidden_states=transformer_outputs.hidden_states,
1013
+ attentions=transformer_outputs.attentions,
1014
+ )
1015
+
1016
+ def serving_output(self, output):
1017
+ hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
1018
+ attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
1019
+
1020
+ return TFTransfoXLLMHeadModelOutput(
1021
+ prediction_scores=output.prediction_scores,
1022
+ mems=tf.convert_to_tensor(output.mems),
1023
+ hidden_states=hs,
1024
+ attentions=attns,
1025
+ )
1026
+
1027
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
1028
+ inputs = {}
1029
+
1030
+ # if past is defined in model kwargs then use it for faster decoding
1031
+ if past_key_values:
1032
+ input_ids = tf.expand_dims(input_ids[:, -1], axis=-1)
1033
+ else:
1034
+ input_ids = input_ids
1035
+
1036
+ return inputs
1037
+
1038
+
1039
+ @add_start_docstrings(
1040
+ """
1041
+ The Transfo XL Model transformer with a sequence classification head on top (linear layer).
1042
+
1043
+ [`TFTransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
1044
+ models (e.g. GPT-1,GPT-2) do.
1045
+
1046
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1047
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1048
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1049
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1050
+ each row of the batch).
1051
+ """,
1052
+ TRANSFO_XL_START_DOCSTRING,
1053
+ )
1054
+ class TFTransfoXLForSequenceClassification(TFTransfoXLPreTrainedModel, TFSequenceClassificationLoss):
1055
+ def __init__(self, config, *inputs, **kwargs):
1056
+ super().__init__(config, *inputs, **kwargs)
1057
+ self.num_labels = config.num_labels
1058
+ self.score = tf.keras.layers.Dense(
1059
+ config.num_labels,
1060
+ kernel_initializer=get_initializer(config.init_range),
1061
+ name="score",
1062
+ use_bias=False,
1063
+ )
1064
+ self.transformer = TFTransfoXLMainLayer(config, name="transformer")
1065
+
1066
+ def get_output_embeddings(self):
1067
+ return self.transformer.word_emb
1068
+
1069
+ @unpack_inputs
1070
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
1071
+ @add_code_sample_docstrings(
1072
+ checkpoint=_CHECKPOINT_FOR_DOC,
1073
+ output_type=TFTransfoXLSequenceClassifierOutputWithPast,
1074
+ config_class=_CONFIG_FOR_DOC,
1075
+ )
1076
+ def call(
1077
+ self,
1078
+ input_ids: Optional[TFModelInputType] = None,
1079
+ mems: Optional[List[tf.Tensor]] = None,
1080
+ head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
1081
+ inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
1082
+ output_attentions: Optional[bool] = None,
1083
+ output_hidden_states: Optional[bool] = None,
1084
+ return_dict: Optional[bool] = None,
1085
+ labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
1086
+ training: Optional[bool] = False,
1087
+ ) -> Union[Tuple, TFTransfoXLSequenceClassifierOutputWithPast]:
1088
+ r"""
1089
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1090
+ Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
1091
+ config.vocab_size - 1]`.
1092
+ """
1093
+ transformer_outputs = self.transformer(
1094
+ input_ids=input_ids,
1095
+ mems=mems,
1096
+ head_mask=head_mask,
1097
+ inputs_embeds=inputs_embeds,
1098
+ output_attentions=output_attentions,
1099
+ output_hidden_states=output_hidden_states,
1100
+ return_dict=return_dict,
1101
+ training=training,
1102
+ )
1103
+
1104
+ hidden_states = transformer_outputs[0]
1105
+ logits = self.score(hidden_states)
1106
+ in_logits = None
1107
+ if self.config.pad_token_id is None:
1108
+ sequence_lengths = -1
1109
+ else:
1110
+ if input_ids is not None:
1111
+ sequence_lengths = (
1112
+ tf.reduce_sum(
1113
+ tf.cast(
1114
+ tf.math.not_equal(input_ids, self.config.pad_token_id),
1115
+ dtype=input_ids.dtype,
1116
+ ),
1117
+ -1,
1118
+ keepdims=False,
1119
+ )
1120
+ - 1
1121
+ )
1122
+ in_logits = tf.gather(logits, sequence_lengths, batch_dims=1, axis=1)
1123
+ else:
1124
+ sequence_lengths = -1
1125
+ logger.warning(
1126
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1127
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1128
+ )
1129
+ loss = None
1130
+
1131
+ if labels is not None:
1132
+ if input_ids is not None:
1133
+ batch_size, sequence_length = shape_list(input_ids)[:2]
1134
+ else:
1135
+ batch_size, sequence_length = shape_list(inputs_embeds)[:2]
1136
+ assert (
1137
+ self.config.pad_token_id is not None or batch_size == 1
1138
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1139
+
1140
+ if not tf.is_tensor(sequence_lengths):
1141
+ in_logits = logits[0:batch_size, sequence_lengths]
1142
+
1143
+ loss = self.hf_compute_loss(tf.reshape(labels, [-1, 1]), tf.reshape(in_logits, [-1, self.num_labels]))
1144
+
1145
+ pooled_logits = in_logits if in_logits is not None else logits
1146
+
1147
+ if not return_dict:
1148
+ output = (pooled_logits,) + transformer_outputs[1:]
1149
+ return ((loss,) + output) if loss is not None else output
1150
+
1151
+ return TFTransfoXLSequenceClassifierOutputWithPast(
1152
+ loss=loss,
1153
+ logits=pooled_logits,
1154
+ mems=transformer_outputs.mems,
1155
+ hidden_states=transformer_outputs.hidden_states,
1156
+ attentions=transformer_outputs.attentions,
1157
+ )
1158
+
1159
+ def serving_output(self, output):
1160
+ hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
1161
+ attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
1162
+
1163
+ return TFTransfoXLSequenceClassifierOutputWithPast(
1164
+ logits=output.logits, mems=tf.convert_to_tensor(output.mems), hidden_states=hs, attentions=attns
1165
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_tf_transfo_xl_utilities.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. 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
+ """
17
+ A TF 2.0 Adaptive Softmax for Transformer XL model.
18
+ """
19
+
20
+
21
+ import tensorflow as tf
22
+
23
+ from ...tf_utils import shape_list
24
+
25
+
26
+ class TFAdaptiveSoftmaxMask(tf.keras.layers.Layer):
27
+ def __init__(self, vocab_size, d_embed, d_proj, cutoffs, div_val=1, keep_order=False, **kwargs):
28
+ super().__init__(**kwargs)
29
+
30
+ self.vocab_size = vocab_size
31
+ self.d_embed = d_embed
32
+ self.d_proj = d_proj
33
+
34
+ self.cutoffs = cutoffs + [vocab_size]
35
+ self.cutoff_ends = [0] + self.cutoffs
36
+ self.div_val = div_val
37
+
38
+ self.shortlist_size = self.cutoffs[0]
39
+ self.n_clusters = len(self.cutoffs) - 1
40
+ self.head_size = self.shortlist_size + self.n_clusters
41
+ self.keep_order = keep_order
42
+
43
+ self.out_layers = []
44
+ self.out_projs = []
45
+
46
+ def build(self, input_shape):
47
+ if self.n_clusters > 0:
48
+ self.cluster_weight = self.add_weight(
49
+ shape=(self.n_clusters, self.d_embed), initializer="zeros", trainable=True, name="cluster_weight"
50
+ )
51
+ self.cluster_bias = self.add_weight(
52
+ shape=(self.n_clusters,), initializer="zeros", trainable=True, name="cluster_bias"
53
+ )
54
+
55
+ if self.div_val == 1:
56
+ for i in range(len(self.cutoffs)):
57
+ if self.d_proj != self.d_embed:
58
+ weight = self.add_weight(
59
+ shape=(self.d_embed, self.d_proj),
60
+ initializer="zeros",
61
+ trainable=True,
62
+ name=f"out_projs_._{i}",
63
+ )
64
+ self.out_projs.append(weight)
65
+ else:
66
+ self.out_projs.append(None)
67
+ weight = self.add_weight(
68
+ shape=(self.vocab_size, self.d_embed),
69
+ initializer="zeros",
70
+ trainable=True,
71
+ name=f"out_layers_._{i}_._weight",
72
+ )
73
+ bias = self.add_weight(
74
+ shape=(self.vocab_size,),
75
+ initializer="zeros",
76
+ trainable=True,
77
+ name=f"out_layers_._{i}_._bias",
78
+ )
79
+ self.out_layers.append((weight, bias))
80
+ else:
81
+ for i in range(len(self.cutoffs)):
82
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
83
+ d_emb_i = self.d_embed // (self.div_val**i)
84
+
85
+ weight = self.add_weight(
86
+ shape=(d_emb_i, self.d_proj), initializer="zeros", trainable=True, name=f"out_projs_._{i}"
87
+ )
88
+ self.out_projs.append(weight)
89
+ weight = self.add_weight(
90
+ shape=(r_idx - l_idx, d_emb_i),
91
+ initializer="zeros",
92
+ trainable=True,
93
+ name=f"out_layers_._{i}_._weight",
94
+ )
95
+ bias = self.add_weight(
96
+ shape=(r_idx - l_idx,),
97
+ initializer="zeros",
98
+ trainable=True,
99
+ name=f"out_layers_._{i}_._bias",
100
+ )
101
+ self.out_layers.append((weight, bias))
102
+ super().build(input_shape)
103
+
104
+ @staticmethod
105
+ def _logit(x, W, b, proj=None):
106
+ y = x
107
+ if proj is not None:
108
+ y = tf.einsum("ibd,ed->ibe", y, proj)
109
+ return tf.einsum("ibd,nd->ibn", y, W) + b
110
+
111
+ @staticmethod
112
+ def _gather_logprob(logprob, target):
113
+ lp_size = shape_list(logprob)
114
+ r = tf.range(lp_size[0], dtype=target.dtype)
115
+ idx = tf.stack([r, target], 1)
116
+ return tf.gather_nd(logprob, idx)
117
+
118
+ def call(self, hidden, target, return_mean=True, training=False):
119
+ head_logprob = 0
120
+ if self.n_clusters == 0:
121
+ output = self._logit(hidden, self.out_layers[0][0], self.out_layers[0][1], self.out_projs[0])
122
+ if target is not None:
123
+ loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output)
124
+ out = tf.nn.log_softmax(output, axis=-1)
125
+ else:
126
+ hidden_sizes = shape_list(hidden)
127
+ out = []
128
+ loss = tf.zeros(hidden_sizes[:2])
129
+ for i in range(len(self.cutoffs)):
130
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
131
+ if target is not None:
132
+ mask = (target >= l_idx) & (target < r_idx)
133
+ mask_idx = tf.where(mask)
134
+ cur_target = tf.boolean_mask(target, mask) - l_idx
135
+
136
+ if self.div_val == 1:
137
+ cur_W = self.out_layers[0][0][l_idx:r_idx]
138
+ cur_b = self.out_layers[0][1][l_idx:r_idx]
139
+ else:
140
+ cur_W = self.out_layers[i][0]
141
+ cur_b = self.out_layers[i][1]
142
+
143
+ if i == 0:
144
+ cur_W = tf.concat([cur_W, self.cluster_weight], 0)
145
+ cur_b = tf.concat([cur_b, self.cluster_bias], 0)
146
+
147
+ head_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[0])
148
+ head_logprob = tf.nn.log_softmax(head_logit)
149
+ out.append(head_logprob[..., : self.cutoffs[0]])
150
+ if target is not None:
151
+ cur_head_logprob = tf.boolean_mask(head_logprob, mask)
152
+ cur_logprob = self._gather_logprob(cur_head_logprob, cur_target)
153
+ else:
154
+ tail_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[i])
155
+ tail_logprob = tf.nn.log_softmax(tail_logit)
156
+ cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
157
+ logprob_i = head_logprob[..., cluster_prob_idx, None] + tail_logprob
158
+ out.append(logprob_i)
159
+ if target is not None:
160
+ cur_head_logprob = tf.boolean_mask(head_logprob, mask)
161
+ cur_tail_logprob = tf.boolean_mask(tail_logprob, mask)
162
+ cur_logprob = self._gather_logprob(cur_tail_logprob, cur_target)
163
+ cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
164
+ if target is not None:
165
+ loss += tf.scatter_nd(mask_idx, -cur_logprob, shape_list(loss))
166
+ out = tf.concat(out, axis=-1)
167
+
168
+ if target is not None:
169
+ if return_mean:
170
+ loss = tf.reduce_mean(loss)
171
+ # Add the training-time loss value to the layer using `self.add_loss()`.
172
+ self.add_loss(loss)
173
+
174
+ # Log the loss as a metric (we could log arbitrary metrics,
175
+ # including different metrics for training and inference.
176
+ self.add_metric(loss, name=self.name, aggregation="mean" if return_mean else "")
177
+
178
+ return out
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_transfo_xl.py ADDED
@@ -0,0 +1,1294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. 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
+ """
17
+ PyTorch Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. In particular
18
+ https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py
19
+ """
20
+ import warnings
21
+ from dataclasses import dataclass
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ add_code_sample_docstrings,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ )
36
+ from .configuration_transfo_xl import TransfoXLConfig
37
+ from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CHECKPOINT_FOR_DOC = "transfo-xl-wt103"
43
+ _CONFIG_FOR_DOC = "TransfoXLConfig"
44
+
45
+ TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST = [
46
+ "transfo-xl-wt103",
47
+ # See all Transformer XL models at https://huggingface.co/models?filter=transfo-xl
48
+ ]
49
+
50
+
51
+ def build_tf_to_pytorch_map(model, config):
52
+ """
53
+ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original
54
+ PyTorch model as possible.
55
+ """
56
+ tf_to_pt_map = {}
57
+
58
+ if hasattr(model, "transformer"):
59
+ # We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax
60
+ tf_to_pt_map.update(
61
+ {
62
+ "transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight,
63
+ "transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias,
64
+ }
65
+ )
66
+ for i, (out_l, proj_l, tie_proj) in enumerate(
67
+ zip(model.crit.out_layers, model.crit.out_projs, config.tie_projs)
68
+ ):
69
+ layer_str = f"transformer/adaptive_softmax/cutoff_{i}/"
70
+ if config.tie_word_embeddings:
71
+ tf_to_pt_map.update({layer_str + "b": out_l.bias})
72
+ else:
73
+ raise NotImplementedError
74
+ # I don't think this is implemented in the TF code
75
+ tf_to_pt_map.update({layer_str + "lookup_table": out_l.weight, layer_str + "b": out_l.bias})
76
+ if not tie_proj:
77
+ tf_to_pt_map.update({layer_str + "proj": proj_l})
78
+ # Now load the rest of the transformer
79
+ model = model.transformer
80
+
81
+ # Embeddings
82
+ for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)):
83
+ layer_str = f"transformer/adaptive_embed/cutoff_{i}/"
84
+ tf_to_pt_map.update({layer_str + "lookup_table": embed_l.weight, layer_str + "proj_W": proj_l})
85
+
86
+ # Transformer blocks
87
+ for i, b in enumerate(model.layers):
88
+ layer_str = f"transformer/layer_{i}/"
89
+ tf_to_pt_map.update(
90
+ {
91
+ layer_str + "rel_attn/LayerNorm/gamma": b.dec_attn.layer_norm.weight,
92
+ layer_str + "rel_attn/LayerNorm/beta": b.dec_attn.layer_norm.bias,
93
+ layer_str + "rel_attn/o/kernel": b.dec_attn.o_net.weight,
94
+ layer_str + "rel_attn/qkv/kernel": b.dec_attn.qkv_net.weight,
95
+ layer_str + "rel_attn/r/kernel": b.dec_attn.r_net.weight,
96
+ layer_str + "ff/LayerNorm/gamma": b.pos_ff.layer_norm.weight,
97
+ layer_str + "ff/LayerNorm/beta": b.pos_ff.layer_norm.bias,
98
+ layer_str + "ff/layer_1/kernel": b.pos_ff.CoreNet[0].weight,
99
+ layer_str + "ff/layer_1/bias": b.pos_ff.CoreNet[0].bias,
100
+ layer_str + "ff/layer_2/kernel": b.pos_ff.CoreNet[3].weight,
101
+ layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias,
102
+ }
103
+ )
104
+
105
+ # Relative positioning biases
106
+ if config.untie_r:
107
+ r_r_list = []
108
+ r_w_list = []
109
+ for b in model.layers:
110
+ r_r_list.append(b.dec_attn.r_r_bias)
111
+ r_w_list.append(b.dec_attn.r_w_bias)
112
+ else:
113
+ r_r_list = [model.r_r_bias]
114
+ r_w_list = [model.r_w_bias]
115
+ tf_to_pt_map.update({"transformer/r_r_bias": r_r_list, "transformer/r_w_bias": r_w_list})
116
+ return tf_to_pt_map
117
+
118
+
119
+ def load_tf_weights_in_transfo_xl(model, config, tf_path):
120
+ """Load tf checkpoints in a pytorch model"""
121
+ try:
122
+ import numpy as np
123
+ import tensorflow as tf
124
+ except ImportError:
125
+ logger.error(
126
+ "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
127
+ "https://www.tensorflow.org/install/ for installation instructions."
128
+ )
129
+ raise
130
+ # Build TF to PyTorch weights loading map
131
+ tf_to_pt_map = build_tf_to_pytorch_map(model, config)
132
+
133
+ # Load weights from TF model
134
+ init_vars = tf.train.list_variables(tf_path)
135
+ tf_weights = {}
136
+ for name, shape in init_vars:
137
+ logger.info(f"Loading TF weight {name} with shape {shape}")
138
+ array = tf.train.load_variable(tf_path, name)
139
+ tf_weights[name] = array
140
+
141
+ for name, pointer in tf_to_pt_map.items():
142
+ assert name in tf_weights
143
+ array = tf_weights[name]
144
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
145
+ # which are not required for using pretrained model
146
+ if "kernel" in name or "proj" in name:
147
+ array = np.transpose(array)
148
+ if ("r_r_bias" in name or "r_w_bias" in name) and len(pointer) > 1:
149
+ # Here we will split the TF weights
150
+ assert len(pointer) == array.shape[0]
151
+ for i, p_i in enumerate(pointer):
152
+ arr_i = array[i, ...]
153
+ try:
154
+ assert p_i.shape == arr_i.shape
155
+ except AssertionError as e:
156
+ e.args += (p_i.shape, arr_i.shape)
157
+ raise
158
+ logger.info(f"Initialize PyTorch weight {name} for layer {i}")
159
+ p_i.data = torch.from_numpy(arr_i)
160
+ else:
161
+ try:
162
+ assert (
163
+ pointer.shape == array.shape
164
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
165
+ except AssertionError as e:
166
+ e.args += (pointer.shape, array.shape)
167
+ raise
168
+ logger.info(f"Initialize PyTorch weight {name}")
169
+ pointer.data = torch.from_numpy(array)
170
+ tf_weights.pop(name, None)
171
+ tf_weights.pop(name + "/Adam", None)
172
+ tf_weights.pop(name + "/Adam_1", None)
173
+
174
+ logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}")
175
+ return model
176
+
177
+
178
+ class PositionalEmbedding(nn.Module):
179
+ def __init__(self, demb):
180
+ super().__init__()
181
+
182
+ self.demb = demb
183
+
184
+ inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))
185
+ self.register_buffer("inv_freq", inv_freq)
186
+
187
+ def forward(self, pos_seq, bsz=None):
188
+ sinusoid_inp = torch.ger(pos_seq, self.inv_freq)
189
+ pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)
190
+
191
+ if bsz is not None:
192
+ return pos_emb[:, None, :].expand(-1, bsz, -1)
193
+ else:
194
+ return pos_emb[:, None, :]
195
+
196
+
197
+ class PositionwiseFF(nn.Module):
198
+ def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5):
199
+ super().__init__()
200
+
201
+ self.d_model = d_model
202
+ self.d_inner = d_inner
203
+ self.dropout = dropout
204
+
205
+ self.CoreNet = nn.Sequential(
206
+ nn.Linear(d_model, d_inner),
207
+ nn.ReLU(inplace=True),
208
+ nn.Dropout(dropout),
209
+ nn.Linear(d_inner, d_model),
210
+ nn.Dropout(dropout),
211
+ )
212
+
213
+ self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
214
+
215
+ self.pre_lnorm = pre_lnorm
216
+
217
+ def forward(self, inp):
218
+ if self.pre_lnorm:
219
+ # layer normalization + positionwise feed-forward
220
+ core_out = self.CoreNet(self.layer_norm(inp))
221
+
222
+ # residual connection
223
+ output = core_out + inp
224
+ else:
225
+ # positionwise feed-forward
226
+ core_out = self.CoreNet(inp)
227
+
228
+ # residual connection + layer normalization
229
+ output = self.layer_norm(inp + core_out)
230
+
231
+ return output
232
+
233
+
234
+ class RelPartialLearnableMultiHeadAttn(nn.Module):
235
+ def __init__(
236
+ self,
237
+ n_head,
238
+ d_model,
239
+ d_head,
240
+ dropout,
241
+ dropatt=0,
242
+ pre_lnorm=False,
243
+ r_r_bias=None,
244
+ r_w_bias=None,
245
+ layer_norm_epsilon=1e-5,
246
+ ):
247
+ super().__init__()
248
+
249
+ self.n_head = n_head
250
+ self.d_model = d_model
251
+ self.d_head = d_head
252
+ self.dropout = dropout
253
+
254
+ self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False)
255
+
256
+ self.drop = nn.Dropout(dropout)
257
+ self.dropatt = nn.Dropout(dropatt)
258
+ self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)
259
+
260
+ self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
261
+
262
+ self.scale = 1 / (d_head**0.5)
263
+
264
+ self.pre_lnorm = pre_lnorm
265
+
266
+ if r_r_bias is None or r_w_bias is None: # Biases are not shared
267
+ self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
268
+ self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
269
+ else:
270
+ self.r_r_bias = r_r_bias
271
+ self.r_w_bias = r_w_bias
272
+
273
+ self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False)
274
+
275
+ def _rel_shift(self, x):
276
+ zero_pad_shape = (x.size(0), 1) + x.size()[2:]
277
+ zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype)
278
+ x_padded = torch.cat([zero_pad, x], dim=1)
279
+
280
+ x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:]
281
+ x_padded = x_padded.view(*x_padded_shape)
282
+
283
+ x = x_padded[1:].view_as(x)
284
+
285
+ return x
286
+
287
+ def forward(self, w, r, attn_mask=None, mems=None, head_mask=None, output_attentions=False):
288
+ qlen, rlen, bsz = w.size(0), r.size(0), w.size(1)
289
+
290
+ if mems is not None:
291
+ cat = torch.cat([mems, w], 0)
292
+ if self.pre_lnorm:
293
+ w_heads = self.qkv_net(self.layer_norm(cat))
294
+ else:
295
+ w_heads = self.qkv_net(cat)
296
+ r_head_k = self.r_net(r)
297
+
298
+ w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
299
+ w_head_q = w_head_q[-qlen:]
300
+ else:
301
+ if self.pre_lnorm:
302
+ w_heads = self.qkv_net(self.layer_norm(w))
303
+ else:
304
+ w_heads = self.qkv_net(w)
305
+ r_head_k = self.r_net(r)
306
+
307
+ w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
308
+
309
+ klen = w_head_k.size(0)
310
+
311
+ w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
312
+ w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
313
+ w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
314
+
315
+ r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head
316
+
317
+ # compute attention score
318
+ rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
319
+ AC = torch.einsum("ibnd,jbnd->ijbn", (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head
320
+
321
+ rr_head_q = w_head_q + self.r_r_bias
322
+ BD = torch.einsum("ibnd,jnd->ijbn", (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head
323
+ BD = self._rel_shift(BD)
324
+
325
+ # [qlen x klen x bsz x n_head]
326
+ attn_score = AC + BD
327
+ attn_score.mul_(self.scale)
328
+
329
+ mask_value = torch.finfo(attn_score.dtype).min
330
+
331
+ # compute attention probability
332
+ if attn_mask is not None and torch.sum(attn_mask).item():
333
+ attn_mask = attn_mask == 1 # Switch to bool
334
+ if attn_mask.dim() == 2:
335
+ attn_score = (
336
+ attn_score.float().masked_fill(attn_mask[None, :, :, None], mask_value).type_as(attn_score)
337
+ )
338
+ elif attn_mask.dim() == 3:
339
+ attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], mask_value).type_as(attn_score)
340
+
341
+ # [qlen x klen x bsz x n_head]
342
+ attn_prob = nn.functional.softmax(attn_score, dim=1)
343
+ attn_prob = self.dropatt(attn_prob)
344
+
345
+ # Mask heads if we want to
346
+ if head_mask is not None:
347
+ attn_prob = attn_prob * head_mask
348
+
349
+ # compute attention vector
350
+ attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, w_head_v))
351
+
352
+ # [qlen x bsz x n_head x d_head]
353
+ attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)
354
+
355
+ # linear projection
356
+ attn_out = self.o_net(attn_vec)
357
+ attn_out = self.drop(attn_out)
358
+
359
+ if self.pre_lnorm:
360
+ # residual connection
361
+ outputs = [w + attn_out]
362
+ else:
363
+ # residual connection + layer normalization
364
+ outputs = [self.layer_norm(w + attn_out)]
365
+
366
+ if output_attentions:
367
+ outputs.append(attn_prob)
368
+
369
+ return outputs
370
+
371
+
372
+ class RelPartialLearnableDecoderLayer(nn.Module):
373
+ def __init__(self, n_head, d_model, d_head, d_inner, dropout, layer_norm_epsilon=1e-5, **kwargs):
374
+ super().__init__()
375
+
376
+ self.dec_attn = RelPartialLearnableMultiHeadAttn(
377
+ n_head, d_model, d_head, dropout, layer_norm_epsilon=layer_norm_epsilon, **kwargs
378
+ )
379
+ self.pos_ff = PositionwiseFF(
380
+ d_model, d_inner, dropout, pre_lnorm=kwargs.get("pre_lnorm"), layer_norm_epsilon=layer_norm_epsilon
381
+ )
382
+
383
+ def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None, output_attentions=False):
384
+ attn_outputs = self.dec_attn(
385
+ dec_inp,
386
+ r,
387
+ attn_mask=dec_attn_mask,
388
+ mems=mems,
389
+ head_mask=head_mask,
390
+ output_attentions=output_attentions,
391
+ )
392
+ ff_output = self.pos_ff(attn_outputs[0])
393
+
394
+ outputs = [ff_output] + attn_outputs[1:]
395
+
396
+ return outputs
397
+
398
+
399
+ class AdaptiveEmbedding(nn.Module):
400
+ def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, sample_softmax=False):
401
+ super().__init__()
402
+
403
+ self.n_token = n_token
404
+ self.d_embed = d_embed
405
+
406
+ self.cutoffs = cutoffs + [n_token]
407
+ self.div_val = div_val
408
+ self.d_proj = d_proj
409
+
410
+ self.emb_scale = d_proj**0.5
411
+
412
+ self.cutoff_ends = [0] + self.cutoffs
413
+
414
+ self.emb_layers = nn.ModuleList()
415
+ self.emb_projs = nn.ParameterList()
416
+ if div_val == 1:
417
+ self.emb_layers.append(nn.Embedding(n_token, d_embed, sparse=sample_softmax > 0))
418
+ if d_proj != d_embed:
419
+ self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
420
+ else:
421
+ for i in range(len(self.cutoffs)):
422
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
423
+ d_emb_i = d_embed // (div_val**i)
424
+ self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i))
425
+ self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
426
+
427
+ def forward(self, inp):
428
+ if self.div_val == 1:
429
+ embed = self.emb_layers[0](inp)
430
+ if self.d_proj != self.d_embed:
431
+ embed = nn.functional.linear(embed, self.emb_projs[0])
432
+ else:
433
+ param = next(self.parameters())
434
+ inp_flat = inp.view(-1)
435
+ emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device)
436
+ for i in range(len(self.cutoffs)):
437
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
438
+
439
+ mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
440
+ indices_i = mask_i.nonzero().squeeze()
441
+
442
+ if indices_i.numel() == 0:
443
+ continue
444
+
445
+ inp_i = inp_flat.index_select(0, indices_i) - l_idx
446
+ emb_i = self.emb_layers[i](inp_i)
447
+ emb_i = nn.functional.linear(emb_i, self.emb_projs[i])
448
+
449
+ emb_flat.index_copy_(0, indices_i, emb_i)
450
+
451
+ embed_shape = inp.size() + (self.d_proj,)
452
+ embed = emb_flat.view(embed_shape)
453
+
454
+ embed.mul_(self.emb_scale)
455
+
456
+ return embed
457
+
458
+
459
+ class TransfoXLPreTrainedModel(PreTrainedModel):
460
+ """
461
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
462
+ models.
463
+ """
464
+
465
+ config_class = TransfoXLConfig
466
+ load_tf_weights = load_tf_weights_in_transfo_xl
467
+ base_model_prefix = "transformer"
468
+
469
+ def _init_weight(self, weight):
470
+ if self.config.init == "uniform":
471
+ nn.init.uniform_(weight, -self.config.init_range, self.config.init_range)
472
+ elif self.config.init == "normal":
473
+ nn.init.normal_(weight, 0.0, self.config.init_std)
474
+
475
+ def _init_bias(self, bias):
476
+ nn.init.constant_(bias, 0.0)
477
+
478
+ def _init_weights(self, m):
479
+ """Initialize the weights."""
480
+ classname = m.__class__.__name__
481
+ if classname.find("Linear") != -1:
482
+ if hasattr(m, "weight") and m.weight is not None:
483
+ self._init_weight(m.weight)
484
+ if hasattr(m, "bias") and m.bias is not None:
485
+ self._init_bias(m.bias)
486
+ elif classname.find("AdaptiveEmbedding") != -1:
487
+ if hasattr(m, "emb_projs"):
488
+ for i in range(len(m.emb_projs)):
489
+ if m.emb_projs[i] is not None:
490
+ nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std)
491
+ elif classname.find("Embedding") != -1:
492
+ if hasattr(m, "weight"):
493
+ self._init_weight(m.weight)
494
+ elif classname.find("ProjectedAdaptiveLogSoftmax") != -1:
495
+ if hasattr(m, "cluster_weight") and m.cluster_weight is not None:
496
+ self._init_weight(m.cluster_weight)
497
+ if hasattr(m, "cluster_bias") and m.cluster_bias is not None:
498
+ self._init_bias(m.cluster_bias)
499
+ if hasattr(m, "out_projs"):
500
+ for i in range(len(m.out_projs)):
501
+ if m.out_projs[i] is not None:
502
+ nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std)
503
+ elif classname.find("LayerNorm") != -1:
504
+ if hasattr(m, "weight"):
505
+ nn.init.normal_(m.weight, 1.0, self.config.init_std)
506
+ if hasattr(m, "bias") and m.bias is not None:
507
+ self._init_bias(m.bias)
508
+ else:
509
+ if hasattr(m, "r_emb"):
510
+ self._init_weight(m.r_emb)
511
+ if hasattr(m, "r_w_bias"):
512
+ self._init_weight(m.r_w_bias)
513
+ if hasattr(m, "r_r_bias"):
514
+ self._init_weight(m.r_r_bias)
515
+ if hasattr(m, "r_bias"):
516
+ self._init_bias(m.r_bias)
517
+
518
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1):
519
+ """
520
+ Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying
521
+ weights embeddings afterwards if the model class has a *tie_weights()* method.
522
+
523
+ Arguments:
524
+ new_num_tokens: (*optional*) int:
525
+ New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at
526
+ the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and
527
+ just returns a pointer to the input tokens `torch.nn.Embeddings` Module of the model.
528
+ layer: (*optional*) int:
529
+ Layer of the *AdaptiveEmbedding* where the resizing should be done. Per default the last layer will be
530
+ resized. Be aware that when resizing other than the last layer, you have to ensure that the new
531
+ token(s) in the tokenizer are at the corresponding position.
532
+
533
+ Return: `torch.nn.Embeddings` Pointer to the input tokens Embeddings Module of the model
534
+ """
535
+ base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed
536
+
537
+ if new_num_tokens is None:
538
+ return self.get_input_embeddings()
539
+
540
+ new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer)
541
+ assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less"
542
+ model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer)
543
+
544
+ # Update base model and current model config
545
+ self.config.vocab_size = new_num_tokens
546
+ base_model.vocab_size = new_num_tokens
547
+ base_model.n_token = new_num_tokens
548
+
549
+ new_embedding_shapes = self._get_embedding_shapes()
550
+ self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer)
551
+
552
+ # Tie weights again if needed
553
+ self.tie_weights()
554
+
555
+ return model_embeds
556
+
557
+ def _get_new_num_tokens_layer(self, new_num_tokens, layer):
558
+ embeddings = self.get_input_embeddings()
559
+ if layer == -1:
560
+ layer = len(embeddings.emb_layers) - 1
561
+ assert 0 <= layer <= len(embeddings.emb_layers) - 1
562
+
563
+ new_num_tokens_layer = (
564
+ new_num_tokens
565
+ - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[:layer]])
566
+ - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :]])
567
+ )
568
+ return new_num_tokens_layer, layer
569
+
570
+ def _get_embedding_shapes(self):
571
+ embeddings = self.get_input_embeddings()
572
+ return [emb.weight.shape[0] for emb in embeddings.emb_layers]
573
+
574
+ def _resize_token_embeddings(self, new_num_tokens, layer=-1):
575
+ embeddings = self.get_input_embeddings()
576
+ if new_num_tokens is None:
577
+ return embeddings
578
+ new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens)
579
+ embeddings.emb_layers[layer] = new_embeddings_layer
580
+
581
+ self.set_input_embeddings(embeddings)
582
+
583
+ return self.get_input_embeddings()
584
+
585
+ def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
586
+ embeddings = self.get_input_embeddings()
587
+
588
+ for i in range(layer, len(embeddings.cutoffs)):
589
+ embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1])
590
+
591
+ embeddings.cutoff_ends = [0] + embeddings.cutoffs
592
+ embeddings.n_token = new_num_tokens
593
+
594
+ self.config.cutoffs = embeddings.cutoffs[:-1]
595
+
596
+ return embeddings.cutoffs
597
+
598
+
599
+ @dataclass
600
+ class TransfoXLModelOutput(ModelOutput):
601
+ """
602
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
603
+
604
+ Args:
605
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
606
+ Sequence of hidden-states at the output of the last layer of the model.
607
+ mems (`List[torch.FloatTensor]` of length `config.n_layers`):
608
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
609
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
610
+ be passed as input ids as they have already been computed.
611
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
612
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
613
+ shape `(batch_size, sequence_length, hidden_size)`.
614
+
615
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
616
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
617
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
618
+ sequence_length)`.
619
+
620
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
621
+ heads.
622
+ """
623
+
624
+ last_hidden_state: torch.FloatTensor
625
+ mems: List[torch.FloatTensor] = None
626
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
627
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
628
+
629
+
630
+ @dataclass
631
+ class TransfoXLSequenceClassifierOutputWithPast(ModelOutput):
632
+ """
633
+ Base class for outputs of sentence classification models.
634
+
635
+ Args:
636
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
637
+ Classification (or regression if config.num_labels==1) loss.
638
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
639
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
640
+ mems (`List[torch.FloatTensor]` of length `config.n_layers`):
641
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
642
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
643
+ be passed as input ids as they have already been computed.
644
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
645
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
646
+ shape `(batch_size, sequence_length, hidden_size)`.
647
+
648
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
649
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
650
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
651
+ sequence_length)`.
652
+
653
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
654
+ heads.
655
+ """
656
+
657
+ loss: Optional[torch.FloatTensor] = None
658
+ logits: torch.FloatTensor = None
659
+ mems: List[torch.FloatTensor] = None
660
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
661
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
662
+
663
+
664
+ @dataclass
665
+ class TransfoXLLMHeadModelOutput(ModelOutput):
666
+ """
667
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
668
+
669
+ Args:
670
+ losses (`torch.FloatTensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
671
+ Language modeling losses (not reduced).
672
+ prediction_scores (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
673
+ Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
674
+ mems (`List[torch.FloatTensor]` of length `config.n_layers`):
675
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
676
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
677
+ be passed as input ids as they have already been computed.
678
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
679
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
680
+ shape `(batch_size, sequence_length, hidden_size)`.
681
+
682
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
683
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
684
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
685
+ sequence_length)`.
686
+
687
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
688
+ heads.
689
+ loss (`torch.FloatTensor` of shape `()`, *optional*, returned when `labels` is provided)
690
+ Reduced language modeling loss.
691
+ """
692
+
693
+ losses: Optional[torch.FloatTensor] = None
694
+ prediction_scores: torch.FloatTensor = None
695
+ mems: List[torch.FloatTensor] = None
696
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
697
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
698
+ loss: Optional[torch.FloatTensor] = None
699
+
700
+ @property
701
+ def logits(self):
702
+ # prediction scores are the output of the adaptive softmax, see
703
+ # the file `modeling_transfo_xl_utilities`. Since the adaptive
704
+ # softmax returns the log softmax value, `self.prediction_scores`
705
+ # are strictly speaking not exactly `logits`, but behave the same
706
+ # way logits do.
707
+ return self.prediction_scores
708
+
709
+
710
+ TRANSFO_XL_START_DOCSTRING = r"""
711
+
712
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
713
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
714
+ etc.)
715
+
716
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
717
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
718
+ and behavior.
719
+
720
+ Parameters:
721
+ config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
722
+ Initializing with a config file does not load the weights associated with the model, only the
723
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
724
+ """
725
+
726
+ TRANSFO_XL_INPUTS_DOCSTRING = r"""
727
+ Args:
728
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
729
+ Indices of input sequence tokens in the vocabulary.
730
+
731
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
732
+ [`PreTrainedTokenizer.__call__`] for details.
733
+
734
+ [What are input IDs?](../glossary#input-ids)
735
+ mems (`List[torch.FloatTensor]` of length `config.n_layers`):
736
+ Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
737
+ `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
738
+ given to this model should not be passed as `input_ids` as they have already been computed.
739
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
740
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
741
+
742
+ - 1 indicates the head is **not masked**,
743
+ - 0 indicates the head is **masked**.
744
+
745
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
746
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
747
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
748
+ model's internal embedding lookup matrix.
749
+ output_attentions (`bool`, *optional*):
750
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
751
+ tensors for more detail.
752
+ output_hidden_states (`bool`, *optional*):
753
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
754
+ more detail.
755
+ return_dict (`bool`, *optional*):
756
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
757
+ """
758
+
759
+
760
+ @add_start_docstrings(
761
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
762
+ TRANSFO_XL_START_DOCSTRING,
763
+ )
764
+ class TransfoXLModel(TransfoXLPreTrainedModel):
765
+ def __init__(self, config):
766
+ super().__init__(config)
767
+
768
+ self.n_token = config.vocab_size
769
+
770
+ self.d_embed = config.d_embed
771
+ self.d_model = config.d_model
772
+ self.n_head = config.n_head
773
+ self.d_head = config.d_head
774
+
775
+ self.word_emb = AdaptiveEmbedding(
776
+ config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
777
+ )
778
+
779
+ self.drop = nn.Dropout(config.dropout)
780
+
781
+ self.n_layer = config.n_layer
782
+ self.mem_len = config.mem_len
783
+ self.attn_type = config.attn_type
784
+
785
+ if not config.untie_r:
786
+ self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
787
+ self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
788
+
789
+ self.layers = nn.ModuleList()
790
+ if config.attn_type == 0: # the default attention
791
+ for i in range(config.n_layer):
792
+ self.layers.append(
793
+ RelPartialLearnableDecoderLayer(
794
+ config.n_head,
795
+ config.d_model,
796
+ config.d_head,
797
+ config.d_inner,
798
+ config.dropout,
799
+ dropatt=config.dropatt,
800
+ pre_lnorm=config.pre_lnorm,
801
+ r_w_bias=None if config.untie_r else self.r_w_bias,
802
+ r_r_bias=None if config.untie_r else self.r_r_bias,
803
+ layer_norm_epsilon=config.layer_norm_epsilon,
804
+ )
805
+ )
806
+ else: # learnable embeddings and absolute embeddings are not used in our pretrained checkpoints
807
+ raise NotImplementedError # Removed them to avoid maintaining dead code
808
+
809
+ self.same_length = config.same_length
810
+ self.clamp_len = config.clamp_len
811
+
812
+ if self.attn_type == 0: # default attention
813
+ self.pos_emb = PositionalEmbedding(self.d_model)
814
+ else: # learnable embeddings and absolute embeddings
815
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
816
+
817
+ # Initialize weights and apply final processing
818
+ self.post_init()
819
+
820
+ def get_input_embeddings(self):
821
+ return self.word_emb
822
+
823
+ def set_input_embeddings(self, new_embeddings):
824
+ self.word_emb = new_embeddings
825
+
826
+ def backward_compatible(self):
827
+ self.sample_softmax = -1
828
+
829
+ def reset_memory_length(self, mem_len):
830
+ self.mem_len = mem_len
831
+
832
+ def _prune_heads(self, heads):
833
+ logger.info("Head pruning is not implemented for Transformer-XL model")
834
+ pass
835
+
836
+ def init_mems(self, bsz):
837
+ if self.mem_len > 0:
838
+ mems = []
839
+ param = next(self.parameters())
840
+ for i in range(self.n_layer):
841
+ empty = torch.zeros(self.mem_len, bsz, self.config.d_model, dtype=param.dtype, device=param.device)
842
+ mems.append(empty)
843
+
844
+ return mems
845
+ else:
846
+ return None
847
+
848
+ def _update_mems(self, hids, mems, mlen, qlen):
849
+ # does not deal with None
850
+ if mems is None:
851
+ return None
852
+
853
+ # mems is not None
854
+ assert len(hids) == len(mems), "len(hids) != len(mems)"
855
+
856
+ # There are `mlen + qlen` steps that can be cached into mems
857
+ with torch.no_grad():
858
+ new_mems = []
859
+ end_idx = mlen + max(0, qlen)
860
+ beg_idx = max(0, end_idx - self.mem_len)
861
+ for i in range(len(hids)):
862
+ cat = torch.cat([mems[i], hids[i]], dim=0)
863
+ new_mems.append(cat[beg_idx:end_idx].detach())
864
+
865
+ return new_mems
866
+
867
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
868
+ @add_code_sample_docstrings(
869
+ checkpoint=_CHECKPOINT_FOR_DOC,
870
+ output_type=TransfoXLModelOutput,
871
+ config_class=_CONFIG_FOR_DOC,
872
+ )
873
+ def forward(
874
+ self,
875
+ input_ids: Optional[torch.LongTensor] = None,
876
+ mems: Optional[List[torch.FloatTensor]] = None,
877
+ head_mask: Optional[torch.FloatTensor] = None,
878
+ inputs_embeds: Optional[torch.FloatTensor] = None,
879
+ output_attentions: Optional[bool] = None,
880
+ output_hidden_states: Optional[bool] = None,
881
+ return_dict: Optional[bool] = None,
882
+ ) -> Union[Tuple, TransfoXLModelOutput]:
883
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
884
+ output_hidden_states = (
885
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
886
+ )
887
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
888
+
889
+ # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
890
+ # so we transpose here from shape [bsz, len] to shape [len, bsz]
891
+ if input_ids is not None and inputs_embeds is not None:
892
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
893
+ elif input_ids is not None:
894
+ input_ids = input_ids.transpose(0, 1).contiguous()
895
+ qlen, bsz = input_ids.size()
896
+ elif inputs_embeds is not None:
897
+ inputs_embeds = inputs_embeds.transpose(0, 1).contiguous()
898
+ qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1]
899
+ else:
900
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
901
+
902
+ if mems is None:
903
+ mems = self.init_mems(bsz)
904
+
905
+ # Prepare head mask if needed
906
+ # 1.0 in head_mask indicate we keep the head
907
+ # attention_probs has shape bsz x n_heads x N x N
908
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
909
+ # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
910
+ if head_mask is not None:
911
+ if head_mask.dim() == 1:
912
+ head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)
913
+ head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1)
914
+ elif head_mask.dim() == 2:
915
+ head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1)
916
+ head_mask = head_mask.to(
917
+ dtype=next(self.parameters()).dtype
918
+ ) # switch to float if need + fp16 compatibility
919
+ else:
920
+ head_mask = [None] * self.n_layer
921
+
922
+ if inputs_embeds is not None:
923
+ word_emb = inputs_embeds
924
+ else:
925
+ word_emb = self.word_emb(input_ids)
926
+
927
+ mlen = mems[0].size(0) if mems is not None else 0
928
+ klen = mlen + qlen
929
+ if self.same_length:
930
+ all_ones = word_emb.new_ones((qlen, klen), dtype=torch.bool)
931
+ mask_len = klen - self.mem_len
932
+ if mask_len > 0:
933
+ mask_shift_len = qlen - mask_len
934
+ else:
935
+ mask_shift_len = qlen
936
+ dec_attn_mask = (torch.triu(all_ones, 1 + mlen) + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1
937
+ else:
938
+ dec_attn_mask = torch.triu(word_emb.new_ones((qlen, klen), dtype=torch.bool), diagonal=1 + mlen)[
939
+ :, :, None
940
+ ]
941
+
942
+ hids = []
943
+ attentions = [] if output_attentions else None
944
+ if self.attn_type == 0: # default
945
+ pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device, dtype=word_emb.dtype)
946
+ if self.clamp_len > 0:
947
+ pos_seq.clamp_(max=self.clamp_len)
948
+ pos_emb = self.pos_emb(pos_seq)
949
+
950
+ core_out = self.drop(word_emb)
951
+ pos_emb = self.drop(pos_emb)
952
+
953
+ for i, layer in enumerate(self.layers):
954
+ hids.append(core_out)
955
+ mems_i = None if mems is None else mems[i]
956
+ layer_outputs = layer(
957
+ core_out,
958
+ pos_emb,
959
+ dec_attn_mask=dec_attn_mask,
960
+ mems=mems_i,
961
+ head_mask=head_mask[i],
962
+ output_attentions=output_attentions,
963
+ )
964
+ core_out = layer_outputs[0]
965
+ if output_attentions:
966
+ attentions.append(layer_outputs[1])
967
+ else: # learnable embeddings and absolute embeddings
968
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
969
+
970
+ core_out = self.drop(core_out)
971
+
972
+ new_mems = self._update_mems(hids, mems, mlen, qlen)
973
+
974
+ if output_hidden_states:
975
+ # Add last layer and transpose to library standard shape [bsz, len, hidden_dim]
976
+ hids.append(core_out)
977
+ hids = tuple(t.transpose(0, 1).contiguous() for t in hids)
978
+ else:
979
+ hids = None
980
+ if output_attentions:
981
+ # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
982
+ attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
983
+ # We transpose back here to shape [bsz, len, hidden_dim]
984
+ core_out = core_out.transpose(0, 1).contiguous()
985
+
986
+ if not return_dict:
987
+ return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
988
+
989
+ return TransfoXLModelOutput(
990
+ last_hidden_state=core_out,
991
+ mems=new_mems,
992
+ hidden_states=hids,
993
+ attentions=attentions,
994
+ )
995
+
996
+
997
+ @add_start_docstrings(
998
+ """
999
+ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
1000
+ input embeddings)
1001
+ """,
1002
+ TRANSFO_XL_START_DOCSTRING,
1003
+ )
1004
+ class TransfoXLLMHeadModel(TransfoXLPreTrainedModel):
1005
+ _keys_to_ignore_on_load_missing = [r"crit\.out_projs\.\d+", r"crit\.out_layers\.\d+\.weight"]
1006
+
1007
+ def __init__(self, config):
1008
+ super().__init__(config)
1009
+ self.transformer = TransfoXLModel(config)
1010
+ self.sample_softmax = config.sample_softmax
1011
+ self.trainer_compatible = getattr(config, "trainer_compatible", False)
1012
+
1013
+ if not self.trainer_compatible:
1014
+ warnings.warn(
1015
+ "The output of TransfoXL will be updated in v5 to support a single loss as first argument. In order"
1016
+ "to use that updated output, please specify `trainer_compatible=True` as your configuration"
1017
+ " attribute.",
1018
+ DeprecationWarning,
1019
+ )
1020
+
1021
+ assert self.sample_softmax <= 0, (
1022
+ "Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
1023
+ " https://github.com/huggingface/transformers/issues/3310"
1024
+ )
1025
+
1026
+ self.crit = ProjectedAdaptiveLogSoftmax(
1027
+ config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
1028
+ )
1029
+
1030
+ # Initialize weights and apply final processing
1031
+ self.post_init()
1032
+
1033
+ def tie_weights(self):
1034
+ """
1035
+ Run this to be sure output and input (adaptive) softmax weights are tied
1036
+ """
1037
+
1038
+ if self.config.tie_word_embeddings:
1039
+ for i in range(len(self.crit.out_layers)):
1040
+ self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_emb.emb_layers[i])
1041
+ if self.config.tie_projs:
1042
+ for i, tie_proj in enumerate(self.config.tie_projs):
1043
+ if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
1044
+ if self.config.torchscript:
1045
+ self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone())
1046
+ else:
1047
+ self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
1048
+ elif tie_proj and self.config.div_val != 1:
1049
+ if self.config.torchscript:
1050
+ self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone())
1051
+ else:
1052
+ self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
1053
+
1054
+ def reset_memory_length(self, mem_len):
1055
+ self.transformer.reset_memory_length(mem_len)
1056
+
1057
+ def init_mems(self, bsz):
1058
+ return self.transformer.init_mems(bsz)
1059
+
1060
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
1061
+ @add_code_sample_docstrings(
1062
+ checkpoint=_CHECKPOINT_FOR_DOC,
1063
+ output_type=TransfoXLLMHeadModelOutput,
1064
+ config_class=_CONFIG_FOR_DOC,
1065
+ )
1066
+ def forward(
1067
+ self,
1068
+ input_ids: Optional[torch.LongTensor] = None,
1069
+ mems: Optional[List[torch.FloatTensor]] = None,
1070
+ head_mask: Optional[torch.FloatTensor] = None,
1071
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1072
+ labels: Optional[torch.LongTensor] = None,
1073
+ output_attentions: Optional[bool] = None,
1074
+ output_hidden_states: Optional[bool] = None,
1075
+ return_dict: Optional[bool] = None,
1076
+ ) -> Union[Tuple, TransfoXLLMHeadModelOutput]:
1077
+ r"""
1078
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1079
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1080
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1081
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1082
+ """
1083
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1084
+ if input_ids is not None:
1085
+ bsz, tgt_len = input_ids.size(0), input_ids.size(1)
1086
+ elif inputs_embeds is not None:
1087
+ bsz, tgt_len = inputs_embeds.size(0), inputs_embeds.size(1)
1088
+ else:
1089
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1090
+
1091
+ transformer_outputs = self.transformer(
1092
+ input_ids,
1093
+ mems=mems,
1094
+ head_mask=head_mask,
1095
+ inputs_embeds=inputs_embeds,
1096
+ output_attentions=output_attentions,
1097
+ output_hidden_states=output_hidden_states,
1098
+ return_dict=return_dict,
1099
+ )
1100
+
1101
+ last_hidden = transformer_outputs[0]
1102
+ pred_hid = last_hidden[:, -tgt_len:]
1103
+
1104
+ if labels is not None:
1105
+ # Prevents all labels being -100 and throwing an error
1106
+ # when backwarding the loss
1107
+ miss_valid_label = labels[0, 1:].sum() == (labels.size(1) - 1) * -100
1108
+ if miss_valid_label:
1109
+ # Sets an <EOS> token, just to prevent loss from being NaN
1110
+ labels[0, 1] = self.config.eos_token_id
1111
+
1112
+ softmax_output = self.crit(pred_hid, labels)
1113
+ prediction_scores = softmax_output.view(bsz, tgt_len, -1) if labels is None else ()
1114
+
1115
+ if labels is not None:
1116
+ losses = softmax_output.view(bsz, tgt_len - 1)
1117
+ # Avoids from incorporating padding (-100) tokens into loss value
1118
+ loss = losses[losses != 0].mean()
1119
+ else:
1120
+ losses, loss = None, None
1121
+
1122
+ if not return_dict:
1123
+ if self.trainer_compatible:
1124
+ output = (prediction_scores, losses) if losses is not None else (prediction_scores,)
1125
+ output += transformer_outputs[1:]
1126
+ return ((loss,) + output) if loss is not None else output
1127
+ else:
1128
+ output = (prediction_scores, *transformer_outputs[1:])
1129
+ output = ((losses,) + output) if losses is not None else output
1130
+ return (output + (loss,)) if loss is not None else output
1131
+
1132
+ return TransfoXLLMHeadModelOutput(
1133
+ loss=loss,
1134
+ prediction_scores=prediction_scores,
1135
+ losses=losses,
1136
+ mems=transformer_outputs.mems,
1137
+ hidden_states=transformer_outputs.hidden_states,
1138
+ attentions=transformer_outputs.attentions,
1139
+ )
1140
+
1141
+ def get_output_embeddings(self):
1142
+ """Double-check if you are using adaptive softmax."""
1143
+ if self.sample_softmax > 0:
1144
+ return self.out_layer
1145
+ else:
1146
+ return self.crit.out_layers[-1]
1147
+
1148
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
1149
+ inputs = {}
1150
+
1151
+ # if past is defined in model kwargs then use it for faster decoding
1152
+ if past_key_values:
1153
+ inputs["mems"] = past_key_values
1154
+ inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1)
1155
+ else:
1156
+ inputs["input_ids"] = input_ids
1157
+
1158
+ return inputs
1159
+
1160
+ def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
1161
+ new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer)
1162
+
1163
+ self.crit.cutoffs = new_cutoffs
1164
+ self.crit.cutoff_ends = [0] + new_cutoffs
1165
+ self.crit.n_token = new_num_tokens
1166
+
1167
+ @staticmethod
1168
+ def _reorder_cache(mems: List[torch.Tensor], beam_idx: torch.Tensor) -> List[torch.Tensor]:
1169
+ """
1170
+ This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
1171
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
1172
+ generation step.
1173
+ """
1174
+ return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems]
1175
+
1176
+
1177
+ @add_start_docstrings(
1178
+ """
1179
+ The Transformer-XL Model transformer with a sequence classification head on top (linear layer).
1180
+
1181
+ [`TransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
1182
+ models (e.g. GPT-1) do.
1183
+
1184
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1185
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1186
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1187
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1188
+ each row of the batch).
1189
+ """,
1190
+ TRANSFO_XL_START_DOCSTRING,
1191
+ )
1192
+ class TransfoXLForSequenceClassification(TransfoXLPreTrainedModel):
1193
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
1194
+
1195
+ def __init__(self, config):
1196
+ super().__init__(config)
1197
+ self.num_labels = config.num_labels
1198
+ self.transformer = TransfoXLModel(config)
1199
+ self.score = nn.Linear(config.d_embed, self.num_labels, bias=False)
1200
+ # Initialize weights and apply final processing
1201
+ self.post_init()
1202
+
1203
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
1204
+ @add_code_sample_docstrings(
1205
+ checkpoint=_CHECKPOINT_FOR_DOC,
1206
+ output_type=TransfoXLSequenceClassifierOutputWithPast,
1207
+ config_class=_CONFIG_FOR_DOC,
1208
+ )
1209
+ def forward(
1210
+ self,
1211
+ input_ids: Optional[torch.LongTensor] = None,
1212
+ mems: Optional[List[torch.FloatTensor]] = None,
1213
+ head_mask: Optional[torch.FloatTensor] = None,
1214
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1215
+ labels: Optional[torch.LongTensor] = None,
1216
+ output_attentions: Optional[bool] = None,
1217
+ output_hidden_states: Optional[bool] = None,
1218
+ return_dict: Optional[bool] = None,
1219
+ ) -> Union[Tuple, TransfoXLSequenceClassifierOutputWithPast]:
1220
+ r"""
1221
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1222
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1223
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1224
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1225
+ """
1226
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1227
+
1228
+ transformer_outputs = self.transformer(
1229
+ input_ids,
1230
+ mems=mems,
1231
+ head_mask=head_mask,
1232
+ inputs_embeds=inputs_embeds,
1233
+ output_attentions=output_attentions,
1234
+ output_hidden_states=output_hidden_states,
1235
+ return_dict=return_dict,
1236
+ )
1237
+ hidden_states = transformer_outputs[0]
1238
+ logits = self.score(hidden_states)
1239
+
1240
+ if input_ids is not None:
1241
+ batch_size, sequence_length = input_ids.shape[:2]
1242
+ else:
1243
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1244
+
1245
+ assert (
1246
+ self.config.pad_token_id is not None or batch_size == 1
1247
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1248
+ if self.config.pad_token_id is None:
1249
+ sequence_lengths = -1
1250
+ else:
1251
+ if input_ids is not None:
1252
+ sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1253
+ else:
1254
+ sequence_lengths = -1
1255
+ logger.warning(
1256
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1257
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1258
+ )
1259
+
1260
+ pooled_logits = logits[range(batch_size), sequence_lengths]
1261
+
1262
+ loss = None
1263
+ if labels is not None:
1264
+ if self.config.problem_type is None:
1265
+ if self.num_labels == 1:
1266
+ self.config.problem_type = "regression"
1267
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1268
+ self.config.problem_type = "single_label_classification"
1269
+ else:
1270
+ self.config.problem_type = "multi_label_classification"
1271
+
1272
+ if self.config.problem_type == "regression":
1273
+ loss_fct = MSELoss()
1274
+ if self.num_labels == 1:
1275
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1276
+ else:
1277
+ loss = loss_fct(pooled_logits, labels)
1278
+ elif self.config.problem_type == "single_label_classification":
1279
+ loss_fct = CrossEntropyLoss()
1280
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1281
+ elif self.config.problem_type == "multi_label_classification":
1282
+ loss_fct = BCEWithLogitsLoss()
1283
+ loss = loss_fct(pooled_logits, labels)
1284
+ if not return_dict:
1285
+ output = (pooled_logits,) + transformer_outputs[1:]
1286
+ return ((loss,) + output) if loss is not None else output
1287
+
1288
+ return TransfoXLSequenceClassifierOutputWithPast(
1289
+ loss=loss,
1290
+ logits=pooled_logits,
1291
+ mems=transformer_outputs.mems,
1292
+ hidden_states=transformer_outputs.hidden_states,
1293
+ attentions=transformer_outputs.attentions,
1294
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/modeling_transfo_xl_utilities.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. 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
+ """
17
+ Utilities for PyTorch Transformer XL model. Directly adapted from https://github.com/kimiyoung/transformer-xl.
18
+ """
19
+
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+
25
+ # CUDA_MAJOR = int(torch.version.cuda.split('.')[0])
26
+ # CUDA_MINOR = int(torch.version.cuda.split('.')[1])
27
+
28
+
29
+ class ProjectedAdaptiveLogSoftmax(nn.Module):
30
+ def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, keep_order=False):
31
+ super().__init__()
32
+
33
+ self.n_token = n_token
34
+ self.d_embed = d_embed
35
+ self.d_proj = d_proj
36
+
37
+ self.cutoffs = cutoffs + [n_token]
38
+ self.cutoff_ends = [0] + self.cutoffs
39
+ self.div_val = div_val
40
+
41
+ self.shortlist_size = self.cutoffs[0]
42
+ self.n_clusters = len(self.cutoffs) - 1
43
+ self.head_size = self.shortlist_size + self.n_clusters
44
+
45
+ if self.n_clusters > 0:
46
+ self.cluster_weight = nn.Parameter(torch.zeros(self.n_clusters, self.d_embed))
47
+ self.cluster_bias = nn.Parameter(torch.zeros(self.n_clusters))
48
+
49
+ self.out_layers = nn.ModuleList()
50
+ self.out_projs = nn.ParameterList()
51
+
52
+ if div_val == 1:
53
+ for i in range(len(self.cutoffs)):
54
+ if d_proj != d_embed:
55
+ self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
56
+ else:
57
+ self.out_projs.append(None)
58
+
59
+ self.out_layers.append(nn.Linear(d_embed, n_token))
60
+ else:
61
+ for i in range(len(self.cutoffs)):
62
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
63
+ d_emb_i = d_embed // (div_val**i)
64
+
65
+ self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
66
+
67
+ self.out_layers.append(nn.Linear(d_emb_i, r_idx - l_idx))
68
+
69
+ self.keep_order = keep_order
70
+
71
+ def _compute_logit(self, hidden, weight, bias, proj):
72
+ if proj is None:
73
+ logit = nn.functional.linear(hidden, weight, bias=bias)
74
+ else:
75
+ # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
76
+ proj_hid = nn.functional.linear(hidden, proj.t().contiguous())
77
+ logit = nn.functional.linear(proj_hid, weight, bias=bias)
78
+ # else:
79
+ # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
80
+ # if bias is not None:
81
+ # logit = logit + bias
82
+
83
+ return logit
84
+
85
+ def forward(self, hidden, labels=None, keep_order=False):
86
+ """
87
+ Params:
88
+ hidden :: [len*bsz x d_proj]
89
+ labels :: [len*bsz]
90
+
91
+ Return:
92
+ if labels is None: out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary else: out ::
93
+ [(len-1)*bsz] Negative log likelihood. We could replace this implementation by the native PyTorch one if
94
+ theirs had an option to set bias on all clusters in the native one. here:
95
+ https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138
96
+ """
97
+
98
+ if labels is not None:
99
+ # Shift so that tokens < n predict n
100
+ hidden = hidden[..., :-1, :].contiguous()
101
+ labels = labels[..., 1:].contiguous()
102
+ hidden = hidden.view(-1, hidden.size(-1))
103
+ labels = labels.view(-1)
104
+ if hidden.size(0) != labels.size(0):
105
+ raise RuntimeError("Input and labels should have the same size in the batch dimension.")
106
+ else:
107
+ hidden = hidden.view(-1, hidden.size(-1))
108
+
109
+ if self.n_clusters == 0:
110
+ logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
111
+ if labels is not None:
112
+ mask = labels != -100
113
+ out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
114
+ out[mask] = (
115
+ -nn.functional.log_softmax(logit, dim=-1)[mask].gather(1, labels[mask].unsqueeze(1)).squeeze(1)
116
+ )
117
+ else:
118
+ out = nn.functional.log_softmax(logit, dim=-1)
119
+ else:
120
+ # construct weights and biases
121
+ weights, biases = [], []
122
+ for i in range(len(self.cutoffs)):
123
+ if self.div_val == 1:
124
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
125
+ weight_i = self.out_layers[0].weight[l_idx:r_idx]
126
+ bias_i = self.out_layers[0].bias[l_idx:r_idx]
127
+ else:
128
+ weight_i = self.out_layers[i].weight
129
+ bias_i = self.out_layers[i].bias
130
+
131
+ if i == 0:
132
+ weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
133
+ bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
134
+
135
+ weights.append(weight_i)
136
+ biases.append(bias_i)
137
+
138
+ head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
139
+
140
+ head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
141
+ head_logprob = nn.functional.log_softmax(head_logit, dim=1)
142
+
143
+ if labels is None:
144
+ out = hidden.new_empty((head_logit.size(0), self.n_token))
145
+ else:
146
+ out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
147
+
148
+ offset = 0
149
+ cutoff_values = [0] + self.cutoffs
150
+ for i in range(len(cutoff_values) - 1):
151
+ l_idx, r_idx = cutoff_values[i], cutoff_values[i + 1]
152
+
153
+ if labels is not None:
154
+ mask_i = (labels >= l_idx) & (labels < r_idx)
155
+ indices_i = mask_i.nonzero().squeeze()
156
+
157
+ if indices_i.numel() == 0:
158
+ continue
159
+
160
+ target_i = labels.index_select(0, indices_i) - l_idx
161
+ head_logprob_i = head_logprob.index_select(0, indices_i)
162
+ hidden_i = hidden.index_select(0, indices_i)
163
+ else:
164
+ hidden_i = hidden
165
+
166
+ if i == 0:
167
+ if labels is not None:
168
+ logprob_i = head_logprob_i.gather(1, target_i[:, None]).squeeze(1)
169
+ else:
170
+ out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
171
+ else:
172
+ weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
173
+
174
+ tail_logit_i = self._compute_logit(hidden_i, weight_i, bias_i, proj_i)
175
+ tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
176
+ cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
177
+ if labels is not None:
178
+ logprob_i = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
179
+ 1, target_i[:, None]
180
+ ).squeeze(1)
181
+ else:
182
+ logprob_i = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
183
+ out[:, l_idx:r_idx] = logprob_i
184
+
185
+ if labels is not None:
186
+ if (hasattr(self, "keep_order") and self.keep_order) or keep_order:
187
+ out.index_copy_(0, indices_i, -logprob_i)
188
+ else:
189
+ out[offset : offset + logprob_i.size(0)].copy_(-logprob_i)
190
+ offset += logprob_i.size(0)
191
+
192
+ return out
193
+
194
+ def log_prob(self, hidden):
195
+ r"""
196
+ Computes log probabilities for all \\(n\_classes\\) From:
197
+ https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.p
198
+
199
+ Args:
200
+ hidden (Tensor): a minibatch of example
201
+
202
+ Returns:
203
+ log-probabilities of for each class \\(c\\) in range \\(0 <= c <= n\_classes\\), where \\(n\_classes\\) is
204
+ a parameter passed to `AdaptiveLogSoftmaxWithLoss` constructor. Shape:
205
+
206
+ - Input: \\((N, in\_features)\\)
207
+ - Output: \\((N, n\_classes)\\)
208
+ """
209
+ if self.n_clusters == 0:
210
+ logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
211
+ return nn.functional.log_softmax(logit, dim=-1)
212
+ else:
213
+ # construct weights and biases
214
+ weights, biases = [], []
215
+ for i in range(len(self.cutoffs)):
216
+ if self.div_val == 1:
217
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
218
+ weight_i = self.out_layers[0].weight[l_idx:r_idx]
219
+ bias_i = self.out_layers[0].bias[l_idx:r_idx]
220
+ else:
221
+ weight_i = self.out_layers[i].weight
222
+ bias_i = self.out_layers[i].bias
223
+
224
+ if i == 0:
225
+ weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
226
+ bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
227
+
228
+ weights.append(weight_i)
229
+ biases.append(bias_i)
230
+
231
+ head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
232
+ head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
233
+
234
+ out = hidden.new_empty((head_logit.size(0), self.n_token))
235
+ head_logprob = nn.functional.log_softmax(head_logit, dim=1)
236
+
237
+ cutoff_values = [0] + self.cutoffs
238
+ for i in range(len(cutoff_values) - 1):
239
+ start_idx, stop_idx = cutoff_values[i], cutoff_values[i + 1]
240
+
241
+ if i == 0:
242
+ out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
243
+ else:
244
+ weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
245
+
246
+ tail_logit_i = self._compute_logit(hidden, weight_i, bias_i, proj_i)
247
+ tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
248
+
249
+ logprob_i = head_logprob[:, -i] + tail_logprob_i
250
+ out[:, start_idx, stop_idx] = logprob_i
251
+
252
+ return out
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/transfo_xl/tokenization_transfo_xl.py ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. 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
+ """
17
+ Tokenization classes for Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl.
18
+ """
19
+
20
+
21
+ import glob
22
+ import os
23
+ import pickle
24
+ import re
25
+ from collections import Counter, OrderedDict
26
+ from typing import List, Optional, Tuple
27
+
28
+ import numpy as np
29
+
30
+ from ...tokenization_utils import PreTrainedTokenizer
31
+ from ...utils import (
32
+ cached_file,
33
+ is_sacremoses_available,
34
+ is_torch_available,
35
+ logging,
36
+ requires_backends,
37
+ torch_only_method,
38
+ )
39
+
40
+
41
+ if is_sacremoses_available():
42
+ import sacremoses as sm
43
+
44
+
45
+ if is_torch_available():
46
+ import torch
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ VOCAB_FILES_NAMES = {
52
+ "pretrained_vocab_file": "vocab.pkl",
53
+ "pretrained_vocab_file_torch": "vocab.bin",
54
+ "vocab_file": "vocab.txt",
55
+ }
56
+
57
+ PRETRAINED_VOCAB_FILES_MAP = {
58
+ "pretrained_vocab_file": {
59
+ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/vocab.pkl",
60
+ }
61
+ }
62
+
63
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
64
+ "transfo-xl-wt103": None,
65
+ }
66
+
67
+ PRETRAINED_CORPUS_ARCHIVE_MAP = {
68
+ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/corpus.bin",
69
+ }
70
+ CORPUS_NAME = "corpus.bin"
71
+
72
+ MATCH_NUMBERS = r"(?<=\d)[,.](?=\d)", r" @\g<0>@ "
73
+ DETOKENIZE_NUMBERS = [(r" @\,@ ", r","), (r" @\.@ ", r".")]
74
+
75
+
76
+ def tokenize_numbers(text_array: List[str]) -> List[str]:
77
+ """
78
+ Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and
79
+ dots with ' @.@ '.
80
+
81
+ Args:
82
+ text_array: An already tokenized text as list.
83
+
84
+ Returns:
85
+ A list of strings with tokenized numbers.
86
+
87
+ Example:
88
+
89
+ ```python
90
+ >>> tokenize_numbers(["$", "5,000", "1.73", "m"])
91
+ ['$', '5', '@,@', '000', '1', '@.@', '73', 'm']
92
+ ```"""
93
+ tokenized = []
94
+ for i in range(len(text_array)):
95
+ reg, sub = MATCH_NUMBERS
96
+ replaced = re.sub(reg, sub, text_array[i]).split()
97
+ tokenized.extend(replaced)
98
+
99
+ return tokenized
100
+
101
+
102
+ def detokenize_numbers(text: str) -> str:
103
+ """
104
+ Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'.
105
+
106
+ Args:
107
+ text: A string where the number should be detokenized.
108
+
109
+ Returns:
110
+ A detokenized string.
111
+
112
+ Example:
113
+
114
+ ```python
115
+ >>> detokenize_numbers("$ 5 @,@ 000 1 @.@ 73 m")
116
+ '$ 5,000 1.73 m'
117
+ ```"""
118
+ for reg, sub in DETOKENIZE_NUMBERS:
119
+ text = re.sub(reg, sub, text)
120
+ return text
121
+
122
+
123
+ class TransfoXLTokenizer(PreTrainedTokenizer):
124
+ """
125
+ Construct a Transformer-XL tokenizer adapted from Vocab class in [the original
126
+ code](https://github.com/kimiyoung/transformer-xl). The Transformer-XL tokenizer is a word-level tokenizer (no
127
+ sub-word tokenization).
128
+
129
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
130
+ this superclass for more information regarding those methods.
131
+
132
+ Args:
133
+ special (`List[str]`, *optional*):
134
+ A list of special tokens (to be treated by the original implementation of this tokenizer).
135
+ min_freq (`int`, *optional*, defaults to 0):
136
+ The minimum number of times a token has to be present in order to be kept in the vocabulary (otherwise it
137
+ will be mapped to `unk_token`).
138
+ max_size (`int`, *optional*):
139
+ The maximum size of the vocabulary. If left unset, it will default to the size of the vocabulary found
140
+ after excluding the tokens according to the `min_freq` rule.
141
+ lower_case (`bool`, *optional*, defaults to `False`):
142
+ Whether or not to lowercase the input when tokenizing.
143
+ delimiter (`str`, *optional*):
144
+ The delimiter used between tokens.
145
+ vocab_file (`str`, *optional*):
146
+ File containing the vocabulary (from the original implementation).
147
+ pretrained_vocab_file (`str`, *optional*):
148
+ File containing the vocabulary as saved with the `save_pretrained()` method.
149
+ never_split (`List[str]`, *optional*):
150
+ List of tokens that should never be split. If no list is specified, will simply use the existing special
151
+ tokens.
152
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
153
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
154
+ token instead.
155
+ eos_token (`str`, *optional*, defaults to `"<eos>"`):
156
+ The end of sequence token.
157
+ additional_special_tokens (`List[str]`, *optional*, defaults to `["<formula>"]`):
158
+ A list of additional special tokens (for the HuggingFace functionality).
159
+ language (`str`, *optional*, defaults to `"en"`):
160
+ The language of this tokenizer (used for mose preprocessing).
161
+ """
162
+
163
+ vocab_files_names = VOCAB_FILES_NAMES
164
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
165
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
166
+ model_input_names = ["input_ids"]
167
+
168
+ def __init__(
169
+ self,
170
+ special=None,
171
+ min_freq=0,
172
+ max_size=None,
173
+ lower_case=False,
174
+ delimiter=None,
175
+ vocab_file=None,
176
+ pretrained_vocab_file: str = None,
177
+ never_split=None,
178
+ unk_token="<unk>",
179
+ eos_token="<eos>",
180
+ additional_special_tokens=["<formula>"],
181
+ language="en",
182
+ **kwargs,
183
+ ):
184
+ super().__init__(
185
+ special=special,
186
+ min_freq=min_freq,
187
+ max_size=max_size,
188
+ lower_case=lower_case,
189
+ delimiter=delimiter,
190
+ vocab_file=vocab_file,
191
+ pretrained_vocab_file=pretrained_vocab_file,
192
+ never_split=never_split,
193
+ unk_token=unk_token,
194
+ eos_token=eos_token,
195
+ additional_special_tokens=additional_special_tokens,
196
+ language=language,
197
+ **kwargs,
198
+ )
199
+ requires_backends(self, "sacremoses")
200
+
201
+ if never_split is None:
202
+ never_split = self.all_special_tokens
203
+ if special is None:
204
+ special = []
205
+ self.counter = Counter()
206
+ self.special = special
207
+ self.min_freq = min_freq
208
+ self.max_size = max_size
209
+ self.lower_case = lower_case
210
+ self.delimiter = delimiter
211
+ self.vocab_file = vocab_file
212
+ self.never_split = never_split
213
+ self.punctuation_symbols = '!"#$%&()*+,-./\\:;<=>?@[\\]^_`{|}~'
214
+ self.punction_without_space_before_pattern = re.compile(rf"[^\s][{self.punctuation_symbols}]")
215
+ self.punctuation_with_space_around_pattern = self._compile_space_around_punctuation_pattern()
216
+ self.language = language
217
+ self.moses_punct_normalizer = sm.MosesPunctNormalizer(language)
218
+ self.moses_tokenizer = sm.MosesTokenizer(language)
219
+ self.moses_detokenizer = sm.MosesDetokenizer(language)
220
+
221
+ # This try... catch... is not beautiful but honestly this tokenizer was not made to be used
222
+ # in a library like ours, at all.
223
+ try:
224
+ vocab_dict = None
225
+ if pretrained_vocab_file is not None:
226
+ # Priority on pickle files (support PyTorch and TF)
227
+ with open(pretrained_vocab_file, "rb") as f:
228
+ vocab_dict = pickle.load(f)
229
+
230
+ # Loading a torch-saved transfo-xl vocab dict with pickle results in an integer
231
+ # Entering this if statement means that we tried to load a torch-saved file with pickle, and we failed.
232
+ # We therefore load it with torch, if it's available.
233
+ if type(vocab_dict) == int:
234
+ if not is_torch_available():
235
+ raise ImportError(
236
+ "Not trying to load dict with PyTorch as you need to install pytorch to load "
237
+ "from a PyTorch pretrained vocabulary, "
238
+ "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
239
+ )
240
+ vocab_dict = torch.load(pretrained_vocab_file)
241
+
242
+ if vocab_dict is not None:
243
+ for key, value in vocab_dict.items():
244
+ if key not in self.__dict__:
245
+ self.__dict__[key] = value
246
+ elif vocab_file is not None:
247
+ self.build_vocab()
248
+
249
+ except Exception as e:
250
+ raise ValueError(
251
+ f"Unable to parse file {pretrained_vocab_file}. Unknown format. "
252
+ "If you tried to load a model saved through TransfoXLTokenizerFast, "
253
+ "please note they are not compatible."
254
+ ) from e
255
+
256
+ if vocab_file is not None:
257
+ self.build_vocab()
258
+
259
+ @property
260
+ def do_lower_case(self):
261
+ return self.lower_case
262
+
263
+ def _compile_space_around_punctuation_pattern(self):
264
+ look_ahead_for_special_token = f"(?=[{self.punctuation_symbols}])"
265
+ look_ahead_to_match_all_except_space = r"(?=[^\s])"
266
+ return re.compile(r"" + look_ahead_for_special_token + look_ahead_to_match_all_except_space)
267
+
268
+ def count_file(self, path, verbose=False, add_eos=False):
269
+ if verbose:
270
+ logger.info(f"counting file {path} ...")
271
+ assert os.path.exists(path), f"Input file {path} not found"
272
+
273
+ sents = []
274
+ with open(path, "r", encoding="utf-8") as f:
275
+ for idx, line in enumerate(f):
276
+ if verbose and idx > 0 and idx % 500000 == 0:
277
+ logger.info(f" line {idx}")
278
+ symbols = self.tokenize(line, add_eos=add_eos)
279
+ self.counter.update(symbols)
280
+ sents.append(symbols)
281
+
282
+ return sents
283
+
284
+ def count_sents(self, sents, verbose=False):
285
+ """
286
+ sents : a list of sentences, each a list of tokenized symbols
287
+ """
288
+ if verbose:
289
+ logger.info(f"counting {len(sents)} sents ...")
290
+ for idx, symbols in enumerate(sents):
291
+ if verbose and idx > 0 and idx % 500000 == 0:
292
+ logger.info(f" line {idx}")
293
+ self.counter.update(symbols)
294
+
295
+ def _build_from_file(self, vocab_file):
296
+ self.idx2sym = []
297
+ self.sym2idx = OrderedDict()
298
+
299
+ with open(vocab_file, "r", encoding="utf-8") as f:
300
+ for line in f:
301
+ symb = line.strip().split()[0]
302
+ self.add_symbol(symb)
303
+ if "<UNK>" in self.sym2idx:
304
+ self.unk_idx = self.sym2idx["<UNK>"]
305
+ elif "<unk>" in self.sym2idx:
306
+ self.unk_idx = self.sym2idx["<unk>"]
307
+ else:
308
+ raise ValueError("No <unknown> token in vocabulary")
309
+
310
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
311
+ if os.path.isdir(save_directory):
312
+ vocab_file = os.path.join(
313
+ save_directory,
314
+ (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["pretrained_vocab_file"],
315
+ )
316
+ else:
317
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
318
+ with open(vocab_file, "wb") as f:
319
+ pickle.dump(self.__dict__, f)
320
+ return (vocab_file,)
321
+
322
+ def build_vocab(self):
323
+ if self.vocab_file:
324
+ logger.info(f"building vocab from {self.vocab_file}")
325
+ self._build_from_file(self.vocab_file)
326
+ logger.info(f"final vocab size {len(self)}")
327
+ else:
328
+ logger.info(f"building vocab with min_freq={self.min_freq}, max_size={self.max_size}")
329
+ self.idx2sym = []
330
+ self.sym2idx = OrderedDict()
331
+
332
+ for sym in self.special:
333
+ self.add_special(sym)
334
+
335
+ for sym, cnt in self.counter.most_common(self.max_size):
336
+ if cnt < self.min_freq:
337
+ break
338
+ self.add_symbol(sym)
339
+
340
+ logger.info(f"final vocab size {len(self)} from {len(self.counter)} unique tokens")
341
+
342
+ @torch_only_method
343
+ def encode_file(self, path, ordered=False, verbose=False, add_eos=True, add_double_eos=False):
344
+ if verbose:
345
+ logger.info(f"encoding file {path} ...")
346
+ assert os.path.exists(path), f"Output file {path} not found"
347
+ encoded = []
348
+ with open(path, "r", encoding="utf-8") as f:
349
+ for idx, line in enumerate(f):
350
+ if verbose and idx > 0 and idx % 500000 == 0:
351
+ logger.info(f" line {idx}")
352
+ symbols = self.tokenize(line, add_eos=add_eos, add_double_eos=add_double_eos)
353
+ encoded.append(self.convert_to_tensor(symbols))
354
+
355
+ if ordered:
356
+ encoded = torch.cat(encoded)
357
+
358
+ return encoded
359
+
360
+ @torch_only_method
361
+ def encode_sents(self, sents, ordered=False, verbose=False):
362
+ if verbose:
363
+ logger.info(f"encoding {len(sents)} sents ...")
364
+ encoded = []
365
+ for idx, symbols in enumerate(sents):
366
+ if verbose and idx > 0 and idx % 500000 == 0:
367
+ logger.info(f" line {idx}")
368
+ encoded.append(self.convert_to_tensor(symbols))
369
+
370
+ if ordered:
371
+ encoded = torch.cat(encoded)
372
+
373
+ return encoded
374
+
375
+ def add_special(self, sym):
376
+ if sym not in self.sym2idx:
377
+ self.idx2sym.append(sym)
378
+ self.sym2idx[sym] = len(self.idx2sym) - 1
379
+ setattr(self, f"{sym.strip('<>')}_idx", self.sym2idx[sym])
380
+
381
+ def add_symbol(self, sym):
382
+ if sym not in self.sym2idx:
383
+ self.idx2sym.append(sym)
384
+ self.sym2idx[sym] = len(self.idx2sym) - 1
385
+
386
+ def move_added_token(self, token: str, target_idx: int):
387
+ """
388
+ Moves an added token to a specific position in the vocab. This method should be used when resizing an embedding
389
+ layer other than the last one in the `AdaptiveEmbedding` in order to move the token in the tokenizer from the
390
+ default position (at the very end) to the desired one.
391
+
392
+ Args:
393
+ token: The token to move to a specific position in the vocab.
394
+ target_idx: The position where the token should be moved to.
395
+ """
396
+ assert token in self.added_tokens_encoder, "Token which should be moved has to be an added token"
397
+ assert token not in self.idx2sym, "Token which should be moved is already in vocab"
398
+
399
+ # Insert sym into vocab
400
+ self.idx2sym.insert(target_idx, token)
401
+ self.sym2idx[token] = target_idx
402
+
403
+ # Shift following indices in sym2idx
404
+ for idx in range(target_idx + 1, len(self.idx2sym)):
405
+ current_sym = self.idx2sym[idx]
406
+ self.sym2idx[current_sym] = idx
407
+
408
+ # Delete token from added_tokens
409
+ old_index = self.added_tokens_encoder[token]
410
+ del self.added_tokens_decoder[old_index]
411
+ del self.added_tokens_encoder[token]
412
+
413
+ def moses_punct_norm(self, text):
414
+ return self.moses_punct_normalizer.normalize(text)
415
+
416
+ def moses_tokenize(self, text):
417
+ return self.moses_tokenizer.tokenize(
418
+ text, aggressive_dash_splits=True, return_str=False, escape=False, protected_patterns=self.never_split
419
+ )
420
+
421
+ def moses_pipeline(self, text: str) -> List[str]:
422
+ """
423
+ Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with
424
+ *aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large
425
+ comma-separated numbers and floating point values are split. E.g. "23,000 people are 1.80m tall" -> "23 @,@ 000
426
+ people are 1 @.@ 80m tall"
427
+
428
+ Args:
429
+ text: Text to be tokenize
430
+
431
+ Returns:
432
+ A list of tokenized string
433
+
434
+ Example:
435
+
436
+ ```python
437
+ >>> tokenizer = TransfoXLTokenizer.from_pretrained("transfo-xl-wt103")
438
+ >>> tokenizer.moses_pipeline("23,000 people are 1.80 m tall")
439
+ ['23', '@,@', '000', 'people', 'are', '1', '@.@', '80', 'm', 'tall']
440
+ ```"""
441
+ text = self.moses_punct_norm(text)
442
+ text = self.moses_tokenize(text)
443
+ text = tokenize_numbers(text)
444
+ return text
445
+
446
+ def _convert_id_to_token(self, idx):
447
+ """Converts an id in a token (BPE) using the vocab."""
448
+ assert 0 <= idx < len(self), f"Index {idx} out of vocabulary range"
449
+ return self.idx2sym[idx]
450
+
451
+ def _convert_token_to_id(self, sym):
452
+ """Converts a token (str) in an id using the vocab."""
453
+ if sym in self.sym2idx:
454
+ return self.sym2idx[sym]
455
+ else:
456
+ # logger.info(f'encounter unk {sym}')
457
+ # assert '<eos>' not in sym
458
+ if hasattr(self, "unk_idx"):
459
+ return self.sym2idx.get(sym, self.unk_idx)
460
+ # Backward compatibility with pre-trained models
461
+ elif "<unk>" in self.sym2idx:
462
+ return self.sym2idx["<unk>"]
463
+ elif "<UNK>" in self.sym2idx:
464
+ return self.sym2idx["<UNK>"]
465
+ else:
466
+ raise ValueError("Token not in vocabulary and no <unk> token in vocabulary for replacement")
467
+
468
+ def convert_tokens_to_string(self, tokens):
469
+ """
470
+ Converts a sequence of tokens (string) in a single string. Additionally, the split numbers are converted back
471
+ into it's original form.
472
+ """
473
+ out_string = self.moses_detokenizer.detokenize(tokens)
474
+ return detokenize_numbers(out_string).strip()
475
+
476
+ @torch_only_method
477
+ def convert_to_tensor(self, symbols):
478
+ return torch.LongTensor(self.convert_tokens_to_ids(symbols))
479
+
480
+ @property
481
+ def vocab_size(self):
482
+ return len(self.idx2sym)
483
+
484
+ def get_vocab(self):
485
+ return dict(self.sym2idx, **self.added_tokens_encoder)
486
+
487
+ def _tokenize(self, line, add_eos=False, add_double_eos=False):
488
+ line = line.strip()
489
+ # convert to lower case
490
+ if self.lower_case:
491
+ line = line.lower()
492
+
493
+ # empty delimiter '' will evaluate False
494
+ if self.delimiter == "":
495
+ symbols = line
496
+ else:
497
+ symbols = self.moses_pipeline(line)
498
+
499
+ if add_double_eos: # lm1b
500
+ return ["<S>"] + symbols + ["<S>"]
501
+ elif add_eos:
502
+ return symbols + ["<eos>"]
503
+ else:
504
+ return symbols
505
+
506
+
507
+ class LMOrderedIterator(object):
508
+ def __init__(self, data, bsz, bptt, device="cpu", ext_len=None):
509
+ """
510
+ data -- LongTensor -- the LongTensor is strictly ordered
511
+ """
512
+ self.bsz = bsz
513
+ self.bptt = bptt
514
+ self.ext_len = ext_len if ext_len is not None else 0
515
+
516
+ self.device = device
517
+
518
+ # Work out how cleanly we can divide the dataset into bsz parts.
519
+ self.n_step = data.size(0) // bsz
520
+
521
+ # Trim off any extra elements that wouldn't cleanly fit (remainders).
522
+ data = data.narrow(0, 0, self.n_step * bsz)
523
+
524
+ # Evenly divide the data across the bsz batches.
525
+ self.data = data.view(bsz, -1).t().contiguous().to(device)
526
+
527
+ # Number of mini-batches
528
+ self.n_batch = (self.n_step + self.bptt - 1) // self.bptt
529
+
530
+ def get_batch(self, i, bptt=None):
531
+ if bptt is None:
532
+ bptt = self.bptt
533
+ seq_len = min(bptt, self.data.size(0) - 1 - i)
534
+
535
+ end_idx = i + seq_len
536
+ beg_idx = max(0, i - self.ext_len)
537
+
538
+ data = self.data[beg_idx:end_idx]
539
+ target = self.data[i + 1 : i + 1 + seq_len]
540
+
541
+ data_out = data.transpose(0, 1).contiguous().to(self.device)
542
+ target_out = target.transpose(0, 1).contiguous().to(self.device)
543
+
544
+ return data_out, target_out, seq_len
545
+
546
+ def get_fixlen_iter(self, start=0):
547
+ for i in range(start, self.data.size(0) - 1, self.bptt):
548
+ yield self.get_batch(i)
549
+
550
+ def get_varlen_iter(self, start=0, std=5, min_len=5, max_deviation=3):
551
+ max_len = self.bptt + max_deviation * std
552
+ i = start
553
+ while True:
554
+ bptt = self.bptt if np.random.random() < 0.95 else self.bptt / 2.0
555
+ bptt = min(max_len, max(min_len, int(np.random.normal(bptt, std))))
556
+ data, target, seq_len = self.get_batch(i, bptt)
557
+ i += seq_len
558
+ yield data, target, seq_len
559
+ if i >= self.data.size(0) - 2:
560
+ break
561
+
562
+ def __iter__(self):
563
+ return self.get_fixlen_iter()
564
+
565
+
566
+ class LMShuffledIterator(object):
567
+ def __init__(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
568
+ """
569
+ data -- list[LongTensor] -- there is no order among the LongTensors
570
+ """
571
+ self.data = data
572
+
573
+ self.bsz = bsz
574
+ self.bptt = bptt
575
+ self.ext_len = ext_len if ext_len is not None else 0
576
+
577
+ self.device = device
578
+ self.shuffle = shuffle
579
+
580
+ def get_sent_stream(self):
581
+ # index iterator
582
+ epoch_indices = np.random.permutation(len(self.data)) if self.shuffle else np.array(range(len(self.data)))
583
+
584
+ # sentence iterator
585
+ for idx in epoch_indices:
586
+ yield self.data[idx]
587
+
588
+ @torch_only_method
589
+ def stream_iterator(self, sent_stream):
590
+ # streams for each data in the batch
591
+ streams = [None] * self.bsz
592
+
593
+ data = torch.LongTensor(self.bptt, self.bsz)
594
+ target = torch.LongTensor(self.bptt, self.bsz)
595
+
596
+ n_retain = 0
597
+
598
+ while True:
599
+ # data : [n_retain+bptt x bsz]
600
+ # target : [bptt x bsz]
601
+ data[n_retain:].fill_(-1)
602
+ target.fill_(-1)
603
+
604
+ valid_batch = True
605
+
606
+ for i in range(self.bsz):
607
+ n_filled = 0
608
+ try:
609
+ while n_filled < self.bptt:
610
+ if streams[i] is None or len(streams[i]) <= 1:
611
+ streams[i] = next(sent_stream)
612
+ # number of new tokens to fill in
613
+ n_new = min(len(streams[i]) - 1, self.bptt - n_filled)
614
+ # first n_retain tokens are retained from last batch
615
+ data[n_retain + n_filled : n_retain + n_filled + n_new, i] = streams[i][:n_new]
616
+ target[n_filled : n_filled + n_new, i] = streams[i][1 : n_new + 1]
617
+ streams[i] = streams[i][n_new:]
618
+ n_filled += n_new
619
+ except StopIteration:
620
+ valid_batch = False
621
+ break
622
+
623
+ if not valid_batch:
624
+ return
625
+
626
+ data_out = data.transpose(0, 1).contiguous().to(self.device)
627
+ target_out = target.transpose(0, 1).contiguous().to(self.device)
628
+
629
+ yield data_out, target_out, self.bptt
630
+
631
+ n_retain = min(data.size(0), self.ext_len)
632
+ if n_retain > 0:
633
+ data[:n_retain] = data[-n_retain:]
634
+ data.resize_(n_retain + self.bptt, data.size(1))
635
+
636
+ def __iter__(self):
637
+ # sent_stream is an iterator
638
+ sent_stream = self.get_sent_stream()
639
+
640
+ for batch in self.stream_iterator(sent_stream):
641
+ yield batch
642
+
643
+
644
+ class LMMultiFileIterator(LMShuffledIterator):
645
+ def __init__(self, paths, vocab, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
646
+ self.paths = paths
647
+ self.vocab = vocab
648
+
649
+ self.bsz = bsz
650
+ self.bptt = bptt
651
+ self.ext_len = ext_len if ext_len is not None else 0
652
+
653
+ self.device = device
654
+ self.shuffle = shuffle
655
+
656
+ def get_sent_stream(self, path):
657
+ sents = self.vocab.encode_file(path, add_double_eos=True)
658
+ if self.shuffle:
659
+ np.random.shuffle(sents)
660
+ sent_stream = iter(sents)
661
+
662
+ return sent_stream
663
+
664
+ def __iter__(self):
665
+ if self.shuffle:
666
+ np.random.shuffle(self.paths)
667
+
668
+ for path in self.paths:
669
+ # sent_stream is an iterator
670
+ sent_stream = self.get_sent_stream(path)
671
+ for batch in self.stream_iterator(sent_stream):
672
+ yield batch
673
+
674
+
675
+ class TransfoXLCorpus(object):
676
+ @classmethod
677
+ @torch_only_method
678
+ def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
679
+ """
680
+ Instantiate a pre-processed corpus.
681
+ """
682
+ vocab = TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
683
+ is_local = os.path.isdir(pretrained_model_name_or_path)
684
+ # redirect to the cache, if necessary
685
+ try:
686
+ resolved_corpus_file = cached_file(pretrained_model_name_or_path, CORPUS_NAME, cache_dir=cache_dir)
687
+ except EnvironmentError:
688
+ logger.error(
689
+ f"Corpus '{pretrained_model_name_or_path}' was not found in corpus list"
690
+ f" ({', '.join(PRETRAINED_CORPUS_ARCHIVE_MAP.keys())}. We assumed '{pretrained_model_name_or_path}'"
691
+ f" was a path or url but couldn't find files {CORPUS_NAME} at this path or url."
692
+ )
693
+ return None
694
+ if is_local:
695
+ logger.info(f"loading corpus file {resolved_corpus_file}")
696
+ else:
697
+ logger.info(f"loading corpus file {CORPUS_NAME} from cache at {resolved_corpus_file}")
698
+
699
+ # Instantiate tokenizer.
700
+ corpus = cls(*inputs, **kwargs)
701
+ corpus_dict = torch.load(resolved_corpus_file)
702
+ for key, value in corpus_dict.items():
703
+ corpus.__dict__[key] = value
704
+ corpus.vocab = vocab
705
+ if corpus.train is not None:
706
+ corpus.train = torch.tensor(corpus.train, dtype=torch.long)
707
+ if corpus.valid is not None:
708
+ corpus.valid = torch.tensor(corpus.valid, dtype=torch.long)
709
+ if corpus.test is not None:
710
+ corpus.test = torch.tensor(corpus.test, dtype=torch.long)
711
+ return corpus
712
+
713
+ def __init__(self, *args, **kwargs):
714
+ self.vocab = TransfoXLTokenizer(*args, **kwargs)
715
+ self.dataset = None
716
+ self.train = None
717
+ self.valid = None
718
+ self.test = None
719
+
720
+ def build_corpus(self, path, dataset):
721
+ self.dataset = dataset
722
+
723
+ if self.dataset in ["ptb", "wt2", "enwik8", "text8"]:
724
+ self.vocab.count_file(os.path.join(path, "train.txt"))
725
+ self.vocab.count_file(os.path.join(path, "valid.txt"))
726
+ self.vocab.count_file(os.path.join(path, "test.txt"))
727
+ elif self.dataset == "wt103":
728
+ self.vocab.count_file(os.path.join(path, "train.txt"))
729
+ elif self.dataset == "lm1b":
730
+ train_path_pattern = os.path.join(
731
+ path,
732
+ "1-billion-word-language-modeling-benchmark-r13output",
733
+ "training-monolingual.tokenized.shuffled",
734
+ "news.en-*",
735
+ )
736
+ train_paths = glob.glob(train_path_pattern)
737
+ # the vocab will load from file when build_vocab() is called
738
+
739
+ self.vocab.build_vocab()
740
+
741
+ if self.dataset in ["ptb", "wt2", "wt103"]:
742
+ self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True)
743
+ self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True)
744
+ self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True)
745
+ elif self.dataset in ["enwik8", "text8"]:
746
+ self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True, add_eos=False)
747
+ self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True, add_eos=False)
748
+ self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True, add_eos=False)
749
+ elif self.dataset == "lm1b":
750
+ self.train = train_paths
751
+ self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=False, add_double_eos=True)
752
+ self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=False, add_double_eos=True)
753
+
754
+ def get_iterator(self, split, *args, **kwargs):
755
+ if split == "train":
756
+ if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
757
+ data_iter = LMOrderedIterator(self.train, *args, **kwargs)
758
+ elif self.dataset == "lm1b":
759
+ kwargs["shuffle"] = True
760
+ data_iter = LMMultiFileIterator(self.train, self.vocab, *args, **kwargs)
761
+ elif split in ["valid", "test"]:
762
+ data = self.valid if split == "valid" else self.test
763
+ if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
764
+ data_iter = LMOrderedIterator(data, *args, **kwargs)
765
+ elif self.dataset == "lm1b":
766
+ data_iter = LMShuffledIterator(data, *args, **kwargs)
767
+ else:
768
+ data_iter = None
769
+ raise ValueError(f"Split not recognized: {split}")
770
+
771
+ return data_iter
772
+
773
+
774
+ @torch_only_method
775
+ def get_lm_corpus(datadir, dataset):
776
+ fn = os.path.join(datadir, "cache.pt")
777
+ fn_pickle = os.path.join(datadir, "cache.pkl")
778
+ if os.path.exists(fn):
779
+ logger.info("Loading cached dataset...")
780
+ corpus = torch.load(fn_pickle)
781
+ elif os.path.exists(fn):
782
+ logger.info("Loading cached dataset from pickle...")
783
+ with open(fn, "rb") as fp:
784
+ corpus = pickle.load(fp)
785
+ else:
786
+ logger.info(f"Producing dataset {dataset}...")
787
+ kwargs = {}
788
+ if dataset in ["wt103", "wt2"]:
789
+ kwargs["special"] = ["<eos>"]
790
+ kwargs["lower_case"] = False
791
+ elif dataset == "ptb":
792
+ kwargs["special"] = ["<eos>"]
793
+ kwargs["lower_case"] = True
794
+ elif dataset == "lm1b":
795
+ kwargs["special"] = []
796
+ kwargs["lower_case"] = False
797
+ kwargs["vocab_file"] = os.path.join(datadir, "1b_word_vocab.txt")
798
+ elif dataset in ["enwik8", "text8"]:
799
+ pass
800
+
801
+ corpus = TransfoXLCorpus(datadir, dataset, **kwargs)
802
+ torch.save(corpus, fn)
803
+
804
+ return corpus
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/__init__.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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 (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_sentencepiece_available,
20
+ is_speech_available,
21
+ is_torch_available,
22
+ )
23
+
24
+
25
+ _import_structure = {
26
+ "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
27
+ "processing_trocr": ["TrOCRProcessor"],
28
+ }
29
+
30
+
31
+ try:
32
+ if not is_torch_available():
33
+ raise OptionalDependencyNotAvailable()
34
+ except OptionalDependencyNotAvailable:
35
+ pass
36
+ else:
37
+ _import_structure["modeling_trocr"] = [
38
+ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
39
+ "TrOCRForCausalLM",
40
+ "TrOCRPreTrainedModel",
41
+ ]
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
46
+ from .processing_trocr import TrOCRProcessor
47
+
48
+ try:
49
+ if not is_torch_available():
50
+ raise OptionalDependencyNotAvailable()
51
+ except OptionalDependencyNotAvailable:
52
+ pass
53
+ else:
54
+ from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
55
+
56
+ else:
57
+ import sys
58
+
59
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/configuration_trocr.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "microsoft/trocr-base-handwritten": (
25
+ "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json"
26
+ ),
27
+ # See all TrOCR models at https://huggingface.co/models?filter=trocr
28
+ }
29
+
30
+
31
+ class TrOCRConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`TrOCRForCausalLM`]. It is used to instantiate an
34
+ TrOCR model according to the specified arguments, defining the model architecture. Instantiating a configuration
35
+ with the defaults will yield a similar configuration to that of the TrOCR
36
+ [microsoft/trocr-base-handwritten](https://huggingface.co/microsoft/trocr-base-handwritten) architecture.
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+
42
+ Args:
43
+ vocab_size (`int`, *optional*, defaults to 50265):
44
+ Vocabulary size of the TrOCR model. Defines the number of different tokens that can be represented by the
45
+ `inputs_ids` passed when calling [`TrOCRForCausalLM`].
46
+ d_model (`int`, *optional*, defaults to 1024):
47
+ Dimensionality of the layers and the pooler layer.
48
+ decoder_layers (`int`, *optional*, defaults to 12):
49
+ Number of decoder layers.
50
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
53
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
54
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
55
+ The non-linear activation function (function or string) in the pooler. If string, `"gelu"`, `"relu"`,
56
+ `"silu"` and `"gelu_new"` are supported.
57
+ max_position_embeddings (`int`, *optional*, defaults to 512):
58
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
59
+ just in case (e.g., 512 or 1024 or 2048).
60
+ dropout (`float`, *optional*, defaults to 0.1):
61
+ The dropout probability for all fully connected layers in the embeddings, and pooler.
62
+ attention_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout ratio for the attention probabilities.
64
+ activation_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio for activations inside the fully connected layer.
66
+ init_std (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
69
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
70
+ for more details.
71
+ use_cache (`bool`, *optional*, defaults to `True`):
72
+ Whether or not the model should return the last key/values attentions (not used by all models).
73
+ scale_embedding (`bool`, *optional*, defaults to `False`):
74
+ Whether or not to scale the word embeddings by sqrt(d_model).
75
+ use_learned_position_embeddings (`bool`, *optional*, defaults to `True`):
76
+ Whether or not to use learned position embeddings. If not, sinusoidal position embeddings will be used.
77
+ layernorm_embedding (`bool`, *optional*, defaults to `True`):
78
+ Whether or not to use a layernorm after the word + position embeddings.
79
+
80
+ Example:
81
+
82
+ ```python
83
+ >>> from transformers import TrOCRConfig, TrOCRForCausalLM
84
+
85
+ >>> # Initializing a TrOCR-base style configuration
86
+ >>> configuration = TrOCRConfig()
87
+
88
+ >>> # Initializing a model (with random weights) from the TrOCR-base style configuration
89
+ >>> model = TrOCRForCausalLM(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+ ```"""
94
+ model_type = "trocr"
95
+ keys_to_ignore_at_inference = ["past_key_values"]
96
+ attribute_map = {
97
+ "num_attention_heads": "decoder_attention_heads",
98
+ "hidden_size": "d_model",
99
+ "num_hidden_layers": "decoder_layers",
100
+ }
101
+
102
+ def __init__(
103
+ self,
104
+ vocab_size=50265,
105
+ d_model=1024,
106
+ decoder_layers=12,
107
+ decoder_attention_heads=16,
108
+ decoder_ffn_dim=4096,
109
+ activation_function="gelu",
110
+ max_position_embeddings=512,
111
+ dropout=0.1,
112
+ attention_dropout=0.0,
113
+ activation_dropout=0.0,
114
+ decoder_start_token_id=2,
115
+ init_std=0.02,
116
+ decoder_layerdrop=0.0,
117
+ use_cache=True,
118
+ scale_embedding=False,
119
+ use_learned_position_embeddings=True,
120
+ layernorm_embedding=True,
121
+ pad_token_id=1,
122
+ bos_token_id=0,
123
+ eos_token_id=2,
124
+ **kwargs,
125
+ ):
126
+ self.vocab_size = vocab_size
127
+ self.d_model = d_model
128
+ self.decoder_layers = decoder_layers
129
+ self.decoder_attention_heads = decoder_attention_heads
130
+ self.decoder_ffn_dim = decoder_ffn_dim
131
+ self.activation_function = activation_function
132
+ self.max_position_embeddings = max_position_embeddings
133
+ self.dropout = dropout
134
+ self.attention_dropout = attention_dropout
135
+ self.activation_dropout = activation_dropout
136
+ self.init_std = init_std
137
+ self.decoder_layerdrop = decoder_layerdrop
138
+ self.use_cache = use_cache
139
+ self.scale_embedding = scale_embedding
140
+ self.use_learned_position_embeddings = use_learned_position_embeddings
141
+ self.layernorm_embedding = layernorm_embedding
142
+
143
+ super().__init__(
144
+ pad_token_id=pad_token_id,
145
+ bos_token_id=bos_token_id,
146
+ eos_token_id=eos_token_id,
147
+ decoder_start_token_id=decoder_start_token_id,
148
+ **kwargs,
149
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ import requests
22
+ import torch
23
+ from PIL import Image
24
+
25
+ from transformers import (
26
+ RobertaTokenizer,
27
+ TrOCRConfig,
28
+ TrOCRForCausalLM,
29
+ TrOCRProcessor,
30
+ VisionEncoderDecoderModel,
31
+ ViTConfig,
32
+ ViTFeatureExtractor,
33
+ ViTModel,
34
+ )
35
+ from transformers.utils import logging
36
+
37
+
38
+ logging.set_verbosity_info()
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ # here we list all keys to be renamed (original name on the left, our name on the right)
43
+ def create_rename_keys(encoder_config, decoder_config):
44
+ rename_keys = []
45
+ for i in range(encoder_config.num_hidden_layers):
46
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
47
+ rename_keys.append(
48
+ (f"encoder.deit.blocks.{i}.norm1.weight", f"encoder.encoder.layer.{i}.layernorm_before.weight")
49
+ )
50
+ rename_keys.append((f"encoder.deit.blocks.{i}.norm1.bias", f"encoder.encoder.layer.{i}.layernorm_before.bias"))
51
+ rename_keys.append(
52
+ (f"encoder.deit.blocks.{i}.attn.proj.weight", f"encoder.encoder.layer.{i}.attention.output.dense.weight")
53
+ )
54
+ rename_keys.append(
55
+ (f"encoder.deit.blocks.{i}.attn.proj.bias", f"encoder.encoder.layer.{i}.attention.output.dense.bias")
56
+ )
57
+ rename_keys.append(
58
+ (f"encoder.deit.blocks.{i}.norm2.weight", f"encoder.encoder.layer.{i}.layernorm_after.weight")
59
+ )
60
+ rename_keys.append((f"encoder.deit.blocks.{i}.norm2.bias", f"encoder.encoder.layer.{i}.layernorm_after.bias"))
61
+ rename_keys.append(
62
+ (f"encoder.deit.blocks.{i}.mlp.fc1.weight", f"encoder.encoder.layer.{i}.intermediate.dense.weight")
63
+ )
64
+ rename_keys.append(
65
+ (f"encoder.deit.blocks.{i}.mlp.fc1.bias", f"encoder.encoder.layer.{i}.intermediate.dense.bias")
66
+ )
67
+ rename_keys.append(
68
+ (f"encoder.deit.blocks.{i}.mlp.fc2.weight", f"encoder.encoder.layer.{i}.output.dense.weight")
69
+ )
70
+ rename_keys.append((f"encoder.deit.blocks.{i}.mlp.fc2.bias", f"encoder.encoder.layer.{i}.output.dense.bias"))
71
+
72
+ # cls token, position embeddings and patch embeddings of encoder
73
+ rename_keys.extend(
74
+ [
75
+ ("encoder.deit.cls_token", "encoder.embeddings.cls_token"),
76
+ ("encoder.deit.pos_embed", "encoder.embeddings.position_embeddings"),
77
+ ("encoder.deit.patch_embed.proj.weight", "encoder.embeddings.patch_embeddings.projection.weight"),
78
+ ("encoder.deit.patch_embed.proj.bias", "encoder.embeddings.patch_embeddings.projection.bias"),
79
+ ("encoder.deit.norm.weight", "encoder.layernorm.weight"),
80
+ ("encoder.deit.norm.bias", "encoder.layernorm.bias"),
81
+ ]
82
+ )
83
+
84
+ return rename_keys
85
+
86
+
87
+ # we split up the matrix of each encoder layer into queries, keys and values
88
+ def read_in_q_k_v(state_dict, encoder_config):
89
+ for i in range(encoder_config.num_hidden_layers):
90
+ # queries, keys and values (only weights, no biases)
91
+ in_proj_weight = state_dict.pop(f"encoder.deit.blocks.{i}.attn.qkv.weight")
92
+
93
+ state_dict[f"encoder.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
94
+ : encoder_config.hidden_size, :
95
+ ]
96
+ state_dict[f"encoder.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
97
+ encoder_config.hidden_size : encoder_config.hidden_size * 2, :
98
+ ]
99
+ state_dict[f"encoder.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
100
+ -encoder_config.hidden_size :, :
101
+ ]
102
+
103
+
104
+ def rename_key(dct, old, new):
105
+ val = dct.pop(old)
106
+ dct[new] = val
107
+
108
+
109
+ # We will verify our results on an image of the IAM Handwriting Database
110
+ def prepare_img(checkpoint_url):
111
+ if "handwritten" in checkpoint_url:
112
+ url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg" # industry
113
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have
114
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let
115
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" #
116
+ # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg"
117
+ elif "printed" in checkpoint_url or "stage1" in checkpoint_url:
118
+ 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"
119
+ im = Image.open(requests.get(url, stream=True).raw).convert("RGB")
120
+ return im
121
+
122
+
123
+ @torch.no_grad()
124
+ def convert_tr_ocr_checkpoint(checkpoint_url, pytorch_dump_folder_path):
125
+ """
126
+ Copy/paste/tweak model's weights to our VisionEncoderDecoderModel structure.
127
+ """
128
+ # define encoder and decoder configs based on checkpoint_url
129
+ encoder_config = ViTConfig(image_size=384, qkv_bias=False)
130
+ decoder_config = TrOCRConfig()
131
+
132
+ # size of the architecture
133
+ if "base" in checkpoint_url:
134
+ decoder_config.encoder_hidden_size = 768
135
+ elif "large" in checkpoint_url:
136
+ # use ViT-large encoder
137
+ encoder_config.hidden_size = 1024
138
+ encoder_config.intermediate_size = 4096
139
+ encoder_config.num_hidden_layers = 24
140
+ encoder_config.num_attention_heads = 16
141
+ decoder_config.encoder_hidden_size = 1024
142
+ else:
143
+ raise ValueError("Should either find 'base' or 'large' in checkpoint URL")
144
+
145
+ # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards
146
+ if "large-printed" in checkpoint_url or "stage1" in checkpoint_url:
147
+ decoder_config.tie_word_embeddings = False
148
+ decoder_config.activation_function = "relu"
149
+ decoder_config.max_position_embeddings = 1024
150
+ decoder_config.scale_embedding = True
151
+ decoder_config.use_learned_position_embeddings = False
152
+ decoder_config.layernorm_embedding = False
153
+
154
+ # load HuggingFace model
155
+ encoder = ViTModel(encoder_config, add_pooling_layer=False)
156
+ decoder = TrOCRForCausalLM(decoder_config)
157
+ model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)
158
+ model.eval()
159
+
160
+ # load state_dict of original model, rename some keys
161
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu", check_hash=True)["model"]
162
+
163
+ rename_keys = create_rename_keys(encoder_config, decoder_config)
164
+ for src, dest in rename_keys:
165
+ rename_key(state_dict, src, dest)
166
+ read_in_q_k_v(state_dict, encoder_config)
167
+
168
+ # remove parameters we don't need
169
+ del state_dict["encoder.deit.head.weight"]
170
+ del state_dict["encoder.deit.head.bias"]
171
+ del state_dict["decoder.version"]
172
+
173
+ # add prefix to decoder keys
174
+ for key, val in state_dict.copy().items():
175
+ val = state_dict.pop(key)
176
+ if key.startswith("decoder") and "output_projection" not in key:
177
+ state_dict["decoder.model." + key] = val
178
+ else:
179
+ state_dict[key] = val
180
+
181
+ # load state dict
182
+ model.load_state_dict(state_dict)
183
+
184
+ # Check outputs on an image
185
+ feature_extractor = ViTFeatureExtractor(size=encoder_config.image_size)
186
+ tokenizer = RobertaTokenizer.from_pretrained("roberta-large")
187
+ processor = TrOCRProcessor(feature_extractor, tokenizer)
188
+
189
+ pixel_values = processor(images=prepare_img(checkpoint_url), return_tensors="pt").pixel_values
190
+
191
+ # verify logits
192
+ decoder_input_ids = torch.tensor([[model.config.decoder.decoder_start_token_id]])
193
+ outputs = model(pixel_values=pixel_values, decoder_input_ids=decoder_input_ids)
194
+ logits = outputs.logits
195
+
196
+ expected_shape = torch.Size([1, 1, 50265])
197
+ if "trocr-base-handwritten" in checkpoint_url:
198
+ expected_slice = torch.tensor(
199
+ [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311]
200
+ )
201
+ elif "trocr-large-handwritten" in checkpoint_url:
202
+ expected_slice = torch.tensor(
203
+ [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170]
204
+ )
205
+ elif "trocr-base-printed" in checkpoint_url:
206
+ expected_slice = torch.tensor(
207
+ [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210]
208
+ )
209
+ elif "trocr-large-printed" in checkpoint_url:
210
+ expected_slice = torch.tensor(
211
+ [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535]
212
+ )
213
+
214
+ if "stage1" not in checkpoint_url:
215
+ assert logits.shape == expected_shape, "Shape of logits not as expected"
216
+ assert torch.allclose(logits[0, 0, :10], expected_slice, atol=1e-3), "First elements of logits not as expected"
217
+
218
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
219
+ print(f"Saving model to {pytorch_dump_folder_path}")
220
+ model.save_pretrained(pytorch_dump_folder_path)
221
+ print(f"Saving processor to {pytorch_dump_folder_path}")
222
+ processor.save_pretrained(pytorch_dump_folder_path)
223
+
224
+
225
+ if __name__ == "__main__":
226
+ parser = argparse.ArgumentParser()
227
+
228
+ parser.add_argument(
229
+ "--checkpoint_url",
230
+ default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt",
231
+ type=str,
232
+ help="URL to the original PyTorch checkpoint (.pth file).",
233
+ )
234
+ parser.add_argument(
235
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
236
+ )
237
+ args = parser.parse_args()
238
+ convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/modeling_trocr.py ADDED
@@ -0,0 +1,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ import copy
19
+ import math
20
+ import random
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import torch
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ...activations import ACT2FN
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
+ TROCR_PRETRAINED_MODEL_ARCHIVE_LIST = [
41
+ "microsoft/trocr-base-handwritten",
42
+ # See all TrOCR models at https://huggingface.co/models?filter=trocr
43
+ ]
44
+
45
+
46
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
47
+ def _make_causal_mask(
48
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
49
+ ):
50
+ """
51
+ Make causal mask used for bi-directional self-attention.
52
+ """
53
+ bsz, tgt_len = input_ids_shape
54
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
55
+ mask_cond = torch.arange(mask.size(-1), device=device)
56
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
57
+ mask = mask.to(dtype)
58
+
59
+ if past_key_values_length > 0:
60
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
61
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
62
+
63
+
64
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
65
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
66
+ """
67
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
68
+ """
69
+ bsz, src_len = mask.size()
70
+ tgt_len = tgt_len if tgt_len is not None else src_len
71
+
72
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
73
+
74
+ inverted_mask = 1.0 - expanded_mask
75
+
76
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
77
+
78
+
79
+ # Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->TrOCR
80
+ class TrOCRLearnedPositionalEmbedding(nn.Embedding):
81
+ """
82
+ This module learns positional embeddings up to a fixed maximum size.
83
+ """
84
+
85
+ def __init__(self, num_embeddings: int, embedding_dim: int):
86
+ # TrOCR is set up so that if padding_idx is specified then offset the embedding ids by 2
87
+ # and adjust num_embeddings appropriately. Other models don't have this hack
88
+ self.offset = 2
89
+ super().__init__(num_embeddings + self.offset, embedding_dim)
90
+
91
+ def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
92
+ """`input_ids' shape is expected to be [bsz x seqlen]."""
93
+
94
+ bsz, seq_len = input_ids.shape[:2]
95
+ positions = torch.arange(
96
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
97
+ ).expand(bsz, -1)
98
+
99
+ return super().forward(positions + self.offset)
100
+
101
+
102
+ class TrOCRSinusoidalPositionalEmbedding(nn.Module):
103
+ """This module produces sinusoidal positional embeddings of any length."""
104
+
105
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
106
+ super().__init__()
107
+ self.offset = 2
108
+ self.embedding_dim = embedding_dim
109
+ self.padding_idx = padding_idx
110
+ self.weights = self.get_embedding(num_positions, embedding_dim, padding_idx)
111
+ self.register_buffer("_float_tensor", torch.FloatTensor(1))
112
+
113
+ @staticmethod
114
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
115
+ """
116
+ Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
117
+ description in Section 3.5 of "Attention Is All You Need".
118
+ """
119
+ half_dim = embedding_dim // 2
120
+ emb = math.log(10000) / (half_dim - 1)
121
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
122
+ emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
123
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
124
+ if embedding_dim % 2 == 1:
125
+ # zero pad
126
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
127
+ if padding_idx is not None:
128
+ emb[padding_idx, :] = 0
129
+
130
+ return emb.to(torch.get_default_dtype())
131
+
132
+ @torch.no_grad()
133
+ def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
134
+ bsz, seq_len = input_ids.size()
135
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
136
+ position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
137
+ input_ids.device
138
+ )
139
+
140
+ # expand embeddings if needed
141
+ max_pos = self.padding_idx + 1 + seq_len
142
+ if self.weights is None or max_pos > self.weights.size(0):
143
+ # recompute/expand embeddings if needed
144
+ self.weights = self.get_embedding(max_pos, self.embedding_dim, self.padding_idx)
145
+ self.weights = self.weights.to(self._float_tensor)
146
+
147
+ x = self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach()
148
+
149
+ return x
150
+
151
+ def create_position_ids_from_input_ids(
152
+ self, input_ids: torch.Tensor, padding_idx: int, past_key_values_length: Optional[int] = 0
153
+ ):
154
+ """
155
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
156
+ symbols are ignored. This is modified from fairseq's `utils.make_positions`.
157
+ """
158
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
159
+ mask = input_ids.ne(padding_idx).int()
160
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
161
+ return incremental_indices.long() + padding_idx
162
+
163
+
164
+ class TrOCRAttention(nn.Module):
165
+ """Multi-headed attention from 'Attention Is All You Need' paper."""
166
+
167
+ def __init__(
168
+ self,
169
+ config,
170
+ embed_dim: int,
171
+ num_heads: int,
172
+ kdim: int = None,
173
+ vdim: int = None,
174
+ dropout: float = 0.0,
175
+ is_decoder: bool = False,
176
+ bias: bool = True,
177
+ is_cross_attention: bool = False,
178
+ ):
179
+ super().__init__()
180
+ self.embed_dim = embed_dim
181
+ self.kdim = kdim if kdim is not None else embed_dim
182
+ self.vdim = vdim if vdim is not None else embed_dim
183
+ self.num_heads = num_heads
184
+ self.dropout = dropout
185
+ self.head_dim = embed_dim // num_heads
186
+ if not (self.head_dim * num_heads == self.embed_dim):
187
+ raise ValueError(
188
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
189
+ f" {num_heads})."
190
+ )
191
+ self.scaling = self.head_dim**-0.5
192
+ self.is_decoder = is_decoder
193
+
194
+ self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias)
195
+ self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias)
196
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
197
+
198
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
199
+
200
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
201
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
202
+
203
+ def forward(
204
+ self,
205
+ hidden_states: torch.Tensor,
206
+ key_value_states: Optional[torch.Tensor] = None,
207
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
208
+ attention_mask: Optional[torch.Tensor] = None,
209
+ layer_head_mask: Optional[torch.Tensor] = None,
210
+ output_attentions: bool = False,
211
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
212
+ """Input shape: Batch x Time x Channel"""
213
+
214
+ # if key_value_states are provided this layer is used as a cross-attention layer
215
+ # for the decoder
216
+ is_cross_attention = key_value_states is not None
217
+ bsz, tgt_len, embed_dim = hidden_states.size()
218
+
219
+ # get query proj
220
+ query_states = self.q_proj(hidden_states) * self.scaling
221
+ # get key, value proj
222
+ if is_cross_attention and past_key_value is not None:
223
+ # reuse k,v, cross_attentions
224
+ key_states = past_key_value[0]
225
+ value_states = past_key_value[1]
226
+ elif is_cross_attention:
227
+ # cross_attentions
228
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
229
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
230
+ elif past_key_value is not None:
231
+ # reuse k, v, self_attention
232
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
233
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
234
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
235
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
236
+ else:
237
+ # self_attention
238
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
239
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
240
+
241
+ if self.is_decoder:
242
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
243
+ # Further calls to cross_attention layer can then reuse all cross-attention
244
+ # key/value_states (first "if" case)
245
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
246
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
247
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
248
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
249
+ past_key_value = (key_states, value_states)
250
+
251
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
252
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
253
+ key_states = key_states.view(*proj_shape)
254
+ value_states = value_states.view(*proj_shape)
255
+
256
+ src_len = key_states.size(1)
257
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
258
+
259
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
260
+ raise ValueError(
261
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
262
+ f" {attn_weights.size()}"
263
+ )
264
+
265
+ if attention_mask is not None:
266
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
267
+ raise ValueError(
268
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
269
+ )
270
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
271
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
272
+
273
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
274
+
275
+ if layer_head_mask is not None:
276
+ if layer_head_mask.size() != (self.num_heads,):
277
+ raise ValueError(
278
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
279
+ f" {layer_head_mask.size()}"
280
+ )
281
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
282
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
283
+
284
+ if output_attentions:
285
+ # this operation is a bit awkward, but it's required to
286
+ # make sure that attn_weights keeps its gradient.
287
+ # In order to do so, attn_weights have to be reshaped
288
+ # twice and have to be reused in the following
289
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
290
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
291
+ else:
292
+ attn_weights_reshaped = None
293
+
294
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
295
+
296
+ attn_output = torch.bmm(attn_probs, value_states)
297
+
298
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
299
+ raise ValueError(
300
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
301
+ f" {attn_output.size()}"
302
+ )
303
+
304
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
305
+ attn_output = attn_output.transpose(1, 2)
306
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
307
+
308
+ attn_output = self.out_proj(attn_output)
309
+
310
+ return attn_output, attn_weights_reshaped, past_key_value
311
+
312
+
313
+ class TrOCRDecoderLayer(nn.Module):
314
+ def __init__(self, config: TrOCRConfig):
315
+ super().__init__()
316
+ self.embed_dim = config.hidden_size
317
+
318
+ self.self_attn = TrOCRAttention(
319
+ config,
320
+ embed_dim=self.embed_dim,
321
+ num_heads=config.decoder_attention_heads,
322
+ dropout=config.attention_dropout,
323
+ is_decoder=True,
324
+ )
325
+ self.dropout = config.dropout
326
+ self.activation_fn = ACT2FN[config.activation_function]
327
+ self.activation_dropout = config.activation_dropout
328
+
329
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
330
+
331
+ if config.is_decoder:
332
+ self.encoder_attn = TrOCRAttention(
333
+ config,
334
+ embed_dim=self.embed_dim,
335
+ num_heads=config.decoder_attention_heads,
336
+ kdim=config.cross_attention_hidden_size,
337
+ vdim=config.cross_attention_hidden_size,
338
+ dropout=config.attention_dropout,
339
+ is_decoder=True,
340
+ is_cross_attention=True,
341
+ )
342
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
343
+
344
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
345
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
346
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
347
+
348
+ def forward(
349
+ self,
350
+ hidden_states: torch.Tensor,
351
+ attention_mask: Optional[torch.Tensor] = None,
352
+ encoder_hidden_states: Optional[torch.Tensor] = None,
353
+ encoder_attention_mask: Optional[torch.Tensor] = None,
354
+ layer_head_mask: Optional[torch.Tensor] = None,
355
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
356
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
357
+ output_attentions: Optional[bool] = False,
358
+ use_cache: Optional[bool] = True,
359
+ ):
360
+ """
361
+ Args:
362
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
363
+ attention_mask (`torch.FloatTensor`): attention mask of size
364
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
365
+ encoder_hidden_states (`torch.FloatTensor`):
366
+ cross attention input to the layer of shape `(seq_len, batch, embed_dim)`
367
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
368
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
369
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
370
+ `(encoder_attention_heads,)`.
371
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
372
+ size *(decoder_attention_heads,)*.
373
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
374
+ output_attentions (`bool`, *optional*):
375
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
376
+ returned tensors for more detail.
377
+ """
378
+ residual = hidden_states
379
+
380
+ # Self Attention
381
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
382
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
383
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
384
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
385
+ hidden_states=hidden_states,
386
+ past_key_value=self_attn_past_key_value,
387
+ attention_mask=attention_mask,
388
+ layer_head_mask=layer_head_mask,
389
+ output_attentions=output_attentions,
390
+ )
391
+
392
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
393
+ hidden_states = residual + hidden_states
394
+ hidden_states = self.self_attn_layer_norm(hidden_states)
395
+
396
+ # Cross-Attention Block
397
+ cross_attn_present_key_value = None
398
+ cross_attn_weights = None
399
+
400
+ if encoder_hidden_states is not None:
401
+ residual = hidden_states
402
+
403
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
404
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
405
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
406
+ hidden_states=hidden_states,
407
+ key_value_states=encoder_hidden_states,
408
+ attention_mask=encoder_attention_mask,
409
+ layer_head_mask=cross_attn_layer_head_mask,
410
+ past_key_value=cross_attn_past_key_value,
411
+ output_attentions=output_attentions,
412
+ )
413
+
414
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
415
+ hidden_states = residual + hidden_states
416
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
417
+
418
+ # add cross-attn to positions 3,4 of present_key_value tuple
419
+ present_key_value = present_key_value + cross_attn_present_key_value
420
+
421
+ # Fully Connected
422
+ residual = hidden_states
423
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
424
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
425
+ hidden_states = self.fc2(hidden_states)
426
+
427
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
428
+ hidden_states = residual + hidden_states
429
+ hidden_states = self.final_layer_norm(hidden_states)
430
+
431
+ outputs = (hidden_states,)
432
+
433
+ if output_attentions:
434
+ outputs += (self_attn_weights, cross_attn_weights)
435
+
436
+ if use_cache:
437
+ outputs += (present_key_value,)
438
+
439
+ return outputs
440
+
441
+
442
+ class TrOCRPreTrainedModel(PreTrainedModel):
443
+ config_class = TrOCRConfig
444
+ base_model_prefix = "model"
445
+ supports_gradient_checkpointing = True
446
+
447
+ def _init_weights(self, module):
448
+ std = self.config.init_std
449
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
450
+ module.weight.data.normal_(mean=0.0, std=std)
451
+ if module.bias is not None:
452
+ module.bias.data.zero_()
453
+ elif isinstance(module, nn.Embedding):
454
+ module.weight.data.normal_(mean=0.0, std=std)
455
+ if module.padding_idx is not None:
456
+ module.weight.data[module.padding_idx].zero_()
457
+
458
+ def _set_gradient_checkpointing(self, module, value=False):
459
+ if isinstance(module, TrOCRDecoder):
460
+ module.gradient_checkpointing = value
461
+
462
+
463
+ TROCR_START_DOCSTRING = r"""
464
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
465
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
466
+ etc.)
467
+
468
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
469
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
470
+ and behavior.
471
+
472
+ Parameters:
473
+ config ([`TrOCRConfig`]):
474
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
475
+ load the weights associated with the model, only the configuration. Check out the
476
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
477
+ """
478
+
479
+
480
+ class TrOCRDecoder(TrOCRPreTrainedModel):
481
+ """
482
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TrOCRDecoderLayer`]
483
+
484
+ Args:
485
+ config: TrOCRConfig
486
+ """
487
+
488
+ def __init__(self, config: TrOCRConfig):
489
+ super().__init__(config)
490
+ self.dropout = config.dropout
491
+ self.layerdrop = config.decoder_layerdrop
492
+ self.padding_idx = config.pad_token_id
493
+ self.embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0
494
+
495
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
496
+
497
+ if config.use_learned_position_embeddings:
498
+ self.embed_positions = TrOCRLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size)
499
+ else:
500
+ self.embed_positions = TrOCRSinusoidalPositionalEmbedding(
501
+ config.max_position_embeddings + self.padding_idx + 1,
502
+ config.hidden_size,
503
+ self.padding_idx,
504
+ )
505
+
506
+ if config.layernorm_embedding:
507
+ self.layernorm_embedding = nn.LayerNorm(config.hidden_size)
508
+ else:
509
+ self.layernorm_embedding = None
510
+
511
+ self.layers = nn.ModuleList([TrOCRDecoderLayer(config) for _ in range(config.decoder_layers)])
512
+
513
+ self.gradient_checkpointing = False
514
+ # Initialize weights and apply final processing
515
+ self.post_init()
516
+
517
+ def get_input_embeddings(self):
518
+ return self.embed_tokens
519
+
520
+ def set_input_embeddings(self, value):
521
+ self.embed_tokens = value
522
+
523
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
524
+ # create causal mask
525
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
526
+ combined_attention_mask = None
527
+ if input_shape[-1] > 1:
528
+ combined_attention_mask = _make_causal_mask(
529
+ input_shape,
530
+ inputs_embeds.dtype,
531
+ device=inputs_embeds.device,
532
+ past_key_values_length=past_key_values_length,
533
+ )
534
+
535
+ if attention_mask is not None:
536
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
537
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
538
+ combined_attention_mask = (
539
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
540
+ )
541
+
542
+ return combined_attention_mask
543
+
544
+ def forward(
545
+ self,
546
+ input_ids=None,
547
+ attention_mask=None,
548
+ encoder_hidden_states=None,
549
+ encoder_attention_mask=None,
550
+ head_mask=None,
551
+ cross_attn_head_mask=None,
552
+ past_key_values=None,
553
+ inputs_embeds=None,
554
+ use_cache=None,
555
+ output_attentions=None,
556
+ output_hidden_states=None,
557
+ return_dict=None,
558
+ ):
559
+ r"""
560
+ Args:
561
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
562
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
563
+ provide it.
564
+
565
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
566
+ [`PreTrainedTokenizer.__call__`] for details.
567
+
568
+ [What are input IDs?](../glossary#input-ids)
569
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
570
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
571
+
572
+ - 1 for tokens that are **not masked**,
573
+ - 0 for tokens that are **masked**.
574
+
575
+ [What are attention masks?](../glossary#attention-mask)
576
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
577
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
578
+ of the decoder.
579
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
580
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
581
+ selected in `[0, 1]`:
582
+
583
+ - 1 for tokens that are **not masked**,
584
+ - 0 for tokens that are **masked**.
585
+
586
+ [What are attention masks?](../glossary#attention-mask)
587
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
588
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
589
+
590
+ - 1 indicates the head is **not masked**,
591
+ - 0 indicates the head is **masked**.
592
+
593
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
594
+ Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
595
+ on hidden heads. Mask values selected in `[0, 1]`:
596
+
597
+ - 1 indicates the head is **not masked**,
598
+ - 0 indicates the head is **masked**.
599
+
600
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
601
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
602
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
603
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
604
+
605
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
606
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
607
+
608
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
609
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
610
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of
611
+ shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
612
+ `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
613
+ control over how to convert `input_ids` indices into associated vectors than the model's internal
614
+ embedding lookup matrix.
615
+ output_attentions (`bool`, *optional*):
616
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
617
+ returned tensors for more detail.
618
+ output_hidden_states (`bool`, *optional*):
619
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
620
+ for more detail.
621
+ return_dict (`bool`, *optional*):
622
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
623
+ """
624
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
625
+ output_hidden_states = (
626
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
627
+ )
628
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
629
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
630
+
631
+ # retrieve input_ids and inputs_embeds
632
+ if input_ids is not None and inputs_embeds is not None:
633
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
634
+ elif input_ids is not None:
635
+ input = input_ids
636
+ input_ids = input_ids.view(-1, input.shape[-1])
637
+ elif inputs_embeds is not None:
638
+ input_shape = inputs_embeds.size()[:-1]
639
+ input = inputs_embeds[:, :, -1]
640
+ else:
641
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
642
+
643
+ # past_key_values_length
644
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
645
+
646
+ if inputs_embeds is None:
647
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
648
+
649
+ if self.config.use_learned_position_embeddings:
650
+ embed_pos = self.embed_positions(input, past_key_values_length=past_key_values_length)
651
+ else:
652
+ embed_pos = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
653
+
654
+ hidden_states = inputs_embeds + embed_pos
655
+
656
+ if self.layernorm_embedding is not None:
657
+ hidden_states = self.layernorm_embedding(hidden_states)
658
+
659
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
660
+
661
+ input_shape = input.shape
662
+
663
+ attention_mask = self._prepare_decoder_attention_mask(
664
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
665
+ )
666
+
667
+ # expand encoder attention mask
668
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
669
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
670
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
671
+
672
+ if self.gradient_checkpointing and self.training:
673
+ if use_cache:
674
+ logger.warning_once(
675
+ "`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`..."
676
+ )
677
+ use_cache = False
678
+
679
+ # decoder layers
680
+ all_hidden_states = () if output_hidden_states else None
681
+ all_self_attns = () if output_attentions else None
682
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
683
+ next_decoder_cache = () if use_cache else None
684
+
685
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
686
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
687
+ if attn_mask is not None:
688
+ if attn_mask.size()[0] != (len(self.layers)):
689
+ raise ValueError(
690
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
691
+ f" {head_mask.size()[0]}."
692
+ )
693
+ for idx, decoder_layer in enumerate(self.layers):
694
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
695
+ if output_hidden_states:
696
+ all_hidden_states += (hidden_states,)
697
+ dropout_probability = random.uniform(0, 1)
698
+ if self.training and (dropout_probability < self.layerdrop):
699
+ continue
700
+
701
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
702
+
703
+ if self.gradient_checkpointing and self.training:
704
+
705
+ def create_custom_forward(module):
706
+ def custom_forward(*inputs):
707
+ # None for past_key_value
708
+ return module(*inputs, output_attentions, use_cache)
709
+
710
+ return custom_forward
711
+
712
+ layer_outputs = torch.utils.checkpoint.checkpoint(
713
+ create_custom_forward(decoder_layer),
714
+ hidden_states,
715
+ attention_mask,
716
+ encoder_hidden_states,
717
+ encoder_attention_mask,
718
+ head_mask[idx] if head_mask is not None else None,
719
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
720
+ None,
721
+ )
722
+ else:
723
+ layer_outputs = decoder_layer(
724
+ hidden_states,
725
+ attention_mask=attention_mask,
726
+ encoder_hidden_states=encoder_hidden_states,
727
+ encoder_attention_mask=encoder_attention_mask,
728
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
729
+ cross_attn_layer_head_mask=(
730
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
731
+ ),
732
+ past_key_value=past_key_value,
733
+ output_attentions=output_attentions,
734
+ use_cache=use_cache,
735
+ )
736
+ hidden_states = layer_outputs[0]
737
+
738
+ if use_cache:
739
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
740
+
741
+ if output_attentions:
742
+ all_self_attns += (layer_outputs[1],)
743
+
744
+ if encoder_hidden_states is not None:
745
+ all_cross_attentions += (layer_outputs[2],)
746
+
747
+ # add hidden states from the last decoder layer
748
+ if output_hidden_states:
749
+ all_hidden_states += (hidden_states,)
750
+
751
+ next_cache = next_decoder_cache if use_cache else None
752
+ if not return_dict:
753
+ return tuple(
754
+ v
755
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
756
+ if v is not None
757
+ )
758
+ return BaseModelOutputWithPastAndCrossAttentions(
759
+ last_hidden_state=hidden_states,
760
+ past_key_values=next_cache,
761
+ hidden_states=all_hidden_states,
762
+ attentions=all_self_attns,
763
+ cross_attentions=all_cross_attentions,
764
+ )
765
+
766
+
767
+ @add_start_docstrings(
768
+ "The TrOCR Model with a language modeling head. Can be used for summarization.",
769
+ TROCR_START_DOCSTRING,
770
+ )
771
+ class TrOCRDecoderWrapper(TrOCRPreTrainedModel):
772
+ """
773
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
774
+ used in combination with the [`EncoderDecoderModel`] framework.
775
+ """
776
+
777
+ def __init__(self, config):
778
+ super().__init__(config)
779
+ self.decoder = TrOCRDecoder(config)
780
+
781
+ def forward(self, *args, **kwargs):
782
+ return self.decoder(*args, **kwargs)
783
+
784
+
785
+ @add_start_docstrings(
786
+ "The TrOCR Decoder with a language modeling head. Can be used as the decoder part of [`EncoderDecoderModel`] and"
787
+ " [`VisionEncoderDecoder`].",
788
+ TROCR_START_DOCSTRING,
789
+ )
790
+ class TrOCRForCausalLM(TrOCRPreTrainedModel):
791
+ _keys_to_ignore_on_load_missing = ["output_projection.weight"]
792
+
793
+ def __init__(self, config):
794
+ config = copy.deepcopy(config)
795
+ config.is_decoder = True
796
+ config.is_encoder_decoder = False
797
+ super().__init__(config)
798
+ self.model = TrOCRDecoderWrapper(config)
799
+
800
+ self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
801
+
802
+ # Initialize weights and apply final processing
803
+ self.post_init()
804
+
805
+ def get_input_embeddings(self):
806
+ return self.model.decoder.embed_tokens
807
+
808
+ def set_input_embeddings(self, value):
809
+ self.model.decoder.embed_tokens = value
810
+
811
+ def get_output_embeddings(self):
812
+ return self.output_projection
813
+
814
+ def set_output_embeddings(self, new_embeddings):
815
+ self.output_projection = new_embeddings
816
+
817
+ def set_decoder(self, decoder):
818
+ self.model.decoder = decoder
819
+
820
+ def get_decoder(self):
821
+ return self.model.decoder
822
+
823
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
824
+ def forward(
825
+ self,
826
+ input_ids: Optional[torch.LongTensor] = None,
827
+ attention_mask: Optional[torch.Tensor] = None,
828
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
829
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
830
+ head_mask: Optional[torch.Tensor] = None,
831
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
832
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
833
+ inputs_embeds: Optional[torch.FloatTensor] = None,
834
+ labels: Optional[torch.LongTensor] = None,
835
+ use_cache: Optional[bool] = None,
836
+ output_attentions: Optional[bool] = None,
837
+ output_hidden_states: Optional[bool] = None,
838
+ return_dict: Optional[bool] = None,
839
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
840
+ r"""
841
+ Args:
842
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
843
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
844
+ provide it.
845
+
846
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
847
+ [`PreTrainedTokenizer.__call__`] for details.
848
+
849
+ [What are input IDs?](../glossary#input-ids)
850
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
851
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
852
+
853
+ - 1 for tokens that are **not masked**,
854
+ - 0 for tokens that are **masked**.
855
+
856
+ [What are attention masks?](../glossary#attention-mask)
857
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
858
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
859
+ if the model is configured as a decoder.
860
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
861
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
862
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
863
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
864
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
865
+
866
+ - 1 indicates the head is **not masked**,
867
+ - 0 indicates the head is **masked**.
868
+
869
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
870
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
871
+
872
+ - 1 indicates the head is **not masked**,
873
+ - 0 indicates the head is **masked**.
874
+
875
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
876
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
877
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
878
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
879
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
880
+
881
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
882
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
883
+
884
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
885
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
886
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
887
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
888
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
889
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
890
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
891
+ use_cache (`bool`, *optional*):
892
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
893
+ (see `past_key_values`).
894
+
895
+ - 1 for tokens that are **not masked**,
896
+ - 0 for tokens that are **masked**.
897
+ output_attentions (`bool`, *optional*):
898
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
899
+ returned tensors for more detail.
900
+ output_hidden_states (`bool`, *optional*):
901
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
902
+ for more detail.
903
+ return_dict (`bool`, *optional*):
904
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
905
+
906
+ Returns:
907
+
908
+ Example:
909
+
910
+ ```python
911
+ >>> from transformers import (
912
+ ... TrOCRConfig,
913
+ ... TrOCRProcessor,
914
+ ... TrOCRForCausalLM,
915
+ ... ViTConfig,
916
+ ... ViTModel,
917
+ ... VisionEncoderDecoderModel,
918
+ ... )
919
+ >>> import requests
920
+ >>> from PIL import Image
921
+
922
+ >>> # TrOCR is a decoder model and should be used within a VisionEncoderDecoderModel
923
+ >>> # init vision2text model with random weights
924
+ >>> encoder = ViTModel(ViTConfig())
925
+ >>> decoder = TrOCRForCausalLM(TrOCRConfig())
926
+ >>> model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)
927
+
928
+ >>> # If you want to start from the pretrained model, load the checkpoint with `VisionEncoderDecoderModel`
929
+ >>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
930
+ >>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
931
+
932
+ >>> # load image from the IAM dataset
933
+ >>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
934
+ >>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
935
+ >>> pixel_values = processor(image, return_tensors="pt").pixel_values
936
+ >>> text = "industry, ' Mr. Brown commented icily. ' Let us have a"
937
+
938
+ >>> # training
939
+ >>> model.config.decoder_start_token_id = processor.tokenizer.cls_token_id
940
+ >>> model.config.pad_token_id = processor.tokenizer.pad_token_id
941
+ >>> model.config.vocab_size = model.config.decoder.vocab_size
942
+
943
+ >>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
944
+ >>> outputs = model(pixel_values, labels=labels)
945
+ >>> loss = outputs.loss
946
+ >>> round(loss.item(), 2)
947
+ 5.30
948
+
949
+ >>> # inference
950
+ >>> generated_ids = model.generate(pixel_values)
951
+ >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
952
+ >>> generated_text
953
+ 'industry, " Mr. Brown commented icily. " Let us have a'
954
+ ```"""
955
+
956
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
957
+ output_hidden_states = (
958
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
959
+ )
960
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
961
+
962
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
963
+ outputs = self.model.decoder(
964
+ input_ids=input_ids,
965
+ attention_mask=attention_mask,
966
+ encoder_hidden_states=encoder_hidden_states,
967
+ encoder_attention_mask=encoder_attention_mask,
968
+ head_mask=head_mask,
969
+ cross_attn_head_mask=cross_attn_head_mask,
970
+ past_key_values=past_key_values,
971
+ inputs_embeds=inputs_embeds,
972
+ use_cache=use_cache,
973
+ output_attentions=output_attentions,
974
+ output_hidden_states=output_hidden_states,
975
+ return_dict=return_dict,
976
+ )
977
+
978
+ logits = self.output_projection(outputs[0])
979
+
980
+ loss = None
981
+ if labels is not None:
982
+ loss_fct = CrossEntropyLoss()
983
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
984
+
985
+ if not return_dict:
986
+ output = (logits,) + outputs[1:]
987
+ return (loss,) + output if loss is not None else output
988
+
989
+ return CausalLMOutputWithCrossAttentions(
990
+ loss=loss,
991
+ logits=logits,
992
+ past_key_values=outputs.past_key_values,
993
+ hidden_states=outputs.hidden_states,
994
+ attentions=outputs.attentions,
995
+ cross_attentions=outputs.cross_attentions,
996
+ )
997
+
998
+ def prepare_inputs_for_generation(
999
+ self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
1000
+ ):
1001
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1002
+ if attention_mask is None:
1003
+ attention_mask = input_ids.new_ones(input_ids.shape)
1004
+
1005
+ if past_key_values:
1006
+ input_ids = input_ids[:, -1:]
1007
+ # first step, decoder_cached_states are empty
1008
+ return {
1009
+ "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
1010
+ "attention_mask": attention_mask,
1011
+ "past_key_values": past_key_values,
1012
+ "use_cache": use_cache,
1013
+ }
1014
+
1015
+ @staticmethod
1016
+ def _reorder_cache(past_key_values, beam_idx):
1017
+ reordered_past = ()
1018
+ for layer_past in past_key_values:
1019
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1020
+ return reordered_past
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/trocr/processing_trocr.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import warnings
19
+ from contextlib import contextmanager
20
+
21
+ from ...processing_utils import ProcessorMixin
22
+
23
+
24
+ class TrOCRProcessor(ProcessorMixin):
25
+ r"""
26
+ Constructs a TrOCR processor which wraps a vision image processor and a TrOCR tokenizer into a single processor.
27
+
28
+ [`TrOCRProcessor`] offers all the functionalities of [`ViTImageProcessor`/`DeiTImageProcessor`] and
29
+ [`RobertaTokenizer`/`XLMRobertaTokenizer`]. See the [`~TrOCRProcessor.__call__`] and [`~TrOCRProcessor.decode`] for
30
+ more information.
31
+
32
+ Args:
33
+ image_processor ([`ViTImageProcessor`/`DeiTImageProcessor`]):
34
+ An instance of [`ViTImageProcessor`/`DeiTImageProcessor`]. The image processor is a required input.
35
+ tokenizer ([`RobertaTokenizer`/`XLMRobertaTokenizer`]):
36
+ An instance of [`RobertaTokenizer`/`XLMRobertaTokenizer`]. The tokenizer is a required input.
37
+ """
38
+ attributes = ["image_processor", "tokenizer"]
39
+ image_processor_class = "AutoImageProcessor"
40
+ tokenizer_class = "AutoTokenizer"
41
+
42
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
43
+ if "feature_extractor" in kwargs:
44
+ warnings.warn(
45
+ "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
46
+ " instead.",
47
+ FutureWarning,
48
+ )
49
+ feature_extractor = kwargs.pop("feature_extractor")
50
+
51
+ image_processor = image_processor if image_processor is not None else feature_extractor
52
+ if image_processor is None:
53
+ raise ValueError("You need to specify an `image_processor`.")
54
+ if tokenizer is None:
55
+ raise ValueError("You need to specify a `tokenizer`.")
56
+
57
+ super().__init__(image_processor, tokenizer)
58
+ self.current_processor = self.image_processor
59
+ self._in_target_context_manager = False
60
+
61
+ def __call__(self, *args, **kwargs):
62
+ """
63
+ When used in normal mode, this method forwards all its arguments to AutoImageProcessor's
64
+ [`~AutoImageProcessor.__call__`] and returns its output. If used in the context
65
+ [`~TrOCRProcessor.as_target_processor`] this method forwards all its arguments to TrOCRTokenizer's
66
+ [`~TrOCRTokenizer.__call__`]. Please refer to the doctsring of the above two methods for more information.
67
+ """
68
+ # For backward compatibility
69
+ if self._in_target_context_manager:
70
+ return self.current_processor(*args, **kwargs)
71
+
72
+ images = kwargs.pop("images", None)
73
+ text = kwargs.pop("text", None)
74
+ if len(args) > 0:
75
+ images = args[0]
76
+ args = args[1:]
77
+
78
+ if images is None and text is None:
79
+ raise ValueError("You need to specify either an `images` or `text` input to process.")
80
+
81
+ if images is not None:
82
+ inputs = self.image_processor(images, *args, **kwargs)
83
+ if text is not None:
84
+ encodings = self.tokenizer(text, **kwargs)
85
+
86
+ if text is None:
87
+ return inputs
88
+ elif images is None:
89
+ return encodings
90
+ else:
91
+ inputs["labels"] = encodings["input_ids"]
92
+ return inputs
93
+
94
+ def batch_decode(self, *args, **kwargs):
95
+ """
96
+ This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer
97
+ to the docstring of this method for more information.
98
+ """
99
+ return self.tokenizer.batch_decode(*args, **kwargs)
100
+
101
+ def decode(self, *args, **kwargs):
102
+ """
103
+ This method forwards all its arguments to TrOCRTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
104
+ docstring of this method for more information.
105
+ """
106
+ return self.tokenizer.decode(*args, **kwargs)
107
+
108
+ @contextmanager
109
+ def as_target_processor(self):
110
+ """
111
+ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning TrOCR.
112
+ """
113
+ warnings.warn(
114
+ "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
115
+ "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
116
+ "your images inputs, or in a separate call."
117
+ )
118
+ self._in_target_context_manager = True
119
+ self.current_processor = self.tokenizer
120
+ yield
121
+ self.current_processor = self.image_processor
122
+ self._in_target_context_manager = False
123
+
124
+ @property
125
+ def feature_extractor_class(self):
126
+ warnings.warn(
127
+ "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
128
+ FutureWarning,
129
+ )
130
+ return self.image_processor_class
131
+
132
+ @property
133
+ def feature_extractor(self):
134
+ warnings.warn(
135
+ "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
136
+ FutureWarning,
137
+ )
138
+ return self.image_processor
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/__init__.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ # There's no way to ignore "F401 '...' imported but unused" warnings in this
3
+ # module, but to preserve other warnings. So, don't check this module at all.
4
+
5
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ from typing import TYPE_CHECKING
19
+
20
+ from ...utils import (
21
+ OptionalDependencyNotAvailable,
22
+ _LazyModule,
23
+ is_speech_available,
24
+ is_torch_available,
25
+ is_vision_available,
26
+ )
27
+
28
+
29
+ _import_structure = {
30
+ "configuration_tvlt": ["TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP", "TvltConfig"],
31
+ "processing_tvlt": ["TvltProcessor"],
32
+ }
33
+
34
+ try:
35
+ if not is_torch_available():
36
+ raise OptionalDependencyNotAvailable()
37
+ except OptionalDependencyNotAvailable:
38
+ pass
39
+ else:
40
+ _import_structure["modeling_tvlt"] = [
41
+ "TVLT_PRETRAINED_MODEL_ARCHIVE_LIST",
42
+ "TvltModel",
43
+ "TvltForPreTraining",
44
+ "TvltForAudioVisualClassification",
45
+ "TvltPreTrainedModel",
46
+ ]
47
+
48
+ try:
49
+ if not is_vision_available():
50
+ raise OptionalDependencyNotAvailable()
51
+ except OptionalDependencyNotAvailable:
52
+ pass
53
+ else:
54
+ _import_structure["image_processing_tvlt"] = ["TvltImageProcessor"]
55
+
56
+ try:
57
+ if not is_speech_available():
58
+ raise OptionalDependencyNotAvailable()
59
+ except OptionalDependencyNotAvailable:
60
+ pass
61
+ else:
62
+ _import_structure["feature_extraction_tvlt"] = ["TvltFeatureExtractor"]
63
+
64
+ if TYPE_CHECKING:
65
+ from .configuration_tvlt import TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP, TvltConfig
66
+ from .processing_tvlt import TvltProcessor
67
+
68
+ try:
69
+ if not is_torch_available():
70
+ raise OptionalDependencyNotAvailable()
71
+ except OptionalDependencyNotAvailable:
72
+ pass
73
+ else:
74
+ from .modeling_tvlt import (
75
+ TVLT_PRETRAINED_MODEL_ARCHIVE_LIST,
76
+ TvltForAudioVisualClassification,
77
+ TvltForPreTraining,
78
+ TvltModel,
79
+ TvltPreTrainedModel,
80
+ )
81
+
82
+ try:
83
+ if not is_vision_available():
84
+ raise OptionalDependencyNotAvailable()
85
+ except OptionalDependencyNotAvailable:
86
+ pass
87
+ else:
88
+ from .image_processing_tvlt import TvltImageProcessor
89
+
90
+ try:
91
+ if not is_speech_available():
92
+ raise OptionalDependencyNotAvailable()
93
+ except OptionalDependencyNotAvailable:
94
+ pass
95
+ else:
96
+ from .feature_extraction_tvlt import TvltFeatureExtractor
97
+
98
+ else:
99
+ import sys
100
+
101
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/configuration_tvlt.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 MURGe-Lab 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
+ """ TVLT model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "ZinengTang/tvlt-base": "https://huggingface.co/ZinengTang/tvlt-base/blob/main/config.json",
25
+ }
26
+
27
+
28
+ class TvltConfig(PretrainedConfig):
29
+ r"""
30
+ This is the configuration class to store the configuration of a [`TvltModel`]. It is used to instantiate a TVLT
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 TVLT
33
+ [ZinengTang/tvlt-base](https://huggingface.co/ZinengTang/tvlt-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
+ Args:
39
+ image_size (`int`, *optional*, defaults to 224):
40
+ The size (resolution) of each image.
41
+ spectrogram_length (`int`, *optional*, defaults to 2048):
42
+ The time length of each audio spectrogram.
43
+ frequency_length (`int`, *optional*, defaults to 128):
44
+ The frequency length of audio spectrogram.
45
+ image_patch_size (`List[int]`, *optional*, defaults to `[16, 16]`):
46
+ The size (resolution) of each image patch.
47
+ audio_patch_size (`List[int]`, *optional*, defaults to `[16, 16]`):
48
+ The size (resolution) of each audio patch.
49
+ num_image_channels (`int`, *optional*, defaults to 3):
50
+ The number of input image channels.
51
+ num_audio_channels (`int`, *optional*, defaults to 1):
52
+ The number of input audio channels.
53
+ num_frames (`int`, *optional*, defaults to 8):
54
+ The maximum number of frames for an input video.
55
+ hidden_size (`int`, *optional*, defaults to 768):
56
+ Dimensionality of the encoder layers and the pooler layer.
57
+ num_hidden_layers (`int`, *optional*, defaults to 12):
58
+ Number of hidden layers in the Transformer encoder.
59
+ num_attention_heads (`int`, *optional*, defaults to 12):
60
+ Number of attention heads for each attention layer in the Transformer encoder.
61
+ intermediate_size (`int`, *optional*, defaults to 3072):
62
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
63
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
64
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
65
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
66
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
67
+ The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
68
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
69
+ The dropout ratio for the attention probabilities.
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-6):
73
+ The epsilon used by the layer normalization layers.
74
+ qkv_bias (`bool`, *optional*, defaults to `True`):
75
+ Whether to add a bias to the queries, keys and values.
76
+ use_mean_pooling (`bool`, *optional*, defaults to `False`):
77
+ Whether to mean pool the final hidden states instead of using the final hidden state of the [CLS] token.
78
+ decoder_num_attention_heads (`int`, *optional*, defaults to 16):
79
+ Number of attention heads for each attention layer in the decoder.
80
+ decoder_hidden_size (`int`, *optional*, defaults to 512):
81
+ Dimensionality of the decoder.
82
+ decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
83
+ Number of hidden layers in the decoder.
84
+ decoder_intermediate_size (`int`, *optional*, defaults to 2048):
85
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
86
+ pixel_mask_ratio (`float`, *optional*, defaults to 0.75):
87
+ Image patch masking ratio.
88
+ audio_mask_ratio (`float`, *optional*, defaults to 0.15):
89
+ Audio patch masking ratio.
90
+ audio_mask_type (`str`, *optional*, defaults to `"frame-level"`):
91
+ Audio patch masking type, choose between "frame-level" and "patch-level".
92
+ task_matching (`bool`, *optional*, defaults to `True`):
93
+ Whether to use vision audio matching task in pretraining.
94
+ task_mae (`bool`, *optional*, defaults to `True`):
95
+ Whether to use the masked auto-encoder (MAE) in pretraining.
96
+ loss_type (`str`, *optional*, defaults to `"classification"`):
97
+ Loss types including regression and classification.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import TvltConfig, TvltModel
103
+
104
+ >>> # # Initializing a TVLT ZinengTang/tvlt-base style configuration
105
+ >>> configuration = TvltConfig()
106
+
107
+ >>> # # Initializing a model (with random weights) from the ZinengTang/tvlt-base style configuration
108
+ >>> model = TvltModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+ model_type = "tvlt"
114
+
115
+ def __init__(
116
+ self,
117
+ image_size=224,
118
+ spectrogram_length=2048,
119
+ frequency_length=128,
120
+ image_patch_size=[16, 16],
121
+ audio_patch_size=[16, 16],
122
+ num_image_channels=3,
123
+ num_audio_channels=1,
124
+ num_frames=8,
125
+ hidden_size=768,
126
+ num_hidden_layers=12,
127
+ num_attention_heads=12,
128
+ intermediate_size=3072,
129
+ hidden_act="gelu",
130
+ hidden_dropout_prob=0.0,
131
+ attention_probs_dropout_prob=0.0,
132
+ initializer_range=0.02,
133
+ layer_norm_eps=1e-6,
134
+ qkv_bias=True,
135
+ use_mean_pooling=False,
136
+ decoder_num_attention_heads=16,
137
+ decoder_hidden_size=512,
138
+ decoder_num_hidden_layers=8,
139
+ decoder_intermediate_size=2048,
140
+ pixel_mask_ratio=0.75,
141
+ audio_mask_ratio=0.15,
142
+ audio_mask_type="frame-level",
143
+ task_matching=True,
144
+ task_mae=True,
145
+ loss_type="classification",
146
+ **kwargs,
147
+ ):
148
+ super().__init__(**kwargs)
149
+
150
+ if audio_mask_type not in ("frame-level", "patch_level"):
151
+ raise ValueError(
152
+ "audio_mask_type must be one of two acceptable strategies - {'frame_level', 'patch-level') "
153
+ f"got {audio_mask_type}"
154
+ )
155
+
156
+ self.image_size = image_size
157
+ self.spectrogram_length = spectrogram_length
158
+ self.frequency_length = frequency_length
159
+ self.image_patch_size = image_patch_size
160
+ self.audio_patch_size = audio_patch_size
161
+ self.num_image_channels = num_image_channels
162
+ self.num_audio_channels = num_audio_channels
163
+ self.num_frames = num_frames
164
+
165
+ self.hidden_size = hidden_size
166
+ self.num_hidden_layers = num_hidden_layers
167
+ self.num_attention_heads = num_attention_heads
168
+ self.intermediate_size = intermediate_size
169
+ self.hidden_act = hidden_act
170
+ self.hidden_dropout_prob = hidden_dropout_prob
171
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
172
+ self.initializer_range = initializer_range
173
+ self.layer_norm_eps = layer_norm_eps
174
+ self.qkv_bias = qkv_bias
175
+ self.use_mean_pooling = use_mean_pooling
176
+
177
+ self.decoder_num_attention_heads = decoder_num_attention_heads
178
+ self.decoder_hidden_size = decoder_hidden_size
179
+ self.decoder_num_hidden_layers = decoder_num_hidden_layers
180
+ self.decoder_intermediate_size = decoder_intermediate_size
181
+ self.pixel_mask_ratio = pixel_mask_ratio
182
+ self.audio_mask_ratio = audio_mask_ratio
183
+ self.audio_mask_type = audio_mask_type
184
+
185
+ self.task_matching = task_matching
186
+ self.task_mae = task_mae
187
+ self.loss_type = loss_type
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/feature_extraction_tvlt.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Feature extractor class for TVLT."""
16
+
17
+ from math import ceil
18
+ from typing import List, Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...audio_utils import mel_filter_bank, spectrogram, window_function
23
+ from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
24
+ from ...utils import TensorType, logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class TvltFeatureExtractor(SequenceFeatureExtractor):
31
+ r"""
32
+ Constructs a TVLT audio feature extractor. This feature extractor can be used to prepare audios for the model.
33
+
34
+ This feature extractor inherits from [`FeatureExtractionMixin`] which contains most of the main methods. Users
35
+ should refer to this superclass for more information regarding those methods.
36
+
37
+ Args:
38
+ spectrogram_length (`Dict[str, int]` *optional*, defaults to 2048):
39
+ The time length of each audio spectrogram.
40
+ num_channels (`int` *optional*, defaults to 1):
41
+ Number of audio channels.
42
+ patch_size (`List[int]` *optional*, defaults to `[16, 16]`):
43
+ The patch size of audio patch embedding.
44
+ feature_size (`int`, defaults to 128):
45
+ The frequency length of audio spectrogram.
46
+ sampling_rate (`int`, defaults to 44100):
47
+ The sampling rate at which the audio files should be digitalized expressed in Hertz (Hz).
48
+ hop_length_to_sampling_rate (`int`, defaults to 86):
49
+ Hop length is length of the overlaping windows for the STFT used to obtain the Mel Frequency coefficients.
50
+ For example, with sampling rate 44100, the hop length is 512, with 44100 / 512 = 86
51
+ n_fft (`int`, defaults to 2048):
52
+ Size of the Fourier transform.
53
+ padding_value (`float`, *optional*, defaults to 0.0):
54
+ Padding value used to pad the audio. Should correspond to silences.
55
+ """
56
+
57
+ model_input_names = ["audio_values", "audio_mask"]
58
+
59
+ def __init__(
60
+ self,
61
+ spectrogram_length=2048,
62
+ num_channels=1,
63
+ patch_size=[16, 16],
64
+ feature_size=128,
65
+ sampling_rate=44100,
66
+ hop_length_to_sampling_rate=86,
67
+ n_fft=2048,
68
+ padding_value=0.0,
69
+ **kwargs,
70
+ ):
71
+ super().__init__(
72
+ feature_size=feature_size,
73
+ sampling_rate=sampling_rate,
74
+ padding_value=padding_value,
75
+ **kwargs,
76
+ )
77
+
78
+ self.spectrogram_length = spectrogram_length
79
+ self.num_channels = num_channels
80
+ self.patch_size = patch_size
81
+ self.freq_len = feature_size // self.patch_size[1]
82
+ self.n_fft = n_fft
83
+ self.hop_length = sampling_rate // hop_length_to_sampling_rate
84
+ self.sampling_rate = sampling_rate
85
+ self.padding_value = padding_value
86
+ self.mel_filters = mel_filter_bank(
87
+ num_frequency_bins=1 + n_fft // 2,
88
+ num_mel_filters=feature_size,
89
+ min_frequency=0.0,
90
+ max_frequency=22050.0,
91
+ sampling_rate=sampling_rate,
92
+ norm="slaney",
93
+ mel_scale="slaney",
94
+ ).T
95
+
96
+ def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray:
97
+ """
98
+ Compute the log-mel spectrogram of the provided audio, gives similar results to Whisper's original torch
99
+ implementation with 1e-5 tolerance.
100
+ """
101
+ log_spec = spectrogram(
102
+ waveform,
103
+ window_function(self.n_fft, "hann"),
104
+ frame_length=self.n_fft,
105
+ hop_length=self.hop_length,
106
+ power=2.0,
107
+ mel_filters=self.mel_filters.T,
108
+ log_mel="dB",
109
+ db_range=80.0,
110
+ )
111
+ log_spec = log_spec[:, :-1]
112
+ log_spec = log_spec - 20.0
113
+ log_spec = np.clip(log_spec / 40.0, -2.0, 0.0) + 1.0
114
+ return log_spec
115
+
116
+ def __call__(
117
+ self,
118
+ raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],
119
+ return_tensors: Optional[Union[str, TensorType]] = None,
120
+ return_attention_mask: Optional[bool] = True,
121
+ sampling_rate: Optional[int] = None,
122
+ resample: bool = False,
123
+ mask_audio: bool = False,
124
+ **kwargs,
125
+ ) -> BatchFeature:
126
+ """
127
+ Main method to prepare one or several audio(s) for the model.
128
+
129
+ Args:
130
+ raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
131
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
132
+ values, a list of numpy arrays or a list of list of float values.
133
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
134
+ If set, will return tensors instead of list of python integers. Acceptable values are:
135
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
136
+ - `'np'`: Return Numpy `np.ndarray` objects.
137
+ return_attention_mask (`bool`, *optional*, default to `True`):
138
+ Whether to return the attention mask. If left to the default, will return the attention mask according
139
+ to the specific feature_extractor's default. [What are attention masks?](../glossary#attention-mask)
140
+
141
+ <Tip>
142
+
143
+ For TvltTransformer models, `attention_mask` should alwys be passed for batched inference, to avoid
144
+ subtle bugs.
145
+
146
+ </Tip>
147
+
148
+ sampling_rate (`int`, *optional*):
149
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
150
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
151
+ pipeline. Current model supports sampling rate 16000 and 44100.
152
+ resample (`bool`, *optional*, defaults to `False`):
153
+ If the sampling rate is not matched, resample the input audio to match.
154
+ mask_audio (`bool`, *optional*, defaults to `False`):
155
+ Whether or not to mask input audio for MAE task.
156
+
157
+ Returns:
158
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
159
+
160
+ - **audio_values** -- Audio values to be fed to a model, of shape (batch_size, num_channels, height,
161
+ width).
162
+
163
+ - **audio_mask** -- Audio masks to be fed to a model, of shape (batch_size, num_audio_patches).
164
+ """
165
+
166
+ if sampling_rate is not None:
167
+ if sampling_rate != self.sampling_rate:
168
+ raise ValueError(
169
+ "This feature extractor is set to support sampling rate"
170
+ f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
171
+ f" with {self.sampling_rate} and not {sampling_rate}."
172
+ )
173
+ else:
174
+ logger.warning(
175
+ "It is strongly recommended to pass the `sampling_rate` argument to this function. "
176
+ "Failing to do so can result in silent errors that might be hard to debug."
177
+ )
178
+
179
+ is_batched = bool(
180
+ isinstance(raw_speech, (list, tuple))
181
+ and (isinstance(raw_speech[0], np.ndarray) or isinstance(raw_speech[0], (tuple, list)))
182
+ )
183
+ if is_batched:
184
+ raw_speech = [np.asarray([speech], dtype=np.float32).T for speech in raw_speech]
185
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
186
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
187
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
188
+ raw_speech = raw_speech.astype(np.float32)
189
+ # always return batch
190
+ if not is_batched:
191
+ raw_speech = [np.asarray([raw_speech]).T]
192
+
193
+ # Convert audio signals to log mel spectrograms, truncate by time axis
194
+ audio_features = [
195
+ self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
196
+ ]
197
+ if isinstance(audio_features[0], List):
198
+ audio_features = [np.asarray(feature, dtype=np.float32) for feature in audio_features]
199
+
200
+ # Create audio attention mask
201
+ max_patch_len = max(
202
+ [ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features]
203
+ ) # The maximum number of audio patches in a batch
204
+ if return_attention_mask:
205
+ audio_mask = [
206
+ (ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
207
+ + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
208
+ for feature in audio_features
209
+ ]
210
+ audio_mask = np.array(audio_mask).astype(np.float32)
211
+
212
+ # convert into correct format for padding
213
+ max_time_len = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch
214
+ padded_audio_features = np.ones([len(audio_features), 1, max_time_len, self.feature_size]).astype(np.float32)
215
+ padded_audio_features = padded_audio_features * self.padding_value
216
+ for i in range(len(audio_features)):
217
+ feature = audio_features[i]
218
+ padded_audio_features[i, :, : feature.shape[0], :] = feature
219
+
220
+ # return as BatchFeature
221
+ if return_attention_mask:
222
+ data = {"audio_values": padded_audio_features, "audio_mask": audio_mask}
223
+ else:
224
+ data = {"audio_values": padded_audio_features}
225
+
226
+ encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
227
+ return encoded_inputs
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/image_processing_tvlt.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Image processor class for TVLT."""
16
+ from typing import Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+
20
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
21
+ from ...image_transforms import (
22
+ center_crop,
23
+ get_resize_output_image_size,
24
+ normalize,
25
+ rescale,
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
+ is_valid_image,
36
+ to_numpy_array,
37
+ valid_images,
38
+ )
39
+ from ...utils import TensorType, logging
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ def make_batched(videos) -> List[List[ImageInput]]:
46
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)):
47
+ return videos
48
+
49
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
50
+ videos_dim = np.array(videos[0]).ndim
51
+ if videos_dim == 3:
52
+ return [videos]
53
+ elif videos_dim == 4:
54
+ return videos
55
+
56
+ elif is_valid_image(videos):
57
+ videos_dim = np.array(videos).ndim
58
+ if videos_dim == 3:
59
+ return [[videos]]
60
+ elif videos_dim == 4:
61
+ return [videos]
62
+ elif videos_dim == 5:
63
+ return videos
64
+
65
+ raise ValueError(f"Could not make batched video from {videos}")
66
+
67
+
68
+ class TvltImageProcessor(BaseImageProcessor):
69
+ r"""
70
+ Constructs a TVLT image processor.
71
+
72
+ This processor can be used to prepare either videos or images for the model by converting images to 1-frame videos.
73
+
74
+ Args:
75
+ do_resize (`bool`, *optional*, defaults to `True`):
76
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
77
+ `do_resize` parameter in the `preprocess` method.
78
+ size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
79
+ Size of the output image after resizing. The shortest edge of the image will be resized to
80
+ `size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overriden by
81
+ `size` in the `preprocess` method.
82
+ patch_size (`List[int]` *optional*, defaults to [16,16]):
83
+ The patch size of image patch embedding.
84
+ num_frames (`int` *optional*, defaults to 8):
85
+ The maximum number of video frames.
86
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
87
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
88
+ `preprocess` method.
89
+ do_center_crop (`bool`, *optional*, defaults to `True`):
90
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
91
+ parameter in the `preprocess` method.
92
+ crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
93
+ Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
94
+ `preprocess` method.
95
+ do_rescale (`bool`, *optional*, defaults to `True`):
96
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
97
+ parameter in the `preprocess` method.
98
+ rescale_factor (`int` or `float`, *optional*, defaults to 1/255):
99
+ Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
100
+ in the `preprocess` method.
101
+ do_normalize (`bool`, *optional*, defaults to `True`):
102
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
103
+ method.
104
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
105
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
106
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
107
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
108
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
109
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
110
+ """
111
+
112
+ model_input_names = [
113
+ "pixel_values",
114
+ "pixel_mask",
115
+ "pixel_values_mixed",
116
+ "pixel_mask_mixed",
117
+ ]
118
+
119
+ def __init__(
120
+ self,
121
+ do_resize: bool = True,
122
+ size: Dict[str, int] = None,
123
+ patch_size: List[int] = [16, 16],
124
+ num_frames: int = 8,
125
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
126
+ do_center_crop: bool = True,
127
+ crop_size: Dict[str, int] = None,
128
+ do_rescale: bool = True,
129
+ rescale_factor: Union[int, float] = 1 / 255,
130
+ do_normalize: bool = True,
131
+ image_mean: Optional[Union[float, List[float]]] = IMAGENET_STANDARD_MEAN,
132
+ image_std: Optional[Union[float, List[float]]] = IMAGENET_STANDARD_STD,
133
+ init_mask_generator=False,
134
+ **kwargs,
135
+ ) -> None:
136
+ super().__init__(**kwargs)
137
+ size = size if size is not None else {"shortest_edge": 224}
138
+ size = get_size_dict(size, default_to_square=False)
139
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
140
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
141
+
142
+ self.do_resize = do_resize
143
+ self.size = size
144
+ self.patch_size = patch_size
145
+ self.num_frames = num_frames
146
+ self.do_center_crop = do_center_crop
147
+ self.crop_size = crop_size
148
+ self.resample = resample
149
+ self.do_rescale = do_rescale
150
+ self.rescale_factor = rescale_factor
151
+ self.do_normalize = do_normalize
152
+ self.image_mean = image_mean
153
+ self.image_std = image_std
154
+
155
+ def resize(
156
+ self,
157
+ image: np.ndarray,
158
+ size: Dict[str, int],
159
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
160
+ data_format: Optional[Union[str, ChannelDimension]] = None,
161
+ **kwargs,
162
+ ) -> np.ndarray:
163
+ """
164
+ Resize an image.
165
+
166
+ Args:
167
+ image (`np.ndarray`):
168
+ Image to resize.
169
+ size (`Dict[str, int]`):
170
+ Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
171
+ have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
172
+ shortest edge of length `s` while keeping the aspect ratio of the original image.
173
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
174
+ Resampling filter to use when resiizing the image.
175
+ data_format (`str` or `ChannelDimension`, *optional*):
176
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
177
+ """
178
+ size = get_size_dict(size, default_to_square=False)
179
+ if "shortest_edge" in size:
180
+ output_size = get_resize_output_image_size(image, size["shortest_edge"], default_to_square=False)
181
+ elif "height" in size and "width" in size:
182
+ output_size = (size["height"], size["width"])
183
+ else:
184
+ raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
185
+ return resize(image, size=output_size, resample=resample, data_format=data_format, **kwargs)
186
+
187
+ def center_crop(
188
+ self,
189
+ image: np.ndarray,
190
+ size: Dict[str, int],
191
+ data_format: Optional[Union[str, ChannelDimension]] = None,
192
+ **kwargs,
193
+ ) -> np.ndarray:
194
+ """
195
+ Center crop an image to `(size["height"], size["width"])`. If the input size is smaller than `size` along any
196
+ edge, the image is padded with 0's and then center cropped.
197
+
198
+ Args:
199
+ image (`np.ndarray`):
200
+ Image to center crop.
201
+ size (`Dict[str, int]`):
202
+ Size of the output image.
203
+ data_format (`str` or `ChannelDimension`, *optional*):
204
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
205
+ """
206
+ size = get_size_dict(size)
207
+ if "height" not in size or "width" not in size:
208
+ raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}")
209
+ return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
210
+
211
+ def rescale(
212
+ self,
213
+ image: np.ndarray,
214
+ scale: Union[int, float],
215
+ data_format: Optional[Union[str, ChannelDimension]] = None,
216
+ **kwargs,
217
+ ):
218
+ """
219
+ Rescale an image by a scale factor. image = image * scale.
220
+
221
+ Args:
222
+ image (`np.ndarray`):
223
+ Image to rescale.
224
+ scale (`int` or `float`):
225
+ Scale to apply to the image.
226
+ data_format (`str` or `ChannelDimension`, *optional*):
227
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
228
+ """
229
+ return rescale(image, scale=scale, data_format=data_format, **kwargs)
230
+
231
+ # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.normalize
232
+ def normalize(
233
+ self,
234
+ image: np.ndarray,
235
+ mean: Union[float, List[float]],
236
+ std: Union[float, List[float]],
237
+ data_format: Optional[Union[str, ChannelDimension]] = None,
238
+ **kwargs,
239
+ ) -> np.ndarray:
240
+ """
241
+ Normalize an image. image = (image - image_mean) / image_std.
242
+
243
+ Args:
244
+ image (`np.ndarray`):
245
+ Image to normalize.
246
+ mean (`float` or `List[float]`):
247
+ Image mean to use for normalization.
248
+ std (`float` or `List[float]`):
249
+ Image standard deviation to use for normalization.
250
+ data_format (`str` or `ChannelDimension`, *optional*):
251
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
252
+ image is used. Can be one of:
253
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
254
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
255
+
256
+ Returns:
257
+ `np.ndarray`: The normalized image.
258
+ """
259
+ return normalize(image, mean=mean, std=std, data_format=data_format, **kwargs)
260
+
261
+ def _preprocess_image(
262
+ self,
263
+ image: ImageInput,
264
+ do_resize: bool = None,
265
+ size: Dict[str, int] = None,
266
+ resample: PILImageResampling = None,
267
+ do_center_crop: bool = None,
268
+ crop_size: Dict[str, int] = None,
269
+ do_rescale: bool = None,
270
+ rescale_factor: float = None,
271
+ do_normalize: bool = None,
272
+ image_mean: Optional[Union[float, List[float]]] = None,
273
+ image_std: Optional[Union[float, List[float]]] = None,
274
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
275
+ ) -> np.ndarray:
276
+ """Preprocesses a single image."""
277
+ if do_resize and size is None or resample is None:
278
+ raise ValueError("Size and resample must be specified if do_resize is True.")
279
+
280
+ if do_center_crop and crop_size is None:
281
+ raise ValueError("Crop size must be specified if do_center_crop is True.")
282
+
283
+ if do_rescale and rescale_factor is None:
284
+ raise ValueError("Rescale factor must be specified if do_rescale is True.")
285
+
286
+ if do_normalize and (image_mean is None or image_std is None):
287
+ raise ValueError("Image mean and std must be specified if do_normalize is True.")
288
+
289
+ # All transformations expect numpy arrays.
290
+ image = to_numpy_array(image)
291
+
292
+ if do_resize:
293
+ image = self.resize(image=image, size=size, resample=resample)
294
+
295
+ if do_center_crop:
296
+ image = self.center_crop(image, size=crop_size)
297
+
298
+ if do_rescale:
299
+ image = self.rescale(image=image, scale=rescale_factor)
300
+
301
+ if do_normalize:
302
+ image = self.normalize(image=image, mean=image_mean, std=image_std)
303
+ image = to_channel_dimension_format(image, data_format)
304
+ return image
305
+
306
+ def preprocess(
307
+ self,
308
+ videos: ImageInput,
309
+ do_resize: bool = None,
310
+ size: Dict[str, int] = None,
311
+ patch_size: List[int] = None,
312
+ num_frames: int = None,
313
+ resample: PILImageResampling = None,
314
+ do_center_crop: bool = None,
315
+ crop_size: Dict[str, int] = None,
316
+ do_rescale: bool = None,
317
+ rescale_factor: float = None,
318
+ do_normalize: bool = None,
319
+ image_mean: Optional[Union[float, List[float]]] = None,
320
+ image_std: Optional[Union[float, List[float]]] = None,
321
+ is_mixed: bool = False,
322
+ return_tensors: Optional[Union[str, TensorType]] = None,
323
+ data_format: ChannelDimension = ChannelDimension.FIRST,
324
+ **kwargs,
325
+ ) -> BatchFeature:
326
+ """
327
+ Preprocess an videos or image or batch of videos or images.
328
+
329
+ Args:
330
+ videos (`ImageInput`):
331
+ Images or videos to preprocess.
332
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
333
+ Whether to resize the image.
334
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
335
+ Size of the image after applying resize.
336
+ patch_size (`List[int]` *optional*, defaults to self.patch_size):
337
+ The patch size of image patch embedding.
338
+ num_frames (`int` *optional*, defaults to self.num_frames):
339
+ The maximum number of video frames.
340
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
341
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
342
+ has an effect if `do_resize` is set to `True`.
343
+ do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
344
+ Whether to centre crop the image.
345
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
346
+ Size of the image after applying the centre crop.
347
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
348
+ Whether to rescale the image values between [0 - 1].
349
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
350
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
351
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
352
+ Whether to normalize the image.
353
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
354
+ Image mean.
355
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
356
+ Image standard deviation.
357
+ is_mixed (`bool`, *optional*):
358
+ If the input video has negative samples.
359
+ return_tensors (`str` or `TensorType`, *optional*):
360
+ The type of tensors to return. Can be one of:
361
+ - Unset: Return a list of `np.ndarray`.
362
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
363
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
364
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
365
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
366
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
367
+ The channel dimension format for the output image. Can be one of:
368
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
369
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
370
+ - Unset: Use the inferred channel dimension format of the input image.
371
+
372
+ Returns:
373
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
374
+
375
+ - **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
376
+ width).
377
+
378
+ - **pixel_mask** -- Pixel masks to be fed to a model, of shape (batch_size, num_pixel_patches).
379
+
380
+ - **pixel_values_mixed** -- Pixel values with both postive or negative to be fed to a model, of shape
381
+ (batch_size, num_channels, height, width).
382
+
383
+ - **pixel_mask_mixed** -- Pixel masks with both postive or negative to be fed to a model, of shape
384
+ (batch_size, num_pixel_patches).
385
+ """
386
+ do_resize = do_resize if do_resize is not None else self.do_resize
387
+ resample = resample if resample is not None else self.resample
388
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
389
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
390
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
391
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
392
+ image_mean = image_mean if image_mean is not None else self.image_mean
393
+ image_std = image_std if image_std is not None else self.image_std
394
+
395
+ size = size if size is not None else self.size
396
+ size = get_size_dict(size, default_to_square=False)
397
+ crop_size = crop_size if crop_size is not None else self.crop_size
398
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
399
+ patch_size = patch_size if patch_size is not None else self.patch_size
400
+ num_frames = num_frames if patch_size is not None else self.num_frames
401
+
402
+ if not valid_images(videos):
403
+ raise ValueError(
404
+ "Invalid image or video type. Must be of type PIL.Image.Image, numpy.ndarray, "
405
+ "torch.Tensor, tf.Tensor or jax.ndarray."
406
+ )
407
+
408
+ videos = make_batched(videos)
409
+
410
+ # Check number of frames is fewer than maximum frames
411
+ for video in videos:
412
+ if len(video) > self.num_frames:
413
+ raise ValueError(
414
+ f"number of frames must not be greater than the maximum frames of the model {self.num_frames}."
415
+ )
416
+
417
+ max_num_frames = max([len(video) for video in videos])
418
+ num_patches_per_image = (size["shortest_edge"] // patch_size[0]) ** 2
419
+ video_masks = np.array(
420
+ [
421
+ len(video) * num_patches_per_image * [1] + (max_num_frames - len(video)) * num_patches_per_image * [0]
422
+ for video in videos
423
+ ]
424
+ )
425
+
426
+ videos = [
427
+ [
428
+ self._preprocess_image(
429
+ image=img,
430
+ do_resize=do_resize,
431
+ size=size,
432
+ resample=resample,
433
+ do_center_crop=do_center_crop,
434
+ crop_size=crop_size,
435
+ do_rescale=do_rescale,
436
+ rescale_factor=rescale_factor,
437
+ do_normalize=do_normalize,
438
+ image_mean=image_mean,
439
+ image_std=image_std,
440
+ data_format=data_format,
441
+ )
442
+ for img in video
443
+ ]
444
+ for video in videos
445
+ ]
446
+
447
+ # If videos contain both positive/negative, use mixed key for video-audio matching task
448
+ if is_mixed:
449
+ data = {"pixel_values_mixed": videos, "pixel_mask_mixed": video_masks}
450
+ else:
451
+ data = {"pixel_values": videos, "pixel_mask": video_masks}
452
+
453
+ return BatchFeature(data=data, tensor_type=return_tensors)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/modeling_tvlt.py ADDED
@@ -0,0 +1,1317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 MURGe-Lab 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 TVLT model."""
16
+
17
+
18
+ import collections.abc
19
+ import math
20
+ from copy import deepcopy
21
+ from dataclasses import dataclass
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from ...activations import ACT2FN
30
+ from ...modeling_outputs import BaseModelOutput, SequenceClassifierOutput
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
33
+ from ...utils import (
34
+ ModelOutput,
35
+ add_start_docstrings,
36
+ add_start_docstrings_to_model_forward,
37
+ logging,
38
+ replace_return_docstrings,
39
+ )
40
+ from .configuration_tvlt import TvltConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ _CONFIG_FOR_DOC = "TvltConfig"
46
+ _CHECKPOINT_FOR_DOC = "ZinengTang/tvlt-base"
47
+
48
+ TVLT_PRETRAINED_MODEL_ARCHIVE_LIST = [
49
+ "ZinengTang/tvlt-base",
50
+ # See all TVLT models at https://huggingface.co/ZinengTang/tvlt-base
51
+ ]
52
+
53
+
54
+ @dataclass
55
+ class TvltModelOutput(ModelOutput):
56
+ """
57
+ Class for TvltModel's outputs, with potential hidden states and attentions.
58
+
59
+ Args:
60
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
61
+ Sequence of hidden-states at the output of the last layer of the model.
62
+ last_pixel_hidden_state (`torch.FloatTensor` of shape `(batch_size, pixel_sequence_length, hidden_size)`):
63
+ Pixel sequence of hidden-states at the output of the last layer of the model.
64
+ last_audio_hidden_state (`torch.FloatTensor` of shape `(batch_size, audio_sequence_length, hidden_size)`):
65
+ Audio sequence of hidden-states at the output of the last layer of the model.
66
+ pixel_label_masks (`torch.FloatTensor` of shape `(batch_size, pixel_patch_length)`):
67
+ Tensor indicating which pixel patches are masked (1) and which are not (0).
68
+ audio_label_masks (`torch.FloatTensor` of shape `(batch_size, audio_patch_length)`):
69
+ Tensor indicating which audio patches are masked (1) and which are not (0).
70
+ pixel_ids_restore (`torch.LongTensor` of shape `(batch_size, pixel_patch_length)`):
71
+ Tensor containing the ids permutation of pixel masking.
72
+ audio_ids_restore (`torch.LongTensor` of shape `(batch_size, audio_patch_length)`):
73
+ Tensor containing the ids permutation of audio masking.
74
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
75
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
76
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
77
+ plus the initial embedding outputs.
78
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
79
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
80
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
81
+ the self-attention heads.
82
+ """
83
+
84
+ last_hidden_state: torch.FloatTensor = None
85
+ last_pixel_hidden_state: torch.FloatTensor = None
86
+ last_audio_hidden_state: torch.FloatTensor = None
87
+ pixel_label_masks: torch.LongTensor = None
88
+ audio_label_masks: torch.LongTensor = None
89
+ pixel_ids_restore: torch.LongTensor = None
90
+ audio_ids_restore: torch.LongTensor = None
91
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
92
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
93
+
94
+
95
+ @dataclass
96
+ class TvltDecoderOutput(ModelOutput):
97
+ """
98
+ Class for TvltDecoder's outputs, with potential hidden states and attentions.
99
+
100
+ Args:
101
+ logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
102
+ Pixel reconstruction logits.
103
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
104
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
105
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
106
+ plus the initial embedding outputs.
107
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
108
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
109
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
110
+ the self-attention heads.
111
+ """
112
+
113
+ logits: torch.FloatTensor = None
114
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
115
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
116
+
117
+
118
+ @dataclass
119
+ class TvltForPreTrainingOutput(ModelOutput):
120
+ """
121
+ Class for TvltForPreTraining's outputs, with potential hidden states and attentions.
122
+
123
+ Args:
124
+ loss (`torch.FloatTensor` of shape `(1,)`):
125
+ Pixel reconstruction loss.
126
+ matching_logits (`torch.FloatTensor` of shape `(batch_size, 1)`):
127
+ Matching objective logits.
128
+ pixel_logits (`torch.FloatTensor` of shape
129
+ `(batch_size, pixel_patch_length, image_patch_size ** 3 * pixel_num_channels)`): Pixel reconstruction
130
+ logits.
131
+ audio_logits (`torch.FloatTensor` of shape
132
+ `(batch_size, audio_patch_length, image_patch_size[0] * image_patch_size[1])`): Audio reconstruction
133
+ logits.
134
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
135
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
136
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
137
+ plus the initial embedding outputs.
138
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
139
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
140
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
141
+ the self-attention heads.
142
+ """
143
+
144
+ loss: Optional[torch.FloatTensor] = None
145
+ matching_logits: torch.FloatTensor = None
146
+ pixel_logits: torch.FloatTensor = None
147
+ audio_logits: torch.FloatTensor = None
148
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
149
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
150
+
151
+
152
+ def generate_pixel_mask_noise(pixel_values, pixel_mask=None, mask_ratio=0.75):
153
+ """Generate noise for audio masking."""
154
+
155
+ batch_size, seq_len = pixel_values.shape[:2]
156
+ noise = torch.rand((batch_size, seq_len), device=pixel_values.device) # noise in [0, 1]
157
+ len_keep = int(seq_len * (1 - mask_ratio))
158
+ return noise, len_keep
159
+
160
+
161
+ def generate_audio_mask_noise(audio_values, audio_mask=None, mask_ratio=0.75, mask_type="patch-level", freq_len=8):
162
+ """Generate noise for audio masking."""
163
+
164
+ batch_size, seq_len = audio_values.shape[:2]
165
+ if mask_type == "frame-level":
166
+ num_time_patches = seq_len // freq_len
167
+ noise = (
168
+ torch.rand(batch_size, num_time_patches, device=audio_values.device)
169
+ .unsqueeze(-1)
170
+ .repeat(1, 1, freq_len)
171
+ .view(batch_size, seq_len)
172
+ ) # noise in [0, 1]
173
+ elif mask_type == "patch-level":
174
+ noise = torch.rand(batch_size, seq_len, device=audio_values.device) # noise in [0, 1]
175
+ len_keep = int(seq_len * (1 - mask_ratio))
176
+ return noise, len_keep
177
+
178
+
179
+ def random_masking(sequence, noise, len_keep, attention_masks=None):
180
+ """
181
+ Perform random masking by per-sample shuffling on frame-level. Per-sample shuffling is done by argsort random
182
+ noise. sequence: [batch_size, seq_len, hidden_dim], sequence
183
+ """
184
+
185
+ batch_size, seq_len, hidden_dim = sequence.shape
186
+
187
+ # sort noise for each sample
188
+ ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove
189
+ ids_restore = torch.argsort(ids_shuffle, dim=1)
190
+
191
+ # keep the first subset
192
+ ids_keep = ids_shuffle[:, :len_keep]
193
+ sequence_masked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, hidden_dim))
194
+
195
+ # generate the binary mask: 0 is keep, 1 is remove
196
+ label_masks = torch.ones([batch_size, seq_len], device=sequence.device)
197
+ label_masks[:, :len_keep] = 0
198
+ # unshuffle to get the binary mask
199
+ label_masks = torch.gather(label_masks, dim=1, index=ids_restore)
200
+
201
+ if attention_masks is not None:
202
+ label_masks *= attention_masks
203
+ attention_masks = torch.gather(attention_masks, dim=1, index=ids_keep)
204
+
205
+ return sequence_masked, attention_masks, label_masks, ids_restore
206
+
207
+
208
+ class TvltPixelEmbeddings(nn.Module):
209
+ """Construct the patch and position embeddings."""
210
+
211
+ def __init__(self, config):
212
+ super().__init__()
213
+
214
+ self.patch_embeddings = TvltPixelPatchEmbeddings(config)
215
+ self.num_patches_per_image = self.patch_embeddings.num_patches_per_image
216
+
217
+ self.type_embed_v = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
218
+ self.temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, config.hidden_size))
219
+ self.pos_embed_v = nn.Parameter(torch.zeros(1, self.num_patches_per_image, config.hidden_size))
220
+
221
+ self.config = config
222
+
223
+ def forward(self, pixel_values, attention_masks=None):
224
+ # create patch embeddings
225
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
226
+
227
+ embeddings = self.patch_embeddings(pixel_values)
228
+ embeddings += self.pos_embed_v.repeat(1, num_frames, 1)
229
+ embeddings += torch.repeat_interleave(self.temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1)
230
+ embeddings += self.type_embed_v
231
+
232
+ return embeddings, attention_masks
233
+
234
+
235
+ class TvltAudioEmbeddings(nn.Module):
236
+ """Construct the patch and position embeddings."""
237
+
238
+ def __init__(self, config):
239
+ super().__init__()
240
+
241
+ self.patch_embeddings = TvltAudioPatchEmbeddings(config)
242
+ self.num_patches = self.patch_embeddings.num_patches
243
+
244
+ self.type_embed_a = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
245
+ self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
246
+ self.pos_embed_a = nn.Parameter(torch.zeros(1, self.num_patches // self.num_freq_patches, config.hidden_size))
247
+ self.freq_embed = nn.Parameter(torch.zeros(1, self.num_freq_patches, config.hidden_size))
248
+
249
+ self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
250
+ self.config = config
251
+
252
+ def forward(self, audio_values, attention_masks=None):
253
+ # create patch embeddings
254
+ embeddings = self.patch_embeddings(audio_values)
255
+
256
+ num_time_patches = embeddings.size(1) // self.num_freq_patches
257
+ embeddings += self.freq_embed.repeat(1, num_time_patches, 1)
258
+ embeddings += torch.repeat_interleave(self.pos_embed_a[:, :num_time_patches], self.num_freq_patches, dim=1)
259
+ embeddings += self.type_embed_a
260
+
261
+ return embeddings, attention_masks
262
+
263
+
264
+ class TvltPixelPatchEmbeddings(nn.Module):
265
+ """
266
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
267
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
268
+ Transformer.
269
+ """
270
+
271
+ def __init__(self, config):
272
+ super().__init__()
273
+ image_size, patch_size = config.image_size, config.image_patch_size
274
+ num_channels, hidden_size = config.num_image_channels, config.hidden_size
275
+
276
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
277
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
278
+ num_patches_per_image = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
279
+ self.image_size = image_size
280
+ self.patch_size = patch_size
281
+ self.num_channels = num_channels
282
+ self.num_patches_per_image = num_patches_per_image
283
+ self.hidden_size = hidden_size
284
+
285
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
286
+
287
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
288
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
289
+ if num_channels != self.num_channels:
290
+ raise ValueError(
291
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
292
+ )
293
+ if height != self.image_size[0] or width != self.image_size[1]:
294
+ raise ValueError(
295
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
296
+ )
297
+
298
+ pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
299
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
300
+ embeddings = embeddings.reshape(batch_size, num_frames * self.num_patches_per_image, self.hidden_size)
301
+
302
+ return embeddings
303
+
304
+
305
+ class TvltAudioPatchEmbeddings(nn.Module):
306
+ """
307
+ This class turns `audio_values` of shape `(batch_size, num_channels, height, width)` into the initial
308
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
309
+ Transformer.
310
+ """
311
+
312
+ def __init__(self, config):
313
+ super().__init__()
314
+ spectrogram_length, frequency_length, patch_size = (
315
+ config.spectrogram_length,
316
+ config.frequency_length,
317
+ config.audio_patch_size,
318
+ )
319
+ num_channels, hidden_size = config.num_audio_channels, config.hidden_size
320
+
321
+ spectrogram_size = (spectrogram_length, frequency_length)
322
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
323
+ num_patches = (spectrogram_size[1] // patch_size[1]) * (spectrogram_size[0] // patch_size[0])
324
+ patch_shape = (spectrogram_size[0] // patch_size[0], spectrogram_size[1] // patch_size[1])
325
+ self.spectrogram_size = spectrogram_size
326
+ self.patch_size = patch_size
327
+ self.num_channels = num_channels
328
+ self.num_patches = num_patches
329
+ self.patch_shape = patch_shape
330
+
331
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
332
+
333
+ def forward(self, audio_values: torch.Tensor) -> torch.Tensor:
334
+ batch_size, num_channels, height, width = audio_values.shape
335
+ if num_channels != self.num_channels:
336
+ raise ValueError(
337
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
338
+ )
339
+ if height > self.spectrogram_size[0] or width != self.spectrogram_size[1]:
340
+ raise ValueError(
341
+ f"Input audio size ({height}*{width}) doesn't match model"
342
+ f" ({self.spectrogram_size[0]}*{self.spectrogram_size[1]})."
343
+ )
344
+ embeddings = self.projection(audio_values).flatten(2).transpose(1, 2)
345
+
346
+ return embeddings
347
+
348
+
349
+ # Copied from transformers.models.vilt.modeling_vilt.ViltSelfAttention with Vilt->Tvlt
350
+ class TvltSelfAttention(nn.Module):
351
+ def __init__(self, config):
352
+ super().__init__()
353
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
354
+ raise ValueError(
355
+ f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
356
+ f"heads {config.num_attention_heads}."
357
+ )
358
+
359
+ self.num_attention_heads = config.num_attention_heads
360
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
361
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
362
+
363
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
364
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
365
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
366
+
367
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
368
+
369
+ def transpose_for_scores(self, x):
370
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
371
+ x = x.view(*new_x_shape)
372
+ return x.permute(0, 2, 1, 3)
373
+
374
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
375
+ mixed_query_layer = self.query(hidden_states)
376
+
377
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
378
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
379
+ query_layer = self.transpose_for_scores(mixed_query_layer)
380
+
381
+ # Take the dot product between "query" and "key" to get the raw attention scores.
382
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
383
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
384
+ if attention_mask is not None:
385
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
386
+ attention_scores = attention_scores + attention_mask
387
+
388
+ # Normalize the attention scores to probabilities.
389
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
390
+
391
+ # This is actually dropping out entire tokens to attend to, which might
392
+ # seem a bit unusual, but is taken from the original Transformer paper.
393
+ attention_probs = self.dropout(attention_probs)
394
+
395
+ # Mask heads if we want to
396
+ if head_mask is not None:
397
+ attention_probs = attention_probs * head_mask
398
+
399
+ context_layer = torch.matmul(attention_probs, value_layer)
400
+
401
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
402
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
403
+ context_layer = context_layer.view(*new_context_layer_shape)
404
+
405
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
406
+
407
+ return outputs
408
+
409
+
410
+ # Copied from transformers.models.vilt.modeling_vilt.ViltSelfOutput with Vilt->Tvlt
411
+ class TvltSelfOutput(nn.Module):
412
+ """
413
+ The residual connection is defined in TvltLayer instead of here (as is the case with other models), due to the
414
+ layernorm applied before each block.
415
+ """
416
+
417
+ def __init__(self, config: TvltConfig) -> None:
418
+ super().__init__()
419
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
420
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
421
+
422
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
423
+ hidden_states = self.dense(hidden_states)
424
+ hidden_states = self.dropout(hidden_states)
425
+
426
+ return hidden_states
427
+
428
+
429
+ # Copied from transformers.models.vilt.modeling_vilt.ViltAttention with Vilt->Tvlt
430
+ class TvltAttention(nn.Module):
431
+ def __init__(self, config):
432
+ super().__init__()
433
+ self.attention = TvltSelfAttention(config)
434
+ self.output = TvltSelfOutput(config)
435
+ self.pruned_heads = set()
436
+
437
+ def prune_heads(self, heads):
438
+ if len(heads) == 0:
439
+ return
440
+ heads, index = find_pruneable_heads_and_indices(
441
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
442
+ )
443
+
444
+ # Prune linear layers
445
+ self.attention.query = prune_linear_layer(self.attention.query, index)
446
+ self.attention.key = prune_linear_layer(self.attention.key, index)
447
+ self.attention.value = prune_linear_layer(self.attention.value, index)
448
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
449
+
450
+ # Update hyper params and store pruned heads
451
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
452
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
453
+ self.pruned_heads = self.pruned_heads.union(heads)
454
+
455
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
456
+ self_outputs = self.attention(hidden_states, attention_mask, head_mask, output_attentions)
457
+
458
+ attention_output = self.output(self_outputs[0], hidden_states)
459
+
460
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
461
+ return outputs
462
+
463
+
464
+ # Copied from transformers.models.vilt.modeling_vilt.ViltIntermediate with Vilt->Tvlt
465
+ class TvltIntermediate(nn.Module):
466
+ def __init__(self, config: TvltConfig) -> None:
467
+ super().__init__()
468
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
469
+ if isinstance(config.hidden_act, str):
470
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
471
+ else:
472
+ self.intermediate_act_fn = config.hidden_act
473
+
474
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
475
+ hidden_states = self.dense(hidden_states)
476
+ hidden_states = self.intermediate_act_fn(hidden_states)
477
+
478
+ return hidden_states
479
+
480
+
481
+ # Copied from transformers.models.vilt.modeling_vilt.ViltOutput with Vilt->Tvlt
482
+ class TvltOutput(nn.Module):
483
+ def __init__(self, config: TvltConfig) -> None:
484
+ super().__init__()
485
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
486
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
487
+
488
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
489
+ hidden_states = self.dense(hidden_states)
490
+ hidden_states = self.dropout(hidden_states)
491
+
492
+ hidden_states = hidden_states + input_tensor
493
+
494
+ return hidden_states
495
+
496
+
497
+ # Copied from transformers.models.vilt.modeling_vilt.ViltLayer with Vilt->Tvlt
498
+ class TvltLayer(nn.Module):
499
+ """This corresponds to the Block class in the timm implementation."""
500
+
501
+ def __init__(self, config):
502
+ super().__init__()
503
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
504
+ self.seq_len_dim = 1
505
+ self.attention = TvltAttention(config)
506
+ self.intermediate = TvltIntermediate(config)
507
+ self.output = TvltOutput(config)
508
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
509
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
510
+
511
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
512
+ self_attention_outputs = self.attention(
513
+ self.layernorm_before(hidden_states), # in ViLT, layernorm is applied before self-attention
514
+ attention_mask,
515
+ head_mask,
516
+ output_attentions=output_attentions,
517
+ )
518
+ attention_output = self_attention_outputs[0]
519
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
520
+
521
+ # first residual connection
522
+ hidden_states = attention_output + hidden_states.to(attention_output.device)
523
+
524
+ # in ViLT, layernorm is also applied after self-attention
525
+ layer_output = self.layernorm_after(hidden_states)
526
+ layer_output = self.intermediate(layer_output)
527
+
528
+ # second residual connection is done here
529
+ layer_output = self.output(layer_output, hidden_states)
530
+
531
+ outputs = (layer_output,) + outputs
532
+
533
+ return outputs
534
+
535
+
536
+ # Copied from transformers.models.vilt.modeling_vilt.ViltEncoder with Vilt->Tvlt
537
+ class TvltEncoder(nn.Module):
538
+ def __init__(self, config):
539
+ super().__init__()
540
+ self.config = config
541
+ self.layer = nn.ModuleList([TvltLayer(config) for _ in range(config.num_hidden_layers)])
542
+ self.gradient_checkpointing = False
543
+
544
+ def forward(
545
+ self,
546
+ hidden_states,
547
+ attention_mask=None,
548
+ head_mask=None,
549
+ output_attentions=False,
550
+ output_hidden_states=False,
551
+ return_dict=True,
552
+ ):
553
+ all_hidden_states = () if output_hidden_states else None
554
+ all_self_attentions = () if output_attentions else None
555
+
556
+ for i, layer_module in enumerate(self.layer):
557
+ if output_hidden_states:
558
+ all_hidden_states = all_hidden_states + (hidden_states,)
559
+
560
+ layer_head_mask = head_mask[i] if head_mask is not None else None
561
+
562
+ if self.gradient_checkpointing and self.training:
563
+
564
+ def create_custom_forward(module):
565
+ def custom_forward(*inputs):
566
+ return module(*inputs, output_attentions)
567
+
568
+ return custom_forward
569
+
570
+ layer_outputs = torch.utils.checkpoint.checkpoint(
571
+ create_custom_forward(layer_module),
572
+ hidden_states,
573
+ attention_mask,
574
+ layer_head_mask,
575
+ )
576
+ else:
577
+ layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
578
+
579
+ hidden_states = layer_outputs[0]
580
+
581
+ if output_attentions:
582
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
583
+
584
+ if output_hidden_states:
585
+ all_hidden_states = all_hidden_states + (hidden_states,)
586
+
587
+ if not return_dict:
588
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
589
+ return BaseModelOutput(
590
+ last_hidden_state=hidden_states,
591
+ hidden_states=all_hidden_states,
592
+ attentions=all_self_attentions,
593
+ )
594
+
595
+
596
+ class TvltPreTrainedModel(PreTrainedModel):
597
+ """
598
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
599
+ models.
600
+ """
601
+
602
+ config_class = TvltConfig
603
+ base_model_prefix = "tvlt"
604
+ main_input_name = "pixel_values"
605
+ supports_gradient_checkpointing = True
606
+
607
+ def _init_weights(self, module):
608
+ """Initialize the weights"""
609
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
610
+ # Slightly different from the TF version which uses truncated_normal for initialization
611
+ # cf https://github.com/pytorch/pytorch/pull/5617
612
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
613
+ if module.bias is not None:
614
+ module.bias.data.zero_()
615
+ elif isinstance(module, nn.LayerNorm):
616
+ module.bias.data.zero_()
617
+ module.weight.data.fill_(1.0)
618
+
619
+ def _set_gradient_checkpointing(self, module, value=False):
620
+ if isinstance(module, TvltEncoder):
621
+ module.gradient_checkpointing = value
622
+
623
+
624
+ TVLT_START_DOCSTRING = r"""
625
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
626
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
627
+ behavior.
628
+
629
+ Parameters:
630
+ config ([`TvltConfig`]): Model configuration class with all the parameters of the model.
631
+ Initializing with a config file does not load the weights associated with the model, only the
632
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
633
+ """
634
+
635
+ TVLT_INPUTS_DOCSTRING = r"""
636
+ Args:
637
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
638
+ Pixel values. Pixel values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
639
+ details.
640
+
641
+ audio_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
642
+ Audio values. Audio values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
643
+ details.
644
+
645
+ pixel_mask (`torch.FloatTensor` of shape `(batch_size, num_pixel_patches)`):
646
+ Pixel masks. Pixel masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
647
+ details.
648
+
649
+ audio_mask (`torch.FloatTensor` of shape `(batch_size, num_audio_patches)`):
650
+ Audio masks. Audio masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
651
+ details.
652
+
653
+ pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
654
+ Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Pixel values mixed can
655
+ be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
656
+
657
+ pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
658
+ Pixel masks of pixel_values_mixed. Pixel masks mixed can be obtained using [`TvltProcessor`]. See
659
+ [`TvltProcessor.__call__`] for details.
660
+
661
+ mask_pixel (`bool`, *optional*):
662
+ Whether to mask pixel for MAE tasks. Only set to True in TvltForPreTraining.
663
+
664
+ mask_audio (`bool`, *optional*):
665
+ Whether to mask audio for MAE tasks. Only set to True in TvltForPreTraining.
666
+
667
+ output_attentions (`bool`, *optional*):
668
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
669
+ tensors for more detail.
670
+
671
+ output_hidden_states (`bool`, *optional*):
672
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
673
+ more detail.
674
+
675
+ return_dict (`bool`, *optional*):
676
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
677
+ """
678
+
679
+
680
+ @add_start_docstrings(
681
+ "The bare TVLT Model transformer outputting raw hidden-states without any specific head on top.",
682
+ TVLT_START_DOCSTRING,
683
+ )
684
+ class TvltModel(TvltPreTrainedModel):
685
+ def __init__(self, config):
686
+ super().__init__(config)
687
+ self.config = config
688
+
689
+ self.pixel_embeddings = TvltPixelEmbeddings(config)
690
+ self.audio_embeddings = TvltAudioEmbeddings(config)
691
+ self.encoder = TvltEncoder(config)
692
+
693
+ self.cls_embedding = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
694
+
695
+ if config.use_mean_pooling:
696
+ self.layernorm = None
697
+ else:
698
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
699
+
700
+ # Initialize weights and apply final processing
701
+ self.post_init()
702
+
703
+ def get_input_embeddings(self):
704
+ return self.pixel_embeddings.patch_embeddings, self.audio_embeddings.patch_embeddings
705
+
706
+ def _prune_heads(self, heads_to_prune):
707
+ """
708
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
709
+ class PreTrainedModel
710
+ """
711
+ for layer, heads in heads_to_prune.items():
712
+ self.encoder.layer[layer].attention.prune_heads(heads)
713
+
714
+ @add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
715
+ @replace_return_docstrings(output_type=TvltModelOutput, config_class=_CONFIG_FOR_DOC)
716
+ def forward(
717
+ self,
718
+ pixel_values,
719
+ audio_values,
720
+ pixel_mask=None,
721
+ audio_mask=None,
722
+ mask_pixel=False,
723
+ mask_audio=False,
724
+ output_attentions=None,
725
+ output_hidden_states=None,
726
+ return_dict=None,
727
+ ) -> Union[tuple, TvltModelOutput]:
728
+ r"""
729
+ Returns:
730
+
731
+ Examples:
732
+
733
+ ```python
734
+ >>> from transformers import TvltProcessor, TvltModel
735
+ >>> import numpy as np
736
+ >>> import torch
737
+
738
+ >>> num_frames = 8
739
+ >>> images = list(np.random.randn(num_frames, 3, 224, 224))
740
+ >>> audio = list(np.random.randn(10000))
741
+
742
+ >>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
743
+ >>> model = TvltModel.from_pretrained("ZinengTang/tvlt-base")
744
+
745
+ >>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
746
+
747
+ >>> outputs = model(**input_dict)
748
+ >>> loss = outputs.loss
749
+ ```"""
750
+
751
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
752
+ output_hidden_states = (
753
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
754
+ )
755
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
756
+
757
+ pixel_embedding_output, pixel_mask = self.pixel_embeddings(pixel_values, pixel_mask)
758
+
759
+ audio_embedding_output, audio_mask = self.audio_embeddings(audio_values, audio_mask)
760
+
761
+ # Mask pixel if mask_pixel is True
762
+ pixel_label_masks = None
763
+ pixel_ids_restore = None
764
+ if mask_pixel:
765
+ pixel_mask_noise, pixel_len_keep = generate_pixel_mask_noise(
766
+ pixel_embedding_output, pixel_mask=pixel_mask, mask_ratio=self.config.pixel_mask_ratio
767
+ )
768
+ pixel_embedding_output, pixel_mask, pixel_label_masks, pixel_ids_restore = random_masking(
769
+ pixel_embedding_output,
770
+ pixel_mask_noise,
771
+ pixel_len_keep,
772
+ attention_masks=pixel_mask,
773
+ )
774
+
775
+ # Mask audio if mask_audio is True
776
+ audio_label_masks = None
777
+ audio_ids_restore = None
778
+ if mask_audio:
779
+ num_freq_patches = self.config.frequency_length // self.config.audio_patch_size[1]
780
+ audio_mask_noise, audio_len_keep = generate_audio_mask_noise(
781
+ audio_embedding_output,
782
+ audio_mask=audio_mask,
783
+ mask_ratio=self.config.audio_mask_ratio,
784
+ mask_type=self.config.audio_mask_type,
785
+ freq_len=num_freq_patches,
786
+ )
787
+ audio_embedding_output, audio_mask, audio_label_masks, audio_ids_restore = random_masking(
788
+ audio_embedding_output,
789
+ audio_mask_noise,
790
+ audio_len_keep,
791
+ attention_masks=audio_mask,
792
+ )
793
+
794
+ # Prepare for encoder inputs and attention masks
795
+ batch_size = pixel_values.size(0)
796
+ embedding_output = torch.cat(
797
+ [self.cls_embedding.repeat(batch_size, 1, 1), pixel_embedding_output, audio_embedding_output], 1
798
+ )
799
+ masked_pixel_len = pixel_embedding_output.size(1)
800
+
801
+ attention_mask = None
802
+ if pixel_mask is not None and audio_mask is not None:
803
+ attention_mask = torch.cat([pixel_mask[:, :1], pixel_mask, audio_mask], 1)
804
+
805
+ input_shape = embedding_output.size()
806
+ extended_attention_mask = None
807
+ if attention_mask is not None:
808
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
809
+
810
+ encoder_outputs = self.encoder(
811
+ embedding_output,
812
+ attention_mask=extended_attention_mask,
813
+ output_attentions=output_attentions,
814
+ output_hidden_states=output_hidden_states,
815
+ return_dict=return_dict,
816
+ )
817
+ sequence_output = encoder_outputs[0]
818
+ if self.layernorm is not None:
819
+ sequence_output = self.layernorm(sequence_output)
820
+
821
+ pixel_sequence_output = sequence_output[:, 1 : 1 + masked_pixel_len]
822
+ audio_sequence_output = sequence_output[:, 1 + masked_pixel_len :]
823
+ if not return_dict:
824
+ return (
825
+ sequence_output,
826
+ pixel_sequence_output,
827
+ audio_sequence_output,
828
+ pixel_label_masks,
829
+ audio_label_masks,
830
+ pixel_ids_restore,
831
+ audio_ids_restore,
832
+ ) + encoder_outputs[1:]
833
+
834
+ return TvltModelOutput(
835
+ last_hidden_state=sequence_output,
836
+ last_pixel_hidden_state=pixel_sequence_output,
837
+ last_audio_hidden_state=audio_sequence_output,
838
+ pixel_label_masks=pixel_label_masks,
839
+ audio_label_masks=audio_label_masks,
840
+ pixel_ids_restore=pixel_ids_restore,
841
+ audio_ids_restore=audio_ids_restore,
842
+ hidden_states=encoder_outputs.hidden_states,
843
+ attentions=encoder_outputs.attentions,
844
+ )
845
+
846
+
847
+ class TvltDecoder(nn.Module):
848
+ def __init__(self, config):
849
+ super().__init__()
850
+
851
+ decoder_config = deepcopy(config)
852
+ decoder_config.hidden_size = config.decoder_hidden_size
853
+ decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
854
+ decoder_config.num_attention_heads = config.decoder_num_attention_heads
855
+ decoder_config.intermediate_size = config.decoder_intermediate_size
856
+ self.decoder_layers = nn.ModuleList(
857
+ [TvltLayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
858
+ )
859
+
860
+ self.layernorm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
861
+
862
+ self.gradient_checkpointing = False
863
+ self.config = config
864
+
865
+ def forward(
866
+ self,
867
+ hidden_states,
868
+ output_attentions=False,
869
+ output_hidden_states=False,
870
+ return_dict=True,
871
+ ):
872
+ # apply Transformer layers (blocks)
873
+ all_hidden_states = () if output_hidden_states else None
874
+ all_self_attentions = () if output_attentions else None
875
+ for i, layer_module in enumerate(self.decoder_layers):
876
+ if output_hidden_states:
877
+ all_hidden_states = all_hidden_states + (hidden_states,)
878
+
879
+ if self.gradient_checkpointing and self.training:
880
+
881
+ def create_custom_forward(module):
882
+ def custom_forward(*inputs):
883
+ return module(*inputs, output_attentions)
884
+
885
+ return custom_forward
886
+
887
+ layer_outputs = torch.utils.checkpoint.checkpoint(
888
+ create_custom_forward(layer_module),
889
+ hidden_states,
890
+ None,
891
+ )
892
+ else:
893
+ layer_outputs = layer_module(hidden_states, output_attentions=output_attentions)
894
+
895
+ hidden_states = layer_outputs[0]
896
+
897
+ if output_attentions:
898
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
899
+
900
+ if output_hidden_states:
901
+ all_hidden_states = all_hidden_states + (hidden_states,)
902
+
903
+ # predictor projection
904
+ logits = self.layernorm(hidden_states)
905
+
906
+ if not return_dict:
907
+ return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
908
+ return TvltDecoderOutput(logits=logits, hidden_states=all_hidden_states, attentions=all_self_attentions)
909
+
910
+
911
+ @add_start_docstrings(
912
+ "The TVLT Model transformer with the decoder on top for self-supervised pre-training.",
913
+ TVLT_START_DOCSTRING,
914
+ )
915
+ class TvltForPreTraining(TvltPreTrainedModel):
916
+ def __init__(self, config):
917
+ super().__init__(config)
918
+ self.config = config
919
+
920
+ self.task_matching = config.task_matching
921
+ self.task_mae = config.task_mae
922
+ if not (self.task_matching or self.task_mae):
923
+ raise ValueError("Must set at least one of matching task and MAE task to true")
924
+
925
+ self.tvlt = TvltModel(config)
926
+
927
+ if self.task_matching:
928
+ self.matching_head = TvltMatchingHead(config)
929
+
930
+ if self.task_mae:
931
+ self.encoder_to_decoder = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
932
+
933
+ self.pixel_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
934
+ self.audio_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
935
+
936
+ self.decoder = TvltDecoder(config)
937
+
938
+ decoder_hidden_size = config.decoder_hidden_size
939
+
940
+ num_frames = config.num_frames
941
+ num_patches_per_image = self.tvlt.pixel_embeddings.num_patches_per_image
942
+ self.decoder_pixel_pos_embed = nn.Parameter(torch.zeros(1, num_patches_per_image, decoder_hidden_size))
943
+ self.decoder_temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, decoder_hidden_size))
944
+ self.decoder_pixel_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
945
+
946
+ num_audio_patches = self.tvlt.audio_embeddings.num_patches
947
+ num_freq_patches = config.frequency_length // config.audio_patch_size[1]
948
+ self.decoder_audio_pos_embed = nn.Parameter(
949
+ torch.zeros(1, num_audio_patches // num_freq_patches, decoder_hidden_size)
950
+ )
951
+ self.decoder_freq_embed = nn.Parameter(torch.zeros(1, num_freq_patches, decoder_hidden_size))
952
+ self.decoder_audio_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
953
+
954
+ pixel_mae_output_dim = self.config.image_patch_size[0] ** 2 * self.config.num_image_channels
955
+ self.pixel_mae_head = TvltMAEHead(config, pixel_mae_output_dim)
956
+ audio_mae_output_dim = (
957
+ self.config.audio_patch_size[0] * self.config.audio_patch_size[1] * self.config.num_audio_channels
958
+ )
959
+ self.audio_mae_head = TvltMAEHead(config, audio_mae_output_dim)
960
+
961
+ self.num_frames = num_frames
962
+ self.num_patches_per_image = num_patches_per_image
963
+ self.num_freq_patches = num_freq_patches
964
+ self.image_patch_size = config.image_patch_size
965
+ self.audio_patch_size = config.audio_patch_size
966
+
967
+ # Initialize weights and apply final processing
968
+ self.post_init()
969
+
970
+ def patchify_pixel(self, pixel_values):
971
+ """
972
+ pixel_values: [batch_size, num_frames, 3, height, width]
973
+ """
974
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
975
+ num_patches_height = pixel_values.shape[3] // self.image_patch_size[0]
976
+ num_patches_width = pixel_values.shape[4] // self.image_patch_size[1]
977
+ patchified_pixel_values = pixel_values.reshape(
978
+ shape=(
979
+ batch_size,
980
+ num_frames,
981
+ num_channels,
982
+ num_patches_height,
983
+ self.image_patch_size[0],
984
+ num_patches_width,
985
+ self.image_patch_size[1],
986
+ )
987
+ )
988
+ patchified_pixel_values = torch.einsum("ntchpwq->nthwpqc", patchified_pixel_values)
989
+ patchified_pixel_values = patchified_pixel_values.reshape(
990
+ shape=(
991
+ batch_size,
992
+ num_patches_height * num_patches_width * num_frames,
993
+ self.image_patch_size[0] * self.image_patch_size[1] * num_channels,
994
+ )
995
+ )
996
+ return patchified_pixel_values
997
+
998
+ def patchify_audio(self, audio_values):
999
+ """
1000
+ audio_values: [batch_size, 1, height, width]
1001
+ """
1002
+ batch_size, num_channels, height, width = audio_values.shape
1003
+ num_patches_height = height // self.audio_patch_size[0]
1004
+ num_patches_width = width // self.audio_patch_size[1]
1005
+ patchified_audio_values = audio_values.reshape(
1006
+ shape=(
1007
+ batch_size,
1008
+ num_channels,
1009
+ num_patches_height,
1010
+ self.audio_patch_size[0],
1011
+ num_patches_width,
1012
+ self.audio_patch_size[1],
1013
+ )
1014
+ )
1015
+ patchified_audio_values = torch.einsum("nchpwq->nhwpqc", patchified_audio_values)
1016
+ patchified_audio_values = patchified_audio_values.reshape(
1017
+ shape=(
1018
+ batch_size,
1019
+ num_patches_height * num_patches_width,
1020
+ self.audio_patch_size[0] * self.audio_patch_size[1] * num_channels,
1021
+ )
1022
+ )
1023
+ return patchified_audio_values
1024
+
1025
+ def pixel_mae_loss(self, pixel_values, pixel_predictions, mask):
1026
+ patchified_pixel_values = self.patchify_pixel(pixel_values)
1027
+ loss = (pixel_predictions - patchified_pixel_values) ** 2
1028
+ loss = loss.mean(dim=-1) # [batch_size, pixel_pixel_length], mean loss per patch
1029
+ loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
1030
+ return loss
1031
+
1032
+ def audio_mae_loss(self, audio_values, audio_predictions, mask):
1033
+ patchified_audio_values = self.patchify_audio(audio_values)
1034
+ loss = (audio_predictions - patchified_audio_values) ** 2
1035
+ loss = loss.mean(dim=-1) # [batch_size, audio_pixel_length], mean loss per patch
1036
+ loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
1037
+ return loss
1038
+
1039
+ def concatenate_mask(self, mask_token, sequence, ids_restore):
1040
+ batch_size, seq_length, dim = sequence.shape
1041
+ mask_tokens = mask_token.repeat(batch_size, ids_restore.shape[1] - seq_length, 1)
1042
+ padded_sequence = torch.cat([sequence, mask_tokens], dim=1)
1043
+ padded_sequence = torch.gather(
1044
+ padded_sequence, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, dim)
1045
+ ) # unshuffle
1046
+ return padded_sequence
1047
+
1048
+ @add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
1049
+ @replace_return_docstrings(output_type=TvltForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1050
+ def forward(
1051
+ self,
1052
+ pixel_values,
1053
+ audio_values,
1054
+ pixel_mask=None,
1055
+ audio_mask=None,
1056
+ labels=None,
1057
+ pixel_values_mixed=None,
1058
+ pixel_mask_mixed=None,
1059
+ output_attentions=None,
1060
+ output_hidden_states=None,
1061
+ return_dict=None,
1062
+ ) -> Union[tuple, TvltForPreTrainingOutput]:
1063
+ r"""
1064
+ pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
1065
+ Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Audio values can be
1066
+ obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
1067
+
1068
+ pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1069
+ Pixel masks of pixel_values_mixed. Pixel values mixed can be obtained using [`TvltProcessor`]. See
1070
+ [`TvltProcessor.__call__`] for details.
1071
+
1072
+ labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
1073
+ Labels for computing the vision audio matching loss. Indices should be in `[0, 1]`. num_labels has to be 1.
1074
+
1075
+ Return:
1076
+
1077
+ Examples:
1078
+
1079
+ ```python
1080
+ >>> from transformers import TvltProcessor, TvltForPreTraining
1081
+ >>> import numpy as np
1082
+ >>> import torch
1083
+
1084
+ >>> num_frames = 8
1085
+ >>> images = list(np.random.randn(num_frames, 3, 224, 224))
1086
+ >>> images_mixed = list(np.random.randn(num_frames, 3, 224, 224))
1087
+ >>> audio = list(np.random.randn(10000))
1088
+ >>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
1089
+ >>> model = TvltForPreTraining.from_pretrained("ZinengTang/tvlt-base")
1090
+ >>> input_dict = processor(
1091
+ ... images, audio, images_mixed, sampling_rate=44100, mask_pixel=True, mask_audio=True, return_tensors="pt"
1092
+ ... )
1093
+
1094
+ >>> outputs = model(**input_dict)
1095
+ >>> loss = outputs.loss
1096
+ ```"""
1097
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1098
+ total_loss = 0.0
1099
+
1100
+ if self.task_matching:
1101
+ if labels is None:
1102
+ raise ValueError("Matching task requires labels")
1103
+ if pixel_values_mixed is None:
1104
+ raise ValueError("Matching task requires pixel_values_mixed")
1105
+
1106
+ outputs = self.tvlt(
1107
+ pixel_values_mixed,
1108
+ audio_values,
1109
+ pixel_mask=pixel_mask_mixed,
1110
+ audio_mask=audio_mask,
1111
+ output_attentions=output_attentions,
1112
+ output_hidden_states=output_hidden_states,
1113
+ return_dict=return_dict,
1114
+ )
1115
+
1116
+ sequence_output = outputs[0]
1117
+ matching_logits = self.matching_head(sequence_output)
1118
+
1119
+ loss_fct = BCEWithLogitsLoss()
1120
+ loss = loss_fct(matching_logits.view(-1), labels.view(-1))
1121
+ total_loss += loss
1122
+
1123
+ pixel_logits = None
1124
+ audio_logits = None
1125
+ if self.task_mae and self.training:
1126
+ outputs = self.tvlt(
1127
+ pixel_values,
1128
+ audio_values,
1129
+ pixel_mask=pixel_mask,
1130
+ audio_mask=audio_mask,
1131
+ mask_pixel=True,
1132
+ mask_audio=True,
1133
+ output_attentions=output_attentions,
1134
+ output_hidden_states=output_hidden_states,
1135
+ return_dict=return_dict,
1136
+ )
1137
+ pixel_sequence_output = outputs.last_pixel_hidden_state if return_dict else outputs[1]
1138
+ audio_sequence_output = outputs.last_audio_hidden_state if return_dict else outputs[2]
1139
+ pixel_label_masks = outputs.pixel_label_masks if return_dict else outputs[3]
1140
+ audio_label_masks = outputs.audio_label_masks if return_dict else outputs[4]
1141
+ pixel_ids_restore = outputs.pixel_ids_restore if return_dict else outputs[5]
1142
+ audio_ids_restore = outputs.audio_ids_restore if return_dict else outputs[6]
1143
+
1144
+ pixel_decoder_input = self.encoder_to_decoder(
1145
+ pixel_sequence_output
1146
+ ) # [batch_size, num_masked_pixel_patches, decoder_hidden_size]
1147
+ audio_decoder_input = self.encoder_to_decoder(
1148
+ audio_sequence_output
1149
+ ) # [batch_size, num_masked_audio_patches, decoder_hidden_size]
1150
+ num_frames = pixel_values.size(1)
1151
+ pixel_decoder_input = self.concatenate_mask(self.pixel_mask_token, pixel_decoder_input, pixel_ids_restore)
1152
+ pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_pos_embed.repeat(1, num_frames, 1)
1153
+ pixel_decoder_input = pixel_decoder_input + torch.repeat_interleave(
1154
+ self.decoder_temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1
1155
+ )
1156
+ pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_type_embed
1157
+ pixel_decoder_outputs = self.decoder(pixel_decoder_input)
1158
+ pixel_logits = self.pixel_mae_head(pixel_decoder_outputs.logits)
1159
+
1160
+ audio_decoder_input = self.concatenate_mask(self.audio_mask_token, audio_decoder_input, audio_ids_restore)
1161
+ num_time_patches = audio_decoder_input.size(1) // self.num_freq_patches
1162
+ audio_decoder_input = audio_decoder_input + self.decoder_freq_embed.repeat(1, num_time_patches, 1)
1163
+ audio_decoder_input = audio_decoder_input + torch.repeat_interleave(
1164
+ self.decoder_audio_pos_embed[:, :num_time_patches], self.num_freq_patches, dim=1
1165
+ )
1166
+ audio_decoder_input = audio_decoder_input + self.decoder_audio_type_embed
1167
+ audio_decoder_outputs = self.decoder(audio_decoder_input)
1168
+ audio_logits = self.audio_mae_head(audio_decoder_outputs.logits)
1169
+
1170
+ loss = self.pixel_mae_loss(pixel_values, pixel_logits, pixel_label_masks) + self.audio_mae_loss(
1171
+ audio_values, audio_logits, audio_label_masks
1172
+ )
1173
+ total_loss += loss
1174
+
1175
+ if not return_dict:
1176
+ output = (matching_logits, pixel_logits, audio_logits) + outputs[7:]
1177
+ return ((total_loss,) + output) if loss is not None else output
1178
+
1179
+ return TvltForPreTrainingOutput(
1180
+ loss=total_loss,
1181
+ matching_logits=matching_logits,
1182
+ pixel_logits=pixel_logits,
1183
+ audio_logits=audio_logits,
1184
+ hidden_states=outputs.hidden_states,
1185
+ attentions=outputs.attentions,
1186
+ )
1187
+
1188
+
1189
+ class TvltPooler(nn.Module):
1190
+ def __init__(self, config):
1191
+ super().__init__()
1192
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1193
+ self.activation = nn.Tanh()
1194
+
1195
+ def forward(self, hidden_states):
1196
+ first_token_tensor = hidden_states[:, 0]
1197
+ pooled_output = self.dense(first_token_tensor)
1198
+ pooled_output = self.activation(pooled_output)
1199
+ return pooled_output
1200
+
1201
+
1202
+ class TvltMatchingHead(nn.Module):
1203
+ def __init__(self, config):
1204
+ super().__init__()
1205
+ self.pooler = TvltPooler(config)
1206
+ self.fc = nn.Linear(config.hidden_size, 1)
1207
+
1208
+ def forward(self, hidden_states):
1209
+ hidden_states = self.fc(self.pooler(hidden_states))
1210
+ return hidden_states
1211
+
1212
+
1213
+ class TvltMAEHead(nn.Module):
1214
+ def __init__(self, config, output_dim=None):
1215
+ super().__init__()
1216
+ self.config = config
1217
+ self.decoder = nn.Linear(config.decoder_hidden_size, output_dim)
1218
+
1219
+ def forward(self, hidden_states):
1220
+ hidden_states = self.decoder(hidden_states)
1221
+ return hidden_states
1222
+
1223
+
1224
+ @add_start_docstrings(
1225
+ """
1226
+ Tvlt Model transformer with a classifier head on top (an MLP on top of the final hidden state of the [CLS] token)
1227
+ for audiovisual classification tasks, e.g. CMU-MOSEI Sentiment Analysis and Audio to Video Retrieval.
1228
+ """,
1229
+ TVLT_START_DOCSTRING,
1230
+ )
1231
+ class TvltForAudioVisualClassification(TvltPreTrainedModel):
1232
+ def __init__(self, config):
1233
+ super().__init__(config)
1234
+
1235
+ self.tvlt = TvltModel(config)
1236
+
1237
+ # Classifier head
1238
+ self.classifier = nn.Sequential(
1239
+ nn.Linear(config.hidden_size, config.hidden_size * 2),
1240
+ nn.LayerNorm(config.hidden_size * 2, eps=config.layer_norm_eps),
1241
+ nn.GELU(),
1242
+ nn.Linear(config.hidden_size * 2, config.num_labels),
1243
+ )
1244
+ self.config = config
1245
+
1246
+ # Initialize weights and apply final processing
1247
+ self.post_init()
1248
+
1249
+ @add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
1250
+ @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
1251
+ def forward(
1252
+ self,
1253
+ pixel_values,
1254
+ audio_values,
1255
+ pixel_mask=None,
1256
+ audio_mask=None,
1257
+ output_attentions=None,
1258
+ output_hidden_states=None,
1259
+ return_dict=None,
1260
+ labels=None,
1261
+ ) -> Union[tuple, SequenceClassifierOutput]:
1262
+ r"""
1263
+ labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
1264
+ Labels for computing the audiovisual loss. Indices should be in `[0, ..., num_classes-1]` where num_classes
1265
+ refers to the number of classes in audiovisual tasks.
1266
+
1267
+ Return:
1268
+
1269
+ Examples:
1270
+ ```python
1271
+ >>> from transformers import TvltProcessor, TvltForAudioVisualClassification
1272
+ >>> import numpy as np
1273
+ >>> import torch
1274
+
1275
+ >>> num_frames = 8
1276
+ >>> images = list(np.random.randn(num_frames, 3, 224, 224))
1277
+ >>> audio = list(np.random.randn(10000))
1278
+ >>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
1279
+ >>> model = TvltForAudioVisualClassification.from_pretrained("ZinengTang/tvlt-base")
1280
+ >>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
1281
+
1282
+ >>> outputs = model(**input_dict)
1283
+ >>> loss = outputs.loss
1284
+ ```"""
1285
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1286
+
1287
+ outputs = self.tvlt(
1288
+ pixel_values,
1289
+ audio_values,
1290
+ pixel_mask=pixel_mask,
1291
+ audio_mask=audio_mask,
1292
+ output_attentions=output_attentions,
1293
+ output_hidden_states=output_hidden_states,
1294
+ return_dict=return_dict,
1295
+ )
1296
+ sequence_output = outputs[0][:, 0]
1297
+ logits = self.classifier(sequence_output) # rank value
1298
+
1299
+ loss = None
1300
+ if labels is not None:
1301
+ if self.config.loss_type == "regression":
1302
+ loss_fct = MSELoss()
1303
+ loss = loss_fct(logits, labels)
1304
+ elif self.config.loss_type == "classification":
1305
+ loss_fct = CrossEntropyLoss()
1306
+ loss = loss_fct(logits, labels)
1307
+
1308
+ if not return_dict:
1309
+ output = (logits,) + outputs[4:]
1310
+ return ((loss,) + output) if loss is not None else output
1311
+
1312
+ return SequenceClassifierOutput(
1313
+ loss=loss,
1314
+ logits=logits,
1315
+ hidden_states=outputs.hidden_states,
1316
+ attentions=outputs.attentions,
1317
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/tvlt/processing_tvlt.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 TVLT.
17
+ """
18
+
19
+ from ...processing_utils import ProcessorMixin
20
+
21
+
22
+ class TvltProcessor(ProcessorMixin):
23
+ r"""
24
+ Constructs a TVLT processor which wraps a TVLT image processor and TVLT feature extractor into a single processor.
25
+
26
+ [`TvltProcessor`] offers all the functionalities of [`TvltImageProcessor`] and [`TvltFeatureExtractor`]. See the
27
+ docstring of [`~TvltProcessor.__call__`] for more information.
28
+
29
+ Args:
30
+ image_processor (`TvltImageProcessor`):
31
+ An instance of [`TvltImageProcessor`]. The image processor is a required input.
32
+ feature_extractor (`TvltFeatureExtractor`):
33
+ An instance of [`TvltFeatureExtractor`]. The feature extractor is a required input.
34
+ """
35
+ attributes = ["image_processor", "feature_extractor"]
36
+ image_processor_class = "TvltImageProcessor"
37
+ feature_extractor_class = "TvltFeatureExtractor"
38
+
39
+ def __init__(self, image_processor, feature_extractor):
40
+ super().__init__(image_processor=image_processor, feature_extractor=feature_extractor)
41
+
42
+ self.image_processor = image_processor
43
+ self.feature_extractor = feature_extractor
44
+
45
+ def __call__(
46
+ self,
47
+ images=None,
48
+ audio=None,
49
+ images_mixed=None,
50
+ sampling_rate=None,
51
+ mask_audio=False,
52
+ mask_pixel=False,
53
+ *args,
54
+ **kwargs,
55
+ ):
56
+ """
57
+ Forwards the `images` argument to TvltImageProcessor's [`~TvltImageProcessor.preprocess`] and the `audio`
58
+ argument to TvltFeatureExtractor's [`~TvltFeatureExtractor.__call__`]. Please refer to the docstring of the
59
+ above two methods for more information.
60
+ """
61
+
62
+ if images is None and audio is None:
63
+ raise ValueError("You need to specify either an `images` or `audio` input to process.")
64
+
65
+ images_mixed_dict = None
66
+ if images is not None:
67
+ images_dict = self.image_processor(images, mask_pixel=mask_pixel, *args, **kwargs)
68
+ if images_mixed is not None:
69
+ images_mixed_dict = self.image_processor(images_mixed, is_mixed=True, *args, **kwargs)
70
+ if audio is not None:
71
+ audio_dict = self.feature_extractor(
72
+ audio, *args, sampling_rate=sampling_rate, mask_audio=mask_audio, **kwargs
73
+ )
74
+
75
+ output_dict = {}
76
+ if audio is not None:
77
+ output_dict.update(audio_dict)
78
+ if images is not None:
79
+ output_dict.update(images_dict)
80
+ if images_mixed_dict is not None:
81
+ output_dict.update(images_mixed_dict)
82
+ return output_dict
83
+
84
+ @property
85
+ def model_input_names(self):
86
+ image_processor_input_names = self.image_processor.model_input_names
87
+ feature_extractor_input_names = self.feature_extractor.model_input_names
88
+ return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/__init__.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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 (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_flax_available,
20
+ is_tf_available,
21
+ is_torch_available,
22
+ )
23
+
24
+
25
+ _import_structure = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]}
26
+
27
+ try:
28
+ if not is_torch_available():
29
+ raise OptionalDependencyNotAvailable()
30
+ except OptionalDependencyNotAvailable:
31
+ pass
32
+ else:
33
+ _import_structure["modeling_unispeech"] = [
34
+ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST",
35
+ "UniSpeechForCTC",
36
+ "UniSpeechForPreTraining",
37
+ "UniSpeechForSequenceClassification",
38
+ "UniSpeechModel",
39
+ "UniSpeechPreTrainedModel",
40
+ ]
41
+
42
+ if TYPE_CHECKING:
43
+ from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig
44
+
45
+ try:
46
+ if not is_torch_available():
47
+ raise OptionalDependencyNotAvailable()
48
+ except OptionalDependencyNotAvailable:
49
+ pass
50
+ else:
51
+ from .modeling_unispeech import (
52
+ UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST,
53
+ UniSpeechForCTC,
54
+ UniSpeechForPreTraining,
55
+ UniSpeechForSequenceClassification,
56
+ UniSpeechModel,
57
+ UniSpeechPreTrainedModel,
58
+ )
59
+
60
+ else:
61
+ import sys
62
+
63
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/configuration_unispeech.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "microsoft/unispeech-large-1500h-cv": (
28
+ "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json"
29
+ ),
30
+ # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
31
+ }
32
+
33
+
34
+ class UniSpeechConfig(PretrainedConfig):
35
+ r"""
36
+ This is the configuration class to store the configuration of a [`UniSpeechModel`]. It is used to instantiate an
37
+ UniSpeech model according to the specified arguments, defining the model architecture. Instantiating a
38
+ configuration with the defaults will yield a similar configuration to that of the UniSpeech
39
+ [microsoft/unispeech-large-1500h-cv](https://huggingface.co/microsoft/unispeech-large-1500h-cv) architecture.
40
+
41
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
42
+ documentation from [`PretrainedConfig`] for more information.
43
+
44
+
45
+ Args:
46
+ vocab_size (`int`, *optional*, defaults to 32):
47
+ Vocabulary size of the UniSpeech model. Defines the number of different tokens that can be represented by
48
+ the `inputs_ids` passed when calling [`UniSpeechModel`]. Vocabulary size of the model. Defines the
49
+ different tokens that can be represented by the *inputs_ids* passed to the forward method of
50
+ [`UniSpeechModel`].
51
+ hidden_size (`int`, *optional*, defaults to 768):
52
+ Dimensionality of the encoder layers and the pooler layer.
53
+ num_hidden_layers (`int`, *optional*, defaults to 12):
54
+ Number of hidden layers in the Transformer encoder.
55
+ num_attention_heads (`int`, *optional*, defaults to 12):
56
+ Number of attention heads for each attention layer in the Transformer encoder.
57
+ intermediate_size (`int`, *optional*, defaults to 3072):
58
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
59
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
60
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
61
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
62
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
63
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
64
+ attention_dropout (`float`, *optional*, defaults to 0.1):
65
+ The dropout ratio for the attention probabilities.
66
+ final_dropout (`float`, *optional*, defaults to 0.1):
67
+ The dropout probability for the final projection layer of [`UniSpeechForCTC`].
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
71
+ The epsilon used by the layer normalization layers.
72
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
73
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
74
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
75
+ convolutional layers.
76
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
77
+ The dropout probability for output of the feature encoder.
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
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
82
+ The dropout probabilitiy for quantized feature encoder states.
83
+ conv_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
84
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
85
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
86
+ conv_stride (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
87
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
88
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
89
+ conv_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
90
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
91
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
92
+ *conv_dim*.
93
+ conv_bias (`bool`, *optional*, defaults to `False`):
94
+ Whether the 1D convolutional layers have a bias.
95
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
96
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
97
+ embeddings layer.
98
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
99
+ Number of groups of 1D convolutional positional embeddings layer.
100
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
101
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
102
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
103
+ False` corresponds to applying layer norm after the attention layer.
104
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
105
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
106
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
107
+ Recognition](https://arxiv.org/abs/1904.08779).
108
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
109
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
110
+ procecure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
111
+ reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
112
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
113
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
114
+ mask_time_length (`int`, *optional*, defaults to 10):
115
+ Length of vector span along the time axis.
116
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
117
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
118
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
119
+ mask_time_min_masks''
120
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
121
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
122
+ masking procecure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
123
+ the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
124
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
125
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
126
+ True`.
127
+ mask_feature_length (`int`, *optional*, defaults to 10):
128
+ Length of vector span along the feature axis.
129
+ mask_feature_min_masks (`int`, *optional*, defaults to 0),:
130
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
131
+ step, irrespectively of `mask_feature_prob`. Only relevant if
132
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
133
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
134
+ Number of entries in each quantization codebook (group).
135
+ num_codevector_groups (`int`, *optional*, defaults to 2):
136
+ Number of codevector groups for product codevector quantization.
137
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
138
+ The temperature *kappa* in the contrastive loss.
139
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
140
+ The dropout probabilitiy for the output of the feature encoder that's used by the quantizer.
141
+ num_negatives (`int`, *optional*, defaults to 100):
142
+ Number of negative samples for the contrastive loss.
143
+ codevector_dim (`int`, *optional*, defaults to 256):
144
+ Dimensionality of the quantized feature vectors.
145
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
146
+ Dimensionality of the final projection of both the quantized and the transformer features.
147
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
148
+ The weight of the codebook diversity loss component.
149
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
150
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
151
+ instance of [`UniSpeechForCTC`].
152
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
153
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
154
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
155
+ of [`UniSpeechForCTC`].
156
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
157
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
158
+ instance of [`UniSpeechForSequenceClassification`].
159
+ classifier_proj_size (`int`, *optional*, defaults to 256):
160
+ Dimensionality of the projection before token mean-pooling for classification.
161
+ replace_prob (`float`, *optional*, defaults to 0.5):
162
+ Propability that transformer feature is replaced by quantized feature for pretraining.
163
+
164
+ Example:
165
+
166
+ ```python
167
+ >>> from transformers import UniSpeechConfig, UniSpeechModel
168
+
169
+ >>> # Initializing a UniSpeech facebook/unispeech-base-960h style configuration
170
+ >>> configuration = UniSpeechConfig()
171
+
172
+ >>> # Initializing a model (with random weights) from the facebook/unispeech-base-960h style configuration
173
+ >>> model = UniSpeechModel(configuration)
174
+
175
+ >>> # Accessing the model configuration
176
+ >>> configuration = model.config
177
+ ```"""
178
+ model_type = "unispeech"
179
+
180
+ def __init__(
181
+ self,
182
+ vocab_size=32,
183
+ hidden_size=768,
184
+ num_hidden_layers=12,
185
+ num_attention_heads=12,
186
+ intermediate_size=3072,
187
+ hidden_act="gelu",
188
+ hidden_dropout=0.1,
189
+ activation_dropout=0.1,
190
+ attention_dropout=0.1,
191
+ feat_proj_dropout=0.0,
192
+ feat_quantizer_dropout=0.0,
193
+ final_dropout=0.1,
194
+ layerdrop=0.1,
195
+ initializer_range=0.02,
196
+ layer_norm_eps=1e-5,
197
+ feat_extract_norm="group",
198
+ feat_extract_activation="gelu",
199
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
200
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
201
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
202
+ conv_bias=False,
203
+ num_conv_pos_embeddings=128,
204
+ num_conv_pos_embedding_groups=16,
205
+ do_stable_layer_norm=False,
206
+ apply_spec_augment=True,
207
+ mask_time_prob=0.05,
208
+ mask_time_length=10,
209
+ mask_time_min_masks=2,
210
+ mask_feature_prob=0.0,
211
+ mask_feature_length=10,
212
+ mask_feature_min_masks=0,
213
+ num_codevectors_per_group=320,
214
+ num_codevector_groups=2,
215
+ contrastive_logits_temperature=0.1,
216
+ num_negatives=100,
217
+ codevector_dim=256,
218
+ proj_codevector_dim=256,
219
+ diversity_loss_weight=0.1,
220
+ ctc_loss_reduction="mean",
221
+ ctc_zero_infinity=False,
222
+ use_weighted_layer_sum=False,
223
+ classifier_proj_size=256,
224
+ num_ctc_classes=80,
225
+ pad_token_id=0,
226
+ bos_token_id=1,
227
+ eos_token_id=2,
228
+ replace_prob=0.5,
229
+ **kwargs,
230
+ ):
231
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
232
+ self.hidden_size = hidden_size
233
+ self.feat_extract_norm = feat_extract_norm
234
+ self.feat_extract_activation = feat_extract_activation
235
+ self.conv_dim = list(conv_dim)
236
+ self.conv_stride = list(conv_stride)
237
+ self.conv_kernel = list(conv_kernel)
238
+ self.conv_bias = conv_bias
239
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
240
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
241
+ self.num_feat_extract_layers = len(self.conv_dim)
242
+ self.num_hidden_layers = num_hidden_layers
243
+ self.intermediate_size = intermediate_size
244
+ self.hidden_act = hidden_act
245
+ self.num_attention_heads = num_attention_heads
246
+ self.hidden_dropout = hidden_dropout
247
+ self.attention_dropout = attention_dropout
248
+ self.activation_dropout = activation_dropout
249
+ self.feat_proj_dropout = feat_proj_dropout
250
+ self.final_dropout = final_dropout
251
+ self.layerdrop = layerdrop
252
+ self.layer_norm_eps = layer_norm_eps
253
+ self.initializer_range = initializer_range
254
+ self.num_ctc_classes = num_ctc_classes
255
+ self.vocab_size = vocab_size
256
+ self.do_stable_layer_norm = do_stable_layer_norm
257
+ self.use_weighted_layer_sum = use_weighted_layer_sum
258
+ self.classifier_proj_size = classifier_proj_size
259
+
260
+ if (
261
+ (len(self.conv_stride) != self.num_feat_extract_layers)
262
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
263
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
264
+ ):
265
+ raise ValueError(
266
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
267
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
268
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
269
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
270
+ )
271
+
272
+ # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
273
+ self.apply_spec_augment = apply_spec_augment
274
+ self.mask_time_prob = mask_time_prob
275
+ self.mask_time_length = mask_time_length
276
+ self.mask_time_min_masks = mask_time_min_masks
277
+ self.mask_feature_prob = mask_feature_prob
278
+ self.mask_feature_length = mask_feature_length
279
+ self.mask_feature_min_masks = mask_feature_min_masks
280
+
281
+ # parameters for pretraining with codevector quantized representations
282
+ self.num_codevectors_per_group = num_codevectors_per_group
283
+ self.num_codevector_groups = num_codevector_groups
284
+ self.contrastive_logits_temperature = contrastive_logits_temperature
285
+ self.feat_quantizer_dropout = feat_quantizer_dropout
286
+ self.num_negatives = num_negatives
287
+ self.codevector_dim = codevector_dim
288
+ self.proj_codevector_dim = proj_codevector_dim
289
+ self.diversity_loss_weight = diversity_loss_weight
290
+
291
+ # ctc loss
292
+ self.ctc_loss_reduction = ctc_loss_reduction
293
+ self.ctc_zero_infinity = ctc_zero_infinity
294
+
295
+ # pretraining loss
296
+ self.replace_prob = replace_prob
297
+
298
+ @property
299
+ def inputs_to_logits_ratio(self):
300
+ return functools.reduce(operator.mul, self.conv_stride, 1)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ import argparse
19
+ import json
20
+ import os
21
+
22
+ import fairseq
23
+ import torch
24
+ from fairseq.data import Dictionary
25
+
26
+ from transformers import (
27
+ UniSpeechConfig,
28
+ UniSpeechForCTC,
29
+ UniSpeechForPreTraining,
30
+ Wav2Vec2FeatureExtractor,
31
+ Wav2Vec2PhonemeCTCTokenizer,
32
+ Wav2Vec2Processor,
33
+ logging,
34
+ )
35
+
36
+
37
+ logging.set_verbosity_info()
38
+ logger = logging.get_logger(__name__)
39
+
40
+ MAPPING = {
41
+ "post_extract_proj": "feature_projection.projection",
42
+ "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
43
+ "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
44
+ "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
45
+ "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
46
+ "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
47
+ "self_attn_layer_norm": "encoder.layers.*.layer_norm",
48
+ "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
49
+ "fc2": "encoder.layers.*.feed_forward.output_dense",
50
+ "final_layer_norm": "encoder.layers.*.final_layer_norm",
51
+ "encoder.layer_norm": "encoder.layer_norm",
52
+ "w2v_model.layer_norm": "feature_projection.layer_norm",
53
+ "quantizer.weight_proj": "quantizer.weight_proj",
54
+ "quantizer.vars": "quantizer.codevectors",
55
+ "project_q": "project_q",
56
+ "final_proj": "project_hid",
57
+ "w2v_encoder.proj": "ctc_proj",
58
+ "mask_emb": "masked_spec_embed",
59
+ }
60
+ TOP_LEVEL_KEYS = [
61
+ "ctc_proj",
62
+ "quantizer.weight_proj",
63
+ "quantizer.codevectors",
64
+ "project_q",
65
+ "project_hid",
66
+ ]
67
+
68
+
69
+ def set_recursively(hf_pointer, key, value, full_name, weight_type, is_finetuned):
70
+ for attribute in key.split("."):
71
+ if is_finetuned:
72
+ if attribute in ["quantizer", "project_q", "project_hid"]:
73
+ # those layers are only relevant for pretraining and should be dropped
74
+ return
75
+
76
+ if attribute == "ctc_proj":
77
+ # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
78
+ attribute = "lm_head"
79
+
80
+ hf_pointer = getattr(hf_pointer, attribute)
81
+
82
+ if weight_type is not None:
83
+ hf_shape = getattr(hf_pointer, weight_type).shape
84
+ else:
85
+ hf_shape = hf_pointer.shape
86
+
87
+ assert hf_shape == value.shape, (
88
+ f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
89
+ f" {value.shape} for {full_name}"
90
+ )
91
+
92
+ if weight_type == "weight":
93
+ hf_pointer.weight.data = value
94
+ elif weight_type == "weight_g":
95
+ hf_pointer.weight_g.data = value
96
+ elif weight_type == "weight_v":
97
+ hf_pointer.weight_v.data = value
98
+ elif weight_type == "bias":
99
+ hf_pointer.bias.data = value
100
+ else:
101
+ hf_pointer.data = value
102
+
103
+ logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.")
104
+
105
+
106
+ def recursively_load_weights(fairseq_model, hf_model, is_finetuned):
107
+ unused_weights = []
108
+ fairseq_dict = fairseq_model.state_dict()
109
+
110
+ feature_extractor = hf_model.unispeech.feature_extractor
111
+
112
+ for name, value in fairseq_dict.items():
113
+ is_used = False
114
+ if "conv_layers" in name:
115
+ load_conv_layer(
116
+ name,
117
+ value,
118
+ feature_extractor,
119
+ unused_weights,
120
+ hf_model.config.feat_extract_norm == "group",
121
+ )
122
+ is_used = True
123
+ else:
124
+ for key, mapped_key in MAPPING.items():
125
+ mapped_key = "unispeech." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
126
+ if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
127
+ is_used = True
128
+ if "*" in mapped_key:
129
+ layer_index = name.split(key)[0].split(".")[-2]
130
+ mapped_key = mapped_key.replace("*", layer_index)
131
+ if "weight_g" in name:
132
+ weight_type = "weight_g"
133
+ elif "weight_v" in name:
134
+ weight_type = "weight_v"
135
+ elif "bias" in name:
136
+ weight_type = "bias"
137
+ elif "weight" in name:
138
+ # TODO: don't match quantizer.weight_proj
139
+ weight_type = "weight"
140
+ else:
141
+ weight_type = None
142
+ set_recursively(hf_model, mapped_key, value, name, weight_type, is_finetuned)
143
+ continue
144
+ if not is_used:
145
+ unused_weights.append(name)
146
+
147
+ logger.warning(f"Unused weights: {unused_weights}")
148
+
149
+
150
+ def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm):
151
+ name = full_name.split("conv_layers.")[-1]
152
+ items = name.split(".")
153
+ layer_id = int(items[0])
154
+ type_id = int(items[1])
155
+
156
+ if type_id == 0:
157
+ if "bias" in name:
158
+ assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
159
+ f"{full_name} has size {value.shape}, but"
160
+ f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
161
+ )
162
+ feature_extractor.conv_layers[layer_id].conv.bias.data = value
163
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
164
+ elif "weight" in name:
165
+ assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
166
+ f"{full_name} has size {value.shape}, but"
167
+ f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
168
+ )
169
+ feature_extractor.conv_layers[layer_id].conv.weight.data = value
170
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
171
+ elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
172
+ if "bias" in name:
173
+ assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
174
+ f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
175
+ " found."
176
+ )
177
+ feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value
178
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
179
+ elif "weight" in name:
180
+ assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
181
+ f"{full_name} has size {value.shape}, but"
182
+ f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
183
+ )
184
+ feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value
185
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
186
+ else:
187
+ unused_weights.append(full_name)
188
+
189
+
190
+ @torch.no_grad()
191
+ def convert_unispeech_checkpoint(
192
+ checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True
193
+ ):
194
+ """
195
+ Copy/paste/tweak model's weights to transformers design.
196
+ """
197
+ if config_path is not None:
198
+ config = UniSpeechConfig.from_pretrained(config_path)
199
+ else:
200
+ config = UniSpeechConfig()
201
+
202
+ if is_finetuned:
203
+ if dict_path:
204
+ target_dict = Dictionary.load_from_json(dict_path)
205
+
206
+ # important change bos & pad token id since CTC symbol is <pad> and
207
+ # not <s> as in fairseq
208
+ config.bos_token_id = target_dict.pad_index
209
+ config.pad_token_id = target_dict.bos_index
210
+ config.eos_token_id = target_dict.eos_index
211
+ config.vocab_size = len(target_dict.symbols)
212
+ vocab_path = os.path.join(pytorch_dump_folder_path, "vocab.json")
213
+ if not os.path.isdir(pytorch_dump_folder_path):
214
+ logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(pytorch_dump_folder_path))
215
+ return
216
+ os.makedirs(pytorch_dump_folder_path, exist_ok=True)
217
+ vocab_dict = target_dict.indices
218
+
219
+ # fairseq has the <pad> and <s> switched
220
+ vocab_dict["<pad>"] = 42
221
+ vocab_dict["<s>"] = 43
222
+ with open(vocab_path, "w", encoding="utf-8") as vocab_handle:
223
+ json.dump(vocab_dict, vocab_handle)
224
+ tokenizer = Wav2Vec2PhonemeCTCTokenizer(
225
+ vocab_path,
226
+ unk_token=target_dict.unk_word,
227
+ pad_token=target_dict.pad_word,
228
+ bos_token=target_dict.bos_word,
229
+ eos_token=target_dict.eos_word,
230
+ word_delimiter_token="|",
231
+ do_lower_case=False,
232
+ )
233
+ return_attention_mask = True if config.feat_extract_norm == "layer" else False
234
+ feature_extractor = Wav2Vec2FeatureExtractor(
235
+ feature_size=1,
236
+ sampling_rate=16000,
237
+ padding_value=0,
238
+ do_normalize=True,
239
+ return_attention_mask=return_attention_mask,
240
+ )
241
+ processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
242
+ processor.save_pretrained(pytorch_dump_folder_path)
243
+
244
+ hf_unispeech = UniSpeechForCTC(config)
245
+ else:
246
+ hf_unispeech = UniSpeechForPreTraining(config)
247
+
248
+ if is_finetuned:
249
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
250
+ [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/")[:-1]), "w2v_path": checkpoint_path}
251
+ )
252
+ else:
253
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path])
254
+
255
+ model = model[0].eval()
256
+
257
+ recursively_load_weights(model, hf_unispeech, is_finetuned)
258
+
259
+ hf_unispeech.save_pretrained(pytorch_dump_folder_path)
260
+
261
+
262
+ if __name__ == "__main__":
263
+ parser = argparse.ArgumentParser()
264
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
265
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
266
+ parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
267
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
268
+ parser.add_argument(
269
+ "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
270
+ )
271
+ args = parser.parse_args()
272
+ convert_unispeech_checkpoint(
273
+ args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
274
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech/modeling_unispeech.py ADDED
@@ -0,0 +1,1585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ...deepspeed import is_deepspeed_zero3_enabled
30
+ from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput, Wav2Vec2BaseModelOutput
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...utils import (
33
+ ModelOutput,
34
+ add_code_sample_docstrings,
35
+ add_start_docstrings,
36
+ add_start_docstrings_to_model_forward,
37
+ logging,
38
+ replace_return_docstrings,
39
+ )
40
+ from .configuration_unispeech import UniSpeechConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ _HIDDEN_STATES_START_POSITION = 2
47
+
48
+ # General docstring
49
+ _CONFIG_FOR_DOC = "UniSpeechConfig"
50
+
51
+ # Base docstring
52
+ _CHECKPOINT_FOR_DOC = "patrickvonplaten/unispeech-large-1500h-cv-timit"
53
+ _EXPECTED_OUTPUT_SHAPE = [1, 292, 1024]
54
+
55
+ # CTC docstring
56
+ _CTC_EXPECTED_OUTPUT = "'mister quilter is the apposl of the midle classes and weare glad to welcom his gosepl'"
57
+ _CTC_EXPECTED_LOSS = 17.17
58
+
59
+ UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST = [
60
+ "microsoft/unispeech-large-1500h-cv",
61
+ "microsoft/unispeech-large-multi-lingual-1500h-cv",
62
+ # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
63
+ ]
64
+
65
+
66
+ @dataclass
67
+ class UniSpeechForPreTrainingOutput(ModelOutput):
68
+ """
69
+ Output type of [`UniSpeechForPreTrainingOutput`], with potential hidden states and attentions.
70
+
71
+ Args:
72
+ loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
73
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
74
+ paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
75
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
76
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
77
+ projected quantized states.
78
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
79
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
80
+ target vectors for contrastive loss.
81
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
82
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
83
+ shape `(batch_size, sequence_length, hidden_size)`.
84
+
85
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
86
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
87
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
88
+ sequence_length)`.
89
+
90
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
91
+ heads.
92
+ """
93
+
94
+ loss: Optional[torch.FloatTensor] = None
95
+ projected_states: torch.FloatTensor = None
96
+ projected_quantized_states: torch.FloatTensor = None
97
+ codevector_perplexity: torch.FloatTensor = None
98
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
99
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
100
+
101
+
102
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2._compute_mask_indices
103
+ def _compute_mask_indices(
104
+ shape: Tuple[int, int],
105
+ mask_prob: float,
106
+ mask_length: int,
107
+ attention_mask: Optional[torch.LongTensor] = None,
108
+ min_masks: int = 0,
109
+ ) -> np.ndarray:
110
+ """
111
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
112
+ ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on
113
+ CPU as part of the preprocessing during training.
114
+
115
+ Args:
116
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
117
+ the first element is the batch size and the second element is the length of the axis to span.
118
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
119
+ independently generated mask spans of length `mask_length` is computed by
120
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
121
+ actual percentage will be smaller.
122
+ mask_length: size of the mask
123
+ min_masks: minimum number of masked spans
124
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
125
+ each batch dimension.
126
+ """
127
+ batch_size, sequence_length = shape
128
+
129
+ if mask_length < 1:
130
+ raise ValueError("`mask_length` has to be bigger than 0.")
131
+
132
+ if mask_length > sequence_length:
133
+ raise ValueError(
134
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
135
+ f" and `sequence_length`: {sequence_length}`"
136
+ )
137
+
138
+ # epsilon is used for probabilistic rounding
139
+ epsilon = np.random.rand(1).item()
140
+
141
+ def compute_num_masked_span(input_length):
142
+ """Given input length, compute how many spans should be masked"""
143
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
144
+ num_masked_span = max(num_masked_span, min_masks)
145
+
146
+ # make sure num masked span <= sequence_length
147
+ if num_masked_span * mask_length > sequence_length:
148
+ num_masked_span = sequence_length // mask_length
149
+
150
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
151
+ if input_length - (mask_length - 1) < num_masked_span:
152
+ num_masked_span = max(input_length - (mask_length - 1), 0)
153
+
154
+ return num_masked_span
155
+
156
+ # compute number of masked spans in batch
157
+ input_lengths = (
158
+ attention_mask.sum(-1).detach().tolist()
159
+ if attention_mask is not None
160
+ else [sequence_length for _ in range(batch_size)]
161
+ )
162
+
163
+ # SpecAugment mask to fill
164
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
165
+ spec_aug_mask_idxs = []
166
+
167
+ max_num_masked_span = compute_num_masked_span(sequence_length)
168
+
169
+ if max_num_masked_span == 0:
170
+ return spec_aug_mask
171
+
172
+ for input_length in input_lengths:
173
+ # compute num of masked spans for this input
174
+ num_masked_span = compute_num_masked_span(input_length)
175
+
176
+ # get random indices to mask
177
+ spec_aug_mask_idx = np.random.choice(
178
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
179
+ )
180
+
181
+ # pick first sampled index that will serve as a dummy index to pad vector
182
+ # to ensure same dimension for all batches due to probabilistic rounding
183
+ # Picking first sample just pads those vectors twice.
184
+ if len(spec_aug_mask_idx) == 0:
185
+ # this case can only happen if `input_length` is strictly smaller then
186
+ # `sequence_length` in which case the last token has to be a padding
187
+ # token which we can use as a dummy mask id
188
+ dummy_mask_idx = sequence_length - 1
189
+ else:
190
+ dummy_mask_idx = spec_aug_mask_idx[0]
191
+
192
+ spec_aug_mask_idx = np.concatenate(
193
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
194
+ )
195
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
196
+
197
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
198
+
199
+ # expand masked indices to masked spans
200
+ spec_aug_mask_idxs = np.broadcast_to(
201
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
202
+ )
203
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
204
+
205
+ # add offset to the starting indexes so that indexes now create a span
206
+ offsets = np.arange(mask_length)[None, None, :]
207
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
208
+ batch_size, max_num_masked_span * mask_length
209
+ )
210
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
211
+
212
+ # ensure that we cannot have indices larger than sequence_length
213
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
214
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
215
+
216
+ # scatter indices to mask
217
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
218
+
219
+ return spec_aug_mask
220
+
221
+
222
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2NoLayerNormConvLayer with Wav2Vec2->UniSpeech
223
+ class UniSpeechNoLayerNormConvLayer(nn.Module):
224
+ def __init__(self, config, layer_id=0):
225
+ super().__init__()
226
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
227
+ self.out_conv_dim = config.conv_dim[layer_id]
228
+
229
+ self.conv = nn.Conv1d(
230
+ self.in_conv_dim,
231
+ self.out_conv_dim,
232
+ kernel_size=config.conv_kernel[layer_id],
233
+ stride=config.conv_stride[layer_id],
234
+ bias=config.conv_bias,
235
+ )
236
+ self.activation = ACT2FN[config.feat_extract_activation]
237
+
238
+ def forward(self, hidden_states):
239
+ hidden_states = self.conv(hidden_states)
240
+ hidden_states = self.activation(hidden_states)
241
+ return hidden_states
242
+
243
+
244
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2LayerNormConvLayer with Wav2Vec2->UniSpeech
245
+ class UniSpeechLayerNormConvLayer(nn.Module):
246
+ def __init__(self, config, layer_id=0):
247
+ super().__init__()
248
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
249
+ self.out_conv_dim = config.conv_dim[layer_id]
250
+
251
+ self.conv = nn.Conv1d(
252
+ self.in_conv_dim,
253
+ self.out_conv_dim,
254
+ kernel_size=config.conv_kernel[layer_id],
255
+ stride=config.conv_stride[layer_id],
256
+ bias=config.conv_bias,
257
+ )
258
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
259
+ self.activation = ACT2FN[config.feat_extract_activation]
260
+
261
+ def forward(self, hidden_states):
262
+ hidden_states = self.conv(hidden_states)
263
+
264
+ hidden_states = hidden_states.transpose(-2, -1)
265
+ hidden_states = self.layer_norm(hidden_states)
266
+ hidden_states = hidden_states.transpose(-2, -1)
267
+
268
+ hidden_states = self.activation(hidden_states)
269
+ return hidden_states
270
+
271
+
272
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2GroupNormConvLayer with Wav2Vec2->UniSpeech
273
+ class UniSpeechGroupNormConvLayer(nn.Module):
274
+ def __init__(self, config, layer_id=0):
275
+ super().__init__()
276
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
277
+ self.out_conv_dim = config.conv_dim[layer_id]
278
+
279
+ self.conv = nn.Conv1d(
280
+ self.in_conv_dim,
281
+ self.out_conv_dim,
282
+ kernel_size=config.conv_kernel[layer_id],
283
+ stride=config.conv_stride[layer_id],
284
+ bias=config.conv_bias,
285
+ )
286
+ self.activation = ACT2FN[config.feat_extract_activation]
287
+
288
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
289
+
290
+ def forward(self, hidden_states):
291
+ hidden_states = self.conv(hidden_states)
292
+ hidden_states = self.layer_norm(hidden_states)
293
+ hidden_states = self.activation(hidden_states)
294
+ return hidden_states
295
+
296
+
297
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2PositionalConvEmbedding with Wav2Vec2->UniSpeech
298
+ class UniSpeechPositionalConvEmbedding(nn.Module):
299
+ def __init__(self, config):
300
+ super().__init__()
301
+ self.conv = nn.Conv1d(
302
+ config.hidden_size,
303
+ config.hidden_size,
304
+ kernel_size=config.num_conv_pos_embeddings,
305
+ padding=config.num_conv_pos_embeddings // 2,
306
+ groups=config.num_conv_pos_embedding_groups,
307
+ )
308
+
309
+ if is_deepspeed_zero3_enabled():
310
+ import deepspeed
311
+
312
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
313
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
314
+ deepspeed.zero.register_external_parameter(self, self.conv.weight_v)
315
+ deepspeed.zero.register_external_parameter(self, self.conv.weight_g)
316
+ else:
317
+ self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
318
+
319
+ self.padding = UniSpeechSamePadLayer(config.num_conv_pos_embeddings)
320
+ self.activation = ACT2FN[config.feat_extract_activation]
321
+
322
+ def forward(self, hidden_states):
323
+ hidden_states = hidden_states.transpose(1, 2)
324
+
325
+ hidden_states = self.conv(hidden_states)
326
+ hidden_states = self.padding(hidden_states)
327
+ hidden_states = self.activation(hidden_states)
328
+
329
+ hidden_states = hidden_states.transpose(1, 2)
330
+ return hidden_states
331
+
332
+
333
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2SamePadLayer with Wav2Vec2->UniSpeech
334
+ class UniSpeechSamePadLayer(nn.Module):
335
+ def __init__(self, num_conv_pos_embeddings):
336
+ super().__init__()
337
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
338
+
339
+ def forward(self, hidden_states):
340
+ if self.num_pad_remove > 0:
341
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
342
+ return hidden_states
343
+
344
+
345
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureEncoder with Wav2Vec2->UniSpeech
346
+ class UniSpeechFeatureEncoder(nn.Module):
347
+ """Construct the features from raw audio waveform"""
348
+
349
+ def __init__(self, config):
350
+ super().__init__()
351
+
352
+ if config.feat_extract_norm == "group":
353
+ conv_layers = [UniSpeechGroupNormConvLayer(config, layer_id=0)] + [
354
+ UniSpeechNoLayerNormConvLayer(config, layer_id=i + 1)
355
+ for i in range(config.num_feat_extract_layers - 1)
356
+ ]
357
+ elif config.feat_extract_norm == "layer":
358
+ conv_layers = [
359
+ UniSpeechLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
360
+ ]
361
+ else:
362
+ raise ValueError(
363
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
364
+ )
365
+ self.conv_layers = nn.ModuleList(conv_layers)
366
+ self.gradient_checkpointing = False
367
+ self._requires_grad = True
368
+
369
+ def _freeze_parameters(self):
370
+ for param in self.parameters():
371
+ param.requires_grad = False
372
+ self._requires_grad = False
373
+
374
+ def forward(self, input_values):
375
+ hidden_states = input_values[:, None]
376
+
377
+ # make sure hidden_states require grad for gradient_checkpointing
378
+ if self._requires_grad and self.training:
379
+ hidden_states.requires_grad = True
380
+
381
+ for conv_layer in self.conv_layers:
382
+ if self._requires_grad and self.gradient_checkpointing and self.training:
383
+
384
+ def create_custom_forward(module):
385
+ def custom_forward(*inputs):
386
+ return module(*inputs)
387
+
388
+ return custom_forward
389
+
390
+ hidden_states = torch.utils.checkpoint.checkpoint(
391
+ create_custom_forward(conv_layer),
392
+ hidden_states,
393
+ )
394
+ else:
395
+ hidden_states = conv_layer(hidden_states)
396
+
397
+ return hidden_states
398
+
399
+
400
+ class UniSpeechFeatureExtractor(UniSpeechFeatureEncoder):
401
+ def __init__(self, config):
402
+ super().__init__(config)
403
+ warnings.warn(
404
+ f"The class `{self.__class__.__name__}` has been depreciated "
405
+ "and will be removed in Transformers v5. "
406
+ f"Use `{self.__class__.__bases__[0].__name__}` instead.",
407
+ FutureWarning,
408
+ )
409
+
410
+
411
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureProjection with Wav2Vec2->UniSpeech
412
+ class UniSpeechFeatureProjection(nn.Module):
413
+ def __init__(self, config):
414
+ super().__init__()
415
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
416
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
417
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
418
+
419
+ def forward(self, hidden_states):
420
+ # non-projected hidden states are needed for quantization
421
+ norm_hidden_states = self.layer_norm(hidden_states)
422
+ hidden_states = self.projection(norm_hidden_states)
423
+ hidden_states = self.dropout(hidden_states)
424
+ return hidden_states, norm_hidden_states
425
+
426
+
427
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->UniSpeech
428
+ class UniSpeechAttention(nn.Module):
429
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
430
+
431
+ def __init__(
432
+ self,
433
+ embed_dim: int,
434
+ num_heads: int,
435
+ dropout: float = 0.0,
436
+ is_decoder: bool = False,
437
+ bias: bool = True,
438
+ ):
439
+ super().__init__()
440
+ self.embed_dim = embed_dim
441
+ self.num_heads = num_heads
442
+ self.dropout = dropout
443
+ self.head_dim = embed_dim // num_heads
444
+
445
+ if (self.head_dim * num_heads) != self.embed_dim:
446
+ raise ValueError(
447
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
448
+ f" and `num_heads`: {num_heads})."
449
+ )
450
+ self.scaling = self.head_dim**-0.5
451
+ self.is_decoder = is_decoder
452
+
453
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
454
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
455
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
456
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
457
+
458
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
459
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
460
+
461
+ def forward(
462
+ self,
463
+ hidden_states: torch.Tensor,
464
+ key_value_states: Optional[torch.Tensor] = None,
465
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
466
+ attention_mask: Optional[torch.Tensor] = None,
467
+ layer_head_mask: Optional[torch.Tensor] = None,
468
+ output_attentions: bool = False,
469
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
470
+ """Input shape: Batch x Time x Channel"""
471
+
472
+ # if key_value_states are provided this layer is used as a cross-attention layer
473
+ # for the decoder
474
+ is_cross_attention = key_value_states is not None
475
+
476
+ bsz, tgt_len, _ = hidden_states.size()
477
+
478
+ # get query proj
479
+ query_states = self.q_proj(hidden_states) * self.scaling
480
+ # get key, value proj
481
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
482
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
483
+ # the provided `key_value_states` to support prefix tuning
484
+ if (
485
+ is_cross_attention
486
+ and past_key_value is not None
487
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
488
+ ):
489
+ # reuse k,v, cross_attentions
490
+ key_states = past_key_value[0]
491
+ value_states = past_key_value[1]
492
+ elif is_cross_attention:
493
+ # cross_attentions
494
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
495
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
496
+ elif past_key_value is not None:
497
+ # reuse k, v, self_attention
498
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
499
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
500
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
501
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
502
+ else:
503
+ # self_attention
504
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
505
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
506
+
507
+ if self.is_decoder:
508
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
509
+ # Further calls to cross_attention layer can then reuse all cross-attention
510
+ # key/value_states (first "if" case)
511
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
512
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
513
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
514
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
515
+ past_key_value = (key_states, value_states)
516
+
517
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
518
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
519
+ key_states = key_states.reshape(*proj_shape)
520
+ value_states = value_states.reshape(*proj_shape)
521
+
522
+ src_len = key_states.size(1)
523
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
524
+
525
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
526
+ raise ValueError(
527
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
528
+ f" {attn_weights.size()}"
529
+ )
530
+
531
+ if attention_mask is not None:
532
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
533
+ raise ValueError(
534
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
535
+ )
536
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
537
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
538
+
539
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
540
+
541
+ if layer_head_mask is not None:
542
+ if layer_head_mask.size() != (self.num_heads,):
543
+ raise ValueError(
544
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
545
+ f" {layer_head_mask.size()}"
546
+ )
547
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
548
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
549
+
550
+ if output_attentions:
551
+ # this operation is a bit awkward, but it's required to
552
+ # make sure that attn_weights keeps its gradient.
553
+ # In order to do so, attn_weights have to be reshaped
554
+ # twice and have to be reused in the following
555
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
556
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
557
+ else:
558
+ attn_weights_reshaped = None
559
+
560
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
561
+
562
+ attn_output = torch.bmm(attn_probs, value_states)
563
+
564
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
565
+ raise ValueError(
566
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
567
+ f" {attn_output.size()}"
568
+ )
569
+
570
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
571
+ attn_output = attn_output.transpose(1, 2)
572
+
573
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
574
+ # partitioned across GPUs when using tensor-parallelism.
575
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
576
+
577
+ attn_output = self.out_proj(attn_output)
578
+
579
+ return attn_output, attn_weights_reshaped, past_key_value
580
+
581
+
582
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeedForward with Wav2Vec2->UniSpeech
583
+ class UniSpeechFeedForward(nn.Module):
584
+ def __init__(self, config):
585
+ super().__init__()
586
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
587
+
588
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
589
+ if isinstance(config.hidden_act, str):
590
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
591
+ else:
592
+ self.intermediate_act_fn = config.hidden_act
593
+
594
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
595
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
596
+
597
+ def forward(self, hidden_states):
598
+ hidden_states = self.intermediate_dense(hidden_states)
599
+ hidden_states = self.intermediate_act_fn(hidden_states)
600
+ hidden_states = self.intermediate_dropout(hidden_states)
601
+
602
+ hidden_states = self.output_dense(hidden_states)
603
+ hidden_states = self.output_dropout(hidden_states)
604
+ return hidden_states
605
+
606
+
607
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderLayer with Wav2Vec2->UniSpeech
608
+ class UniSpeechEncoderLayer(nn.Module):
609
+ def __init__(self, config):
610
+ super().__init__()
611
+ self.attention = UniSpeechAttention(
612
+ embed_dim=config.hidden_size,
613
+ num_heads=config.num_attention_heads,
614
+ dropout=config.attention_dropout,
615
+ is_decoder=False,
616
+ )
617
+ self.dropout = nn.Dropout(config.hidden_dropout)
618
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
619
+ self.feed_forward = UniSpeechFeedForward(config)
620
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
621
+
622
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
623
+ attn_residual = hidden_states
624
+ hidden_states, attn_weights, _ = self.attention(
625
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
626
+ )
627
+ hidden_states = self.dropout(hidden_states)
628
+ hidden_states = attn_residual + hidden_states
629
+
630
+ hidden_states = self.layer_norm(hidden_states)
631
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
632
+ hidden_states = self.final_layer_norm(hidden_states)
633
+
634
+ outputs = (hidden_states,)
635
+
636
+ if output_attentions:
637
+ outputs += (attn_weights,)
638
+
639
+ return outputs
640
+
641
+
642
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderLayerStableLayerNorm with Wav2Vec2->UniSpeech
643
+ class UniSpeechEncoderLayerStableLayerNorm(nn.Module):
644
+ def __init__(self, config):
645
+ super().__init__()
646
+ self.attention = UniSpeechAttention(
647
+ embed_dim=config.hidden_size,
648
+ num_heads=config.num_attention_heads,
649
+ dropout=config.attention_dropout,
650
+ is_decoder=False,
651
+ )
652
+ self.dropout = nn.Dropout(config.hidden_dropout)
653
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
654
+ self.feed_forward = UniSpeechFeedForward(config)
655
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
656
+
657
+ def forward(
658
+ self,
659
+ hidden_states: torch.Tensor,
660
+ attention_mask: Optional[torch.Tensor] = None,
661
+ output_attentions: bool = False,
662
+ ):
663
+ attn_residual = hidden_states
664
+ hidden_states = self.layer_norm(hidden_states)
665
+ hidden_states, attn_weights, _ = self.attention(
666
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
667
+ )
668
+ hidden_states = self.dropout(hidden_states)
669
+ hidden_states = attn_residual + hidden_states
670
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
671
+
672
+ outputs = (hidden_states,)
673
+
674
+ if output_attentions:
675
+ outputs += (attn_weights,)
676
+
677
+ return outputs
678
+
679
+
680
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Encoder with Wav2Vec2->UniSpeech
681
+ class UniSpeechEncoder(nn.Module):
682
+ def __init__(self, config):
683
+ super().__init__()
684
+ self.config = config
685
+ self.pos_conv_embed = UniSpeechPositionalConvEmbedding(config)
686
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
687
+ self.dropout = nn.Dropout(config.hidden_dropout)
688
+ self.layers = nn.ModuleList([UniSpeechEncoderLayer(config) for _ in range(config.num_hidden_layers)])
689
+ self.gradient_checkpointing = False
690
+
691
+ def forward(
692
+ self,
693
+ hidden_states: torch.tensor,
694
+ attention_mask: Optional[torch.Tensor] = None,
695
+ output_attentions: bool = False,
696
+ output_hidden_states: bool = False,
697
+ return_dict: bool = True,
698
+ ):
699
+ all_hidden_states = () if output_hidden_states else None
700
+ all_self_attentions = () if output_attentions else None
701
+
702
+ if attention_mask is not None:
703
+ # make sure padded tokens output 0
704
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
705
+ hidden_states[~expand_attention_mask] = 0
706
+
707
+ # extend attention_mask
708
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
709
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
710
+ attention_mask = attention_mask.expand(
711
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
712
+ )
713
+
714
+ position_embeddings = self.pos_conv_embed(hidden_states)
715
+ hidden_states = hidden_states + position_embeddings
716
+ hidden_states = self.layer_norm(hidden_states)
717
+ hidden_states = self.dropout(hidden_states)
718
+
719
+ deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
720
+
721
+ for layer in self.layers:
722
+ if output_hidden_states:
723
+ all_hidden_states = all_hidden_states + (hidden_states,)
724
+
725
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
726
+ dropout_probability = np.random.uniform(0, 1)
727
+
728
+ skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False
729
+ if not skip_the_layer or deepspeed_zero3_is_enabled:
730
+ # under deepspeed zero3 all gpus must run in sync
731
+ if self.gradient_checkpointing and self.training:
732
+ # create gradient checkpointing function
733
+ def create_custom_forward(module):
734
+ def custom_forward(*inputs):
735
+ return module(*inputs, output_attentions)
736
+
737
+ return custom_forward
738
+
739
+ layer_outputs = torch.utils.checkpoint.checkpoint(
740
+ create_custom_forward(layer),
741
+ hidden_states,
742
+ attention_mask,
743
+ )
744
+ else:
745
+ layer_outputs = layer(
746
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
747
+ )
748
+ hidden_states = layer_outputs[0]
749
+
750
+ if skip_the_layer:
751
+ layer_outputs = (None, None)
752
+
753
+ if output_attentions:
754
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
755
+
756
+ if output_hidden_states:
757
+ all_hidden_states = all_hidden_states + (hidden_states,)
758
+
759
+ if not return_dict:
760
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
761
+ return BaseModelOutput(
762
+ last_hidden_state=hidden_states,
763
+ hidden_states=all_hidden_states,
764
+ attentions=all_self_attentions,
765
+ )
766
+
767
+
768
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2EncoderStableLayerNorm with Wav2Vec2->UniSpeech
769
+ class UniSpeechEncoderStableLayerNorm(nn.Module):
770
+ def __init__(self, config):
771
+ super().__init__()
772
+ self.config = config
773
+ self.pos_conv_embed = UniSpeechPositionalConvEmbedding(config)
774
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
775
+ self.dropout = nn.Dropout(config.hidden_dropout)
776
+ self.layers = nn.ModuleList(
777
+ [UniSpeechEncoderLayerStableLayerNorm(config) for _ in range(config.num_hidden_layers)]
778
+ )
779
+ self.gradient_checkpointing = False
780
+
781
+ def forward(
782
+ self,
783
+ hidden_states,
784
+ attention_mask=None,
785
+ output_attentions=False,
786
+ output_hidden_states=False,
787
+ return_dict=True,
788
+ ):
789
+ all_hidden_states = () if output_hidden_states else None
790
+ all_self_attentions = () if output_attentions else None
791
+
792
+ if attention_mask is not None:
793
+ # make sure padded tokens are not attended to
794
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
795
+ hidden_states[~expand_attention_mask] = 0
796
+
797
+ # extend attention_mask
798
+ attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
799
+ attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
800
+ attention_mask = attention_mask.expand(
801
+ attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1]
802
+ )
803
+
804
+ position_embeddings = self.pos_conv_embed(hidden_states)
805
+ hidden_states = hidden_states + position_embeddings
806
+ hidden_states = self.dropout(hidden_states)
807
+
808
+ deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
809
+
810
+ for layer in self.layers:
811
+ if output_hidden_states:
812
+ all_hidden_states = all_hidden_states + (hidden_states,)
813
+
814
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
815
+ dropout_probability = np.random.uniform(0, 1)
816
+
817
+ skip_the_layer = True if self.training and (dropout_probability < self.config.layerdrop) else False
818
+ if not skip_the_layer or deepspeed_zero3_is_enabled:
819
+ # under deepspeed zero3 all gpus must run in sync
820
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
821
+ if self.gradient_checkpointing and self.training:
822
+ # create gradient checkpointing function
823
+ def create_custom_forward(module):
824
+ def custom_forward(*inputs):
825
+ return module(*inputs, output_attentions)
826
+
827
+ return custom_forward
828
+
829
+ layer_outputs = torch.utils.checkpoint.checkpoint(
830
+ create_custom_forward(layer),
831
+ hidden_states,
832
+ attention_mask,
833
+ )
834
+ else:
835
+ layer_outputs = layer(
836
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
837
+ )
838
+ hidden_states = layer_outputs[0]
839
+
840
+ if skip_the_layer:
841
+ layer_outputs = (None, None)
842
+
843
+ if output_attentions:
844
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
845
+
846
+ hidden_states = self.layer_norm(hidden_states)
847
+
848
+ if output_hidden_states:
849
+ all_hidden_states = all_hidden_states + (hidden_states,)
850
+
851
+ if not return_dict:
852
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
853
+ return BaseModelOutput(
854
+ last_hidden_state=hidden_states,
855
+ hidden_states=all_hidden_states,
856
+ attentions=all_self_attentions,
857
+ )
858
+
859
+
860
+ class UniSpeechGumbelVectorQuantizer(nn.Module):
861
+ """
862
+ Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH
863
+ GUMBEL-SOFTMAX](https://arxiv.org/pdf/1611.01144.pdf) for more information.
864
+ """
865
+
866
+ def __init__(self, config):
867
+ super().__init__()
868
+ self.num_groups = config.num_codevector_groups
869
+ self.num_vars = config.num_codevectors_per_group
870
+
871
+ if config.codevector_dim % self.num_groups != 0:
872
+ raise ValueError(
873
+ f"`config.codevector_dim {config.codevector_dim} must be divisible by `config.num_codevector_groups`"
874
+ f" {self.num_groups} for concatenation"
875
+ )
876
+
877
+ # storage for codebook variables (codewords)
878
+ self.codevectors = nn.Parameter(
879
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
880
+ )
881
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
882
+
883
+ # can be decayed for training
884
+ self.temperature = 2
885
+
886
+ @staticmethod
887
+ def _compute_perplexity(probs):
888
+ marginal_probs = probs.mean(dim=0)
889
+ perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
890
+ return perplexity
891
+
892
+ def forward(self, hidden_states):
893
+ batch_size, sequence_length, hidden_size = hidden_states.shape
894
+
895
+ # project to codevector dim
896
+ hidden_states = self.weight_proj(hidden_states)
897
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
898
+
899
+ if self.training:
900
+ # sample code vector probs via gumbel in differentiateable way
901
+ codevector_probs = nn.functional.gumbel_softmax(
902
+ hidden_states.float(), tau=self.temperature, hard=True
903
+ ).type_as(hidden_states)
904
+
905
+ # compute perplexity
906
+ codevector_soft_dist = torch.softmax(
907
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
908
+ )
909
+ perplexity = self._compute_perplexity(codevector_soft_dist)
910
+ else:
911
+ # take argmax in non-differentiable way
912
+ # comptute hard codevector distribution (one hot)
913
+ codevector_idx = hidden_states.argmax(dim=-1)
914
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
915
+ -1, codevector_idx.view(-1, 1), 1.0
916
+ )
917
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
918
+
919
+ perplexity = self._compute_perplexity(codevector_probs)
920
+
921
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
922
+ # use probs to retrieve codevectors
923
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
924
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
925
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
926
+
927
+ return codevectors, perplexity
928
+
929
+
930
+ class UniSpeechPreTrainedModel(PreTrainedModel):
931
+ """
932
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
933
+ models.
934
+ """
935
+
936
+ config_class = UniSpeechConfig
937
+ base_model_prefix = "unispeech"
938
+ main_input_name = "input_values"
939
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
940
+ supports_gradient_checkpointing = True
941
+
942
+ def _init_weights(self, module):
943
+ """Initialize the weights"""
944
+ # gumbel softmax requires special init
945
+ if isinstance(module, UniSpeechGumbelVectorQuantizer):
946
+ module.weight_proj.weight.data.normal_(mean=0.0, std=1)
947
+ module.weight_proj.bias.data.zero_()
948
+ nn.init.uniform_(module.codevectors)
949
+ elif isinstance(module, UniSpeechPositionalConvEmbedding):
950
+ nn.init.normal_(
951
+ module.conv.weight,
952
+ mean=0,
953
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
954
+ )
955
+ nn.init.constant_(module.conv.bias, 0)
956
+ elif isinstance(module, UniSpeechFeatureProjection):
957
+ k = math.sqrt(1 / module.projection.in_features)
958
+ nn.init.uniform_(module.projection.weight, a=-k, b=k)
959
+ nn.init.uniform_(module.projection.bias, a=-k, b=k)
960
+ elif isinstance(module, nn.Linear):
961
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
962
+
963
+ if module.bias is not None:
964
+ module.bias.data.zero_()
965
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
966
+ module.bias.data.zero_()
967
+ module.weight.data.fill_(1.0)
968
+ elif isinstance(module, nn.Conv1d):
969
+ nn.init.kaiming_normal_(module.weight)
970
+
971
+ if module.bias is not None:
972
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
973
+ nn.init.uniform_(module.bias, a=-k, b=k)
974
+
975
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
976
+ """
977
+ Computes the output length of the convolutional layers
978
+ """
979
+
980
+ def _conv_out_length(input_length, kernel_size, stride):
981
+ # 1D convolutional layer output length formula taken
982
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
983
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
984
+
985
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
986
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
987
+
988
+ return input_lengths
989
+
990
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
991
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
992
+ # on inference mode.
993
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
994
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long)
995
+ batch_size = attention_mask.shape[0]
996
+
997
+ attention_mask = torch.zeros(
998
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
999
+ )
1000
+ # these two operations makes sure that all values before the output lengths idxs are attended to
1001
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
1002
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
1003
+ return attention_mask
1004
+
1005
+ def _set_gradient_checkpointing(self, module, value=False):
1006
+ if isinstance(module, (UniSpeechEncoder, UniSpeechEncoderStableLayerNorm, UniSpeechFeatureEncoder)):
1007
+ module.gradient_checkpointing = value
1008
+
1009
+
1010
+ UNISPEECH_START_DOCSTRING = r"""
1011
+ UniSpeech was proposed in [UniSpeech: Unified Speech Representation Learning with Labeled and Unlabeled
1012
+ Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei,
1013
+ Michael Zeng, Xuedong Huang.
1014
+
1015
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1016
+ library implements for all its model (such as downloading or saving etc.).
1017
+
1018
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
1019
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
1020
+ behavior.
1021
+
1022
+ Parameters:
1023
+ config ([`UniSpeechConfig`]): Model configuration class with all the parameters of the model.
1024
+ Initializing with a config file does not load the weights associated with the model, only the
1025
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1026
+ """
1027
+
1028
+
1029
+ UNISPEECH_INPUTS_DOCSTRING = r"""
1030
+ Args:
1031
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1032
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1033
+ into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install
1034
+ soundfile`). To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and
1035
+ conversion into a tensor of type `torch.FloatTensor`. See [`Wav2Vec2Processor.__call__`] for details.
1036
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1037
+ Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,
1038
+ 1]`:
1039
+
1040
+ - 1 for tokens that are **not masked**,
1041
+ - 0 for tokens that are **masked**.
1042
+
1043
+ [What are attention masks?](../glossary#attention-mask)
1044
+
1045
+ <Tip warning={true}>
1046
+
1047
+ `attention_mask` should only be passed if the corresponding processor has `config.return_attention_mask ==
1048
+ True`. For all models whose processor has `config.return_attention_mask == False`, `attention_mask` should
1049
+ **not** be passed to avoid degraded performance when doing batched inference. For such models
1050
+ `input_values` should simply be padded with 0 and passed without `attention_mask`. Be aware that these
1051
+ models also yield slightly different results depending on whether `input_values` is padded or not.
1052
+
1053
+ </Tip>
1054
+
1055
+ output_attentions (`bool`, *optional*):
1056
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1057
+ tensors for more detail.
1058
+ output_hidden_states (`bool`, *optional*):
1059
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1060
+ more detail.
1061
+ return_dict (`bool`, *optional*):
1062
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1063
+ """
1064
+
1065
+
1066
+ @add_start_docstrings(
1067
+ "The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.",
1068
+ UNISPEECH_START_DOCSTRING,
1069
+ )
1070
+ class UniSpeechModel(UniSpeechPreTrainedModel):
1071
+ def __init__(self, config: UniSpeechConfig):
1072
+ super().__init__(config)
1073
+ self.config = config
1074
+ self.feature_extractor = UniSpeechFeatureEncoder(config)
1075
+ self.feature_projection = UniSpeechFeatureProjection(config)
1076
+
1077
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
1078
+ self.masked_spec_embed = nn.Parameter(torch.FloatTensor(config.hidden_size).uniform_())
1079
+
1080
+ if config.do_stable_layer_norm:
1081
+ self.encoder = UniSpeechEncoderStableLayerNorm(config)
1082
+ else:
1083
+ self.encoder = UniSpeechEncoder(config)
1084
+
1085
+ # Initialize weights and apply final processing
1086
+ self.post_init()
1087
+
1088
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model._mask_hidden_states
1089
+ def _mask_hidden_states(
1090
+ self,
1091
+ hidden_states: torch.FloatTensor,
1092
+ mask_time_indices: Optional[torch.FloatTensor] = None,
1093
+ attention_mask: Optional[torch.LongTensor] = None,
1094
+ ):
1095
+ """
1096
+ Masks extracted features along time axis and/or along feature axis according to
1097
+ [SpecAugment](https://arxiv.org/abs/1904.08779).
1098
+ """
1099
+
1100
+ # `config.apply_spec_augment` can set masking to False
1101
+ if not getattr(self.config, "apply_spec_augment", True):
1102
+ return hidden_states
1103
+
1104
+ # generate indices & apply SpecAugment along time axis
1105
+ batch_size, sequence_length, hidden_size = hidden_states.size()
1106
+
1107
+ if mask_time_indices is not None:
1108
+ # apply SpecAugment along time axis with given mask_time_indices
1109
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1110
+ elif self.config.mask_time_prob > 0 and self.training:
1111
+ mask_time_indices = _compute_mask_indices(
1112
+ (batch_size, sequence_length),
1113
+ mask_prob=self.config.mask_time_prob,
1114
+ mask_length=self.config.mask_time_length,
1115
+ attention_mask=attention_mask,
1116
+ min_masks=self.config.mask_time_min_masks,
1117
+ )
1118
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
1119
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1120
+
1121
+ if self.config.mask_feature_prob > 0 and self.training:
1122
+ # generate indices & apply SpecAugment along feature axis
1123
+ mask_feature_indices = _compute_mask_indices(
1124
+ (batch_size, hidden_size),
1125
+ mask_prob=self.config.mask_feature_prob,
1126
+ mask_length=self.config.mask_feature_length,
1127
+ min_masks=self.config.mask_feature_min_masks,
1128
+ )
1129
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
1130
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
1131
+ hidden_states[mask_feature_indices] = 0
1132
+
1133
+ return hidden_states
1134
+
1135
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1136
+ @add_code_sample_docstrings(
1137
+ checkpoint=_CHECKPOINT_FOR_DOC,
1138
+ output_type=Wav2Vec2BaseModelOutput,
1139
+ config_class=_CONFIG_FOR_DOC,
1140
+ modality="audio",
1141
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
1142
+ )
1143
+ def forward(
1144
+ self,
1145
+ input_values: Optional[torch.Tensor],
1146
+ attention_mask: Optional[torch.Tensor] = None,
1147
+ mask_time_indices: Optional[torch.FloatTensor] = None,
1148
+ output_attentions: Optional[bool] = None,
1149
+ output_hidden_states: Optional[bool] = None,
1150
+ return_dict: Optional[bool] = None,
1151
+ ) -> Union[Tuple, Wav2Vec2BaseModelOutput]:
1152
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1153
+ output_hidden_states = (
1154
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1155
+ )
1156
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1157
+
1158
+ extract_features = self.feature_extractor(input_values)
1159
+ extract_features = extract_features.transpose(1, 2)
1160
+
1161
+ if attention_mask is not None:
1162
+ # compute reduced attention_mask corresponding to feature vectors
1163
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
1164
+
1165
+ hidden_states, extract_features = self.feature_projection(extract_features)
1166
+ hidden_states = self._mask_hidden_states(
1167
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1168
+ )
1169
+
1170
+ encoder_outputs = self.encoder(
1171
+ hidden_states,
1172
+ attention_mask=attention_mask,
1173
+ output_attentions=output_attentions,
1174
+ output_hidden_states=output_hidden_states,
1175
+ return_dict=return_dict,
1176
+ )
1177
+
1178
+ hidden_states = encoder_outputs[0]
1179
+
1180
+ if not return_dict:
1181
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1182
+
1183
+ return Wav2Vec2BaseModelOutput(
1184
+ last_hidden_state=hidden_states,
1185
+ extract_features=extract_features,
1186
+ hidden_states=encoder_outputs.hidden_states,
1187
+ attentions=encoder_outputs.attentions,
1188
+ )
1189
+
1190
+
1191
+ @add_start_docstrings(
1192
+ """UniSpeech Model with a vector-quantization module and ctc loss for pre-training.""", UNISPEECH_START_DOCSTRING
1193
+ )
1194
+ class UniSpeechForPreTraining(UniSpeechPreTrainedModel):
1195
+ def __init__(self, config: UniSpeechConfig):
1196
+ super().__init__(config)
1197
+ self.unispeech = UniSpeechModel(config)
1198
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
1199
+
1200
+ self.quantizer = UniSpeechGumbelVectorQuantizer(config)
1201
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
1202
+ self.project_hid = nn.Linear(config.proj_codevector_dim, config.hidden_size)
1203
+
1204
+ self.ctc_proj = nn.Linear(config.hidden_size, config.num_ctc_classes)
1205
+ self.dropout = nn.Dropout(config.final_dropout)
1206
+
1207
+ # Initialize weights and apply final processing
1208
+ self.post_init()
1209
+
1210
+ def set_gumbel_temperature(self, temperature: int):
1211
+ """
1212
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
1213
+ """
1214
+ self.quantizer.temperature = temperature
1215
+
1216
+ def freeze_feature_extractor(self):
1217
+ """
1218
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1219
+ not be updated during training.
1220
+ """
1221
+ warnings.warn(
1222
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5."
1223
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1224
+ FutureWarning,
1225
+ )
1226
+ self.freeze_feature_encoder()
1227
+
1228
+ def freeze_feature_encoder(self):
1229
+ """
1230
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1231
+ not be updated during training.
1232
+ """
1233
+ self.unispeech.feature_extractor._freeze_parameters()
1234
+
1235
+ @staticmethod
1236
+ def compute_contrastive_logits(
1237
+ target_features: torch.FloatTensor,
1238
+ negative_features: torch.FloatTensor,
1239
+ predicted_features: torch.FloatTensor,
1240
+ temperature: int = 1,
1241
+ ):
1242
+ """
1243
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
1244
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
1245
+ """
1246
+ target_features = torch.cat([target_features, negative_features], dim=0)
1247
+
1248
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1)
1249
+ logits = logits.type_as(target_features)
1250
+
1251
+ # apply temperature
1252
+ logits = logits / temperature
1253
+ return logits
1254
+
1255
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1256
+ @replace_return_docstrings(output_type=UniSpeechForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1257
+ def forward(
1258
+ self,
1259
+ input_values: Optional[torch.Tensor],
1260
+ attention_mask: Optional[torch.Tensor] = None,
1261
+ output_attentions: Optional[bool] = None,
1262
+ output_hidden_states: Optional[bool] = None,
1263
+ return_dict: Optional[bool] = None,
1264
+ ) -> Union[Tuple, UniSpeechForPreTrainingOutput]:
1265
+ r"""
1266
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1267
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1268
+ masked extracted features in *config.proj_codevector_dim* space.
1269
+ sampled_negative_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_negatives)`, *optional*):
1270
+ Indices indicating which quantized target vectors are used as negative sampled vectors in contrastive loss.
1271
+ Required input for pre-training.
1272
+
1273
+ Returns:
1274
+
1275
+ Example:
1276
+
1277
+ ```python
1278
+ >>> import torch
1279
+ >>> from transformers import AutoFeatureExtractor, UniSpeechForPreTraining
1280
+
1281
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-large-1500h-cv")
1282
+ >>> model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv")
1283
+ >>> # TODO: Add full pretraining example
1284
+ ```"""
1285
+
1286
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1287
+
1288
+ outputs = self.unispeech(
1289
+ input_values,
1290
+ attention_mask=attention_mask,
1291
+ output_attentions=output_attentions,
1292
+ output_hidden_states=output_hidden_states,
1293
+ return_dict=return_dict,
1294
+ )
1295
+ transformer_features = outputs[0]
1296
+
1297
+ # quantize all (unmasked) extracted features and project to final vq dim
1298
+ extract_features = self.dropout_features(outputs[1])
1299
+ quantized_features, codevector_perplexity = self.quantizer(extract_features)
1300
+
1301
+ # project quantized features twice
1302
+ quantized_features = self.project_q(quantized_features)
1303
+ quantized_features = self.project_hid(quantized_features)
1304
+
1305
+ prob_replace_matrix = torch.empty(transformer_features.size(0), transformer_features.size(1)).fill_(
1306
+ self.config.replace_prob
1307
+ )
1308
+ prob_replace_matrix = prob_replace_matrix.transpose(0, 1)
1309
+ sampled_replace_matrix = torch.bernoulli(prob_replace_matrix).bool().to(transformer_features.device)
1310
+ sampled_replace_matrix = sampled_replace_matrix.transpose(0, 1)
1311
+ sampled_replace_matrix = sampled_replace_matrix.unsqueeze(-1)
1312
+ logits = transformer_features.masked_fill(sampled_replace_matrix, 0.0) + (
1313
+ quantized_features.masked_fill(~sampled_replace_matrix, 0.0)
1314
+ )
1315
+
1316
+ # project to ctc units
1317
+ logits = self.dropout(logits)
1318
+ logits = self.ctc_proj(logits)
1319
+
1320
+ # TODO(PVP) - add negative sampling & loss computation
1321
+ loss = None
1322
+ if not return_dict:
1323
+ if loss is not None:
1324
+ return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1325
+ return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1326
+
1327
+ return UniSpeechForPreTrainingOutput(
1328
+ loss=loss,
1329
+ projected_states=transformer_features,
1330
+ projected_quantized_states=quantized_features,
1331
+ codevector_perplexity=codevector_perplexity,
1332
+ hidden_states=outputs.hidden_states,
1333
+ attentions=outputs.attentions,
1334
+ )
1335
+
1336
+
1337
+ @add_start_docstrings(
1338
+ """UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).""",
1339
+ UNISPEECH_START_DOCSTRING,
1340
+ )
1341
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC with Wav2Vec2->UniSpeech, wav2vec2->unispeech, WAV_2_VEC_2->UNISPEECH
1342
+ class UniSpeechForCTC(UniSpeechPreTrainedModel):
1343
+ def __init__(self, config):
1344
+ super().__init__(config)
1345
+
1346
+ self.unispeech = UniSpeechModel(config)
1347
+ self.dropout = nn.Dropout(config.final_dropout)
1348
+
1349
+ if config.vocab_size is None:
1350
+ raise ValueError(
1351
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1352
+ "does not define the vocabulary size of the language model head. Please "
1353
+ "instantiate the model as follows: `UniSpeechForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1354
+ "or define `vocab_size` of your model's configuration."
1355
+ )
1356
+ output_hidden_size = (
1357
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1358
+ )
1359
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1360
+
1361
+ # Initialize weights and apply final processing
1362
+ self.post_init()
1363
+
1364
+ def freeze_feature_extractor(self):
1365
+ """
1366
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1367
+ not be updated during training.
1368
+ """
1369
+ warnings.warn(
1370
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5."
1371
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1372
+ FutureWarning,
1373
+ )
1374
+ self.freeze_feature_encoder()
1375
+
1376
+ def freeze_feature_encoder(self):
1377
+ """
1378
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1379
+ not be updated during training.
1380
+ """
1381
+ self.unispeech.feature_extractor._freeze_parameters()
1382
+
1383
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1384
+ @add_code_sample_docstrings(
1385
+ checkpoint=_CHECKPOINT_FOR_DOC,
1386
+ output_type=CausalLMOutput,
1387
+ config_class=_CONFIG_FOR_DOC,
1388
+ expected_output=_CTC_EXPECTED_OUTPUT,
1389
+ expected_loss=_CTC_EXPECTED_LOSS,
1390
+ )
1391
+ def forward(
1392
+ self,
1393
+ input_values: Optional[torch.Tensor],
1394
+ attention_mask: Optional[torch.Tensor] = None,
1395
+ output_attentions: Optional[bool] = None,
1396
+ output_hidden_states: Optional[bool] = None,
1397
+ return_dict: Optional[bool] = None,
1398
+ labels: Optional[torch.Tensor] = None,
1399
+ ) -> Union[Tuple, CausalLMOutput]:
1400
+ r"""
1401
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1402
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1403
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1404
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1405
+ config.vocab_size - 1]`.
1406
+ """
1407
+
1408
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1409
+
1410
+ outputs = self.unispeech(
1411
+ input_values,
1412
+ attention_mask=attention_mask,
1413
+ output_attentions=output_attentions,
1414
+ output_hidden_states=output_hidden_states,
1415
+ return_dict=return_dict,
1416
+ )
1417
+
1418
+ hidden_states = outputs[0]
1419
+ hidden_states = self.dropout(hidden_states)
1420
+
1421
+ logits = self.lm_head(hidden_states)
1422
+
1423
+ loss = None
1424
+ if labels is not None:
1425
+ if labels.max() >= self.config.vocab_size:
1426
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1427
+
1428
+ # retrieve loss input_lengths from attention_mask
1429
+ attention_mask = (
1430
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1431
+ )
1432
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1433
+
1434
+ # assuming that padded tokens are filled with -100
1435
+ # when not being attended to
1436
+ labels_mask = labels >= 0
1437
+ target_lengths = labels_mask.sum(-1)
1438
+ flattened_targets = labels.masked_select(labels_mask)
1439
+
1440
+ # ctc_loss doesn't support fp16
1441
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1442
+
1443
+ with torch.backends.cudnn.flags(enabled=False):
1444
+ loss = nn.functional.ctc_loss(
1445
+ log_probs,
1446
+ flattened_targets,
1447
+ input_lengths,
1448
+ target_lengths,
1449
+ blank=self.config.pad_token_id,
1450
+ reduction=self.config.ctc_loss_reduction,
1451
+ zero_infinity=self.config.ctc_zero_infinity,
1452
+ )
1453
+
1454
+ if not return_dict:
1455
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1456
+ return ((loss,) + output) if loss is not None else output
1457
+
1458
+ return CausalLMOutput(
1459
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1460
+ )
1461
+
1462
+
1463
+ @add_start_docstrings(
1464
+ """
1465
+ UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1466
+ SUPERB Keyword Spotting.
1467
+ """,
1468
+ UNISPEECH_START_DOCSTRING,
1469
+ )
1470
+ class UniSpeechForSequenceClassification(UniSpeechPreTrainedModel):
1471
+ def __init__(self, config):
1472
+ super().__init__(config)
1473
+
1474
+ if hasattr(config, "add_adapter") and config.add_adapter:
1475
+ raise ValueError(
1476
+ "Sequence classification does not support the use of UniSpeech adapters (config.add_adapter=True)"
1477
+ )
1478
+ self.unispeech = UniSpeechModel(config)
1479
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1480
+ if config.use_weighted_layer_sum:
1481
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1482
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1483
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1484
+
1485
+ # Initialize weights and apply final processing
1486
+ self.post_init()
1487
+
1488
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.freeze_feature_extractor
1489
+ def freeze_feature_extractor(self):
1490
+ """
1491
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1492
+ not be updated during training.
1493
+ """
1494
+ warnings.warn(
1495
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5."
1496
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1497
+ FutureWarning,
1498
+ )
1499
+ self.freeze_feature_encoder()
1500
+
1501
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.freeze_feature_encoder with wav2vec2->unispeech
1502
+ def freeze_feature_encoder(self):
1503
+ """
1504
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1505
+ not be updated during training.
1506
+ """
1507
+ self.unispeech.feature_extractor._freeze_parameters()
1508
+
1509
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.freeze_base_model with wav2vec2->unispeech
1510
+ def freeze_base_model(self):
1511
+ """
1512
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1513
+ be updated during training. Only the classification head will be updated.
1514
+ """
1515
+ for param in self.unispeech.parameters():
1516
+ param.requires_grad = False
1517
+
1518
+ @add_start_docstrings_to_model_forward(UNISPEECH_INPUTS_DOCSTRING)
1519
+ @add_code_sample_docstrings(
1520
+ checkpoint=_CHECKPOINT_FOR_DOC,
1521
+ output_type=SequenceClassifierOutput,
1522
+ config_class=_CONFIG_FOR_DOC,
1523
+ modality="audio",
1524
+ )
1525
+ # Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification.forward with Wav2Vec2->UniSpeech, wav2vec2->unispeech
1526
+ def forward(
1527
+ self,
1528
+ input_values: Optional[torch.Tensor],
1529
+ attention_mask: Optional[torch.Tensor] = None,
1530
+ output_attentions: Optional[bool] = None,
1531
+ output_hidden_states: Optional[bool] = None,
1532
+ return_dict: Optional[bool] = None,
1533
+ labels: Optional[torch.Tensor] = None,
1534
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1535
+ r"""
1536
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1537
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1538
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1539
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1540
+ """
1541
+
1542
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1543
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1544
+
1545
+ outputs = self.unispeech(
1546
+ input_values,
1547
+ attention_mask=attention_mask,
1548
+ output_attentions=output_attentions,
1549
+ output_hidden_states=output_hidden_states,
1550
+ return_dict=return_dict,
1551
+ )
1552
+
1553
+ if self.config.use_weighted_layer_sum:
1554
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1555
+ hidden_states = torch.stack(hidden_states, dim=1)
1556
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1557
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1558
+ else:
1559
+ hidden_states = outputs[0]
1560
+
1561
+ hidden_states = self.projector(hidden_states)
1562
+ if attention_mask is None:
1563
+ pooled_output = hidden_states.mean(dim=1)
1564
+ else:
1565
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1566
+ hidden_states[~padding_mask] = 0.0
1567
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1568
+
1569
+ logits = self.classifier(pooled_output)
1570
+
1571
+ loss = None
1572
+ if labels is not None:
1573
+ loss_fct = CrossEntropyLoss()
1574
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1575
+
1576
+ if not return_dict:
1577
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1578
+ return ((loss,) + output) if loss is not None else output
1579
+
1580
+ return SequenceClassifierOutput(
1581
+ loss=loss,
1582
+ logits=logits,
1583
+ hidden_states=outputs.hidden_states,
1584
+ attentions=outputs.attentions,
1585
+ )
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech_sat/__init__.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 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 (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_flax_available,
20
+ is_tf_available,
21
+ is_torch_available,
22
+ )
23
+
24
+
25
+ _import_structure = {
26
+ "configuration_unispeech_sat": ["UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechSatConfig"],
27
+ }
28
+
29
+ try:
30
+ if not is_torch_available():
31
+ raise OptionalDependencyNotAvailable()
32
+ except OptionalDependencyNotAvailable:
33
+ pass
34
+ else:
35
+ _import_structure["modeling_unispeech_sat"] = [
36
+ "UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST",
37
+ "UniSpeechSatForAudioFrameClassification",
38
+ "UniSpeechSatForCTC",
39
+ "UniSpeechSatForPreTraining",
40
+ "UniSpeechSatForSequenceClassification",
41
+ "UniSpeechSatForXVector",
42
+ "UniSpeechSatModel",
43
+ "UniSpeechSatPreTrainedModel",
44
+ ]
45
+
46
+ if TYPE_CHECKING:
47
+ from .configuration_unispeech_sat import UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechSatConfig
48
+
49
+ try:
50
+ if not is_torch_available():
51
+ raise OptionalDependencyNotAvailable()
52
+ except OptionalDependencyNotAvailable:
53
+ pass
54
+ else:
55
+ from .modeling_unispeech_sat import (
56
+ UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST,
57
+ UniSpeechSatForAudioFrameClassification,
58
+ UniSpeechSatForCTC,
59
+ UniSpeechSatForPreTraining,
60
+ UniSpeechSatForSequenceClassification,
61
+ UniSpeechSatForXVector,
62
+ UniSpeechSatModel,
63
+ UniSpeechSatPreTrainedModel,
64
+ )
65
+
66
+ else:
67
+ import sys
68
+
69
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech_sat/configuration_unispeech_sat.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "microsoft/unispeech-sat-base-100h-libri-ft": (
28
+ "https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json"
29
+ ),
30
+ # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
31
+ }
32
+
33
+
34
+ class UniSpeechSatConfig(PretrainedConfig):
35
+ r"""
36
+ This is the configuration class to store the configuration of a [`UniSpeechSatModel`]. It is used to instantiate an
37
+ UniSpeechSat model according to the specified arguments, defining the model architecture. Instantiating a
38
+ configuration with the defaults will yield a similar configuration to that of the UniSpeechSat
39
+ [microsoft/unispeech-sat-base-100h-libri-ft](https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft)
40
+ architecture.
41
+
42
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
43
+ documentation from [`PretrainedConfig`] for more information.
44
+
45
+
46
+ Args:
47
+ vocab_size (`int`, *optional*, defaults to 32):
48
+ Vocabulary size of the UniSpeechSat model. Defines the number of different tokens that can be represented
49
+ by the `inputs_ids` passed when calling [`UniSpeechSatModel`]. Vocabulary size of the model. Defines the
50
+ different tokens that can be represented by the *inputs_ids* passed to the forward method of
51
+ [`UniSpeechSatModel`].
52
+ hidden_size (`int`, *optional*, defaults to 768):
53
+ Dimensionality of the encoder layers and the pooler layer.
54
+ num_hidden_layers (`int`, *optional*, defaults to 12):
55
+ Number of hidden layers in the Transformer encoder.
56
+ num_attention_heads (`int`, *optional*, defaults to 12):
57
+ Number of attention heads for each attention layer in the Transformer encoder.
58
+ intermediate_size (`int`, *optional*, defaults to 3072):
59
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
61
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
62
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
63
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
64
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
65
+ attention_dropout (`float`, *optional*, defaults to 0.1):
66
+ The dropout ratio for the attention probabilities.
67
+ final_dropout (`float`, *optional*, defaults to 0.1):
68
+ The dropout probability for the final projection layer of [`UniSpeechSatForCTC`].
69
+ initializer_range (`float`, *optional*, defaults to 0.02):
70
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
71
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
72
+ The epsilon used by the layer normalization layers.
73
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
74
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
75
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
76
+ convolutional layers.
77
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
78
+ The dropout probability for output of the feature encoder.
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
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
83
+ The dropout probabilitiy for quantized feature encoder states.
84
+ conv_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
85
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
86
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
87
+ conv_stride (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
88
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
89
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
90
+ conv_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 3, 3)`):
91
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
92
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
93
+ *conv_dim*.
94
+ conv_bias (`bool`, *optional*, defaults to `False`):
95
+ Whether the 1D convolutional layers have a bias.
96
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
97
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
98
+ embeddings layer.
99
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
100
+ Number of groups of 1D convolutional positional embeddings layer.
101
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
102
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
103
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
104
+ False` corresponds to applying layer norm after the attention layer.
105
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
106
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
107
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
108
+ Recognition](https://arxiv.org/abs/1904.08779).
109
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
110
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
111
+ procecure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
112
+ reasoning from the propability of each feature vector to be chosen as the start of the vector span to be
113
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
114
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
115
+ mask_time_length (`int`, *optional*, defaults to 10):
116
+ Length of vector span along the time axis.
117
+ mask_time_min_masks (`int`, *optional*, defaults to 2),:
118
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
119
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
120
+ mask_time_min_masks''
121
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
122
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
123
+ masking procecure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
124
+ the axis. If reasoning from the propability of each feature vector to be chosen as the start of the vector
125
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
126
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
127
+ True`.
128
+ mask_feature_length (`int`, *optional*, defaults to 10):
129
+ Length of vector span along the feature axis.
130
+ mask_feature_min_masks (`int`, *optional*, defaults to 0),:
131
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
132
+ step, irrespectively of `mask_feature_prob`. Only relevant if
133
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
134
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
135
+ Number of entries in each quantization codebook (group).
136
+ num_codevector_groups (`int`, *optional*, defaults to 2):
137
+ Number of codevector groups for product codevector quantization.
138
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
139
+ The temperature *kappa* in the contrastive loss.
140
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
141
+ The dropout probabilitiy for the output of the feature encoder that's used by the quantizer.
142
+ num_negatives (`int`, *optional*, defaults to 100):
143
+ Number of negative samples for the contrastive loss.
144
+ codevector_dim (`int`, *optional*, defaults to 256):
145
+ Dimensionality of the quantized feature vectors.
146
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
147
+ Dimensionality of the final projection of both the quantized and the transformer features.
148
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
149
+ The weight of the codebook diversity loss component.
150
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
151
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
152
+ instance of [`UniSpeechSatForCTC`].
153
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
154
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
155
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
156
+ of [`UniSpeechSatForCTC`].
157
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
158
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
159
+ instance of [`UniSpeechSatForSequenceClassification`].
160
+ classifier_proj_size (`int`, *optional*, defaults to 256):
161
+ Dimensionality of the projection before token mean-pooling for classification.
162
+ tdnn_dim (`Tuple[int]` or `List[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
163
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
164
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
165
+ tdnn_kernel (`Tuple[int]` or `List[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
166
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
167
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
168
+ tdnn_dilation (`Tuple[int]` or `List[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
169
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
170
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
171
+ xvector_output_dim (`int`, *optional*, defaults to 512):
172
+ Dimensionality of the *XVector* embedding vectors.
173
+
174
+ Example:
175
+
176
+ ```python
177
+ >>> from transformers import UniSpeechSatModel, UniSpeechSatConfig
178
+
179
+ >>> # Initializing a UniSpeechSat microsoft/unispeech-sat-base-100h-libri-ft style configuration
180
+ >>> configuration = UniSpeechSatConfig()
181
+
182
+ >>> # Initializing a model from the microsoft/unispeech-sat-base-100h-libri-ft style configuration
183
+ >>> model = UniSpeechSatModel(configuration)
184
+
185
+ >>> # Accessing the model configuration
186
+ >>> configuration = model.config
187
+ ```"""
188
+ model_type = "unispeech-sat"
189
+
190
+ def __init__(
191
+ self,
192
+ vocab_size=32,
193
+ hidden_size=768,
194
+ num_hidden_layers=12,
195
+ num_attention_heads=12,
196
+ intermediate_size=3072,
197
+ hidden_act="gelu",
198
+ hidden_dropout=0.1,
199
+ activation_dropout=0.1,
200
+ attention_dropout=0.1,
201
+ feat_proj_dropout=0.0,
202
+ feat_quantizer_dropout=0.0,
203
+ final_dropout=0.1,
204
+ layerdrop=0.1,
205
+ initializer_range=0.02,
206
+ layer_norm_eps=1e-5,
207
+ feat_extract_norm="group",
208
+ feat_extract_activation="gelu",
209
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
210
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
211
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
212
+ conv_bias=False,
213
+ num_conv_pos_embeddings=128,
214
+ num_conv_pos_embedding_groups=16,
215
+ do_stable_layer_norm=False,
216
+ apply_spec_augment=True,
217
+ mask_time_prob=0.05,
218
+ mask_time_length=10,
219
+ mask_time_min_masks=2,
220
+ mask_feature_prob=0.0,
221
+ mask_feature_length=10,
222
+ mask_feature_min_masks=0,
223
+ num_codevectors_per_group=320,
224
+ num_codevector_groups=2,
225
+ contrastive_logits_temperature=0.1,
226
+ num_negatives=100,
227
+ codevector_dim=256,
228
+ proj_codevector_dim=256,
229
+ diversity_loss_weight=0.1,
230
+ ctc_loss_reduction="mean",
231
+ ctc_zero_infinity=False,
232
+ use_weighted_layer_sum=False,
233
+ classifier_proj_size=256,
234
+ tdnn_dim=(512, 512, 512, 512, 1500),
235
+ tdnn_kernel=(5, 3, 3, 1, 1),
236
+ tdnn_dilation=(1, 2, 3, 1, 1),
237
+ xvector_output_dim=512,
238
+ pad_token_id=0,
239
+ bos_token_id=1,
240
+ eos_token_id=2,
241
+ num_clusters=504,
242
+ **kwargs,
243
+ ):
244
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
245
+ self.hidden_size = hidden_size
246
+ self.feat_extract_norm = feat_extract_norm
247
+ self.feat_extract_activation = feat_extract_activation
248
+ self.conv_dim = list(conv_dim)
249
+ self.conv_stride = list(conv_stride)
250
+ self.conv_kernel = list(conv_kernel)
251
+ self.conv_bias = conv_bias
252
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
253
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
254
+ self.num_feat_extract_layers = len(self.conv_dim)
255
+ self.num_hidden_layers = num_hidden_layers
256
+ self.intermediate_size = intermediate_size
257
+ self.hidden_act = hidden_act
258
+ self.num_attention_heads = num_attention_heads
259
+ self.hidden_dropout = hidden_dropout
260
+ self.attention_dropout = attention_dropout
261
+ self.activation_dropout = activation_dropout
262
+ self.feat_proj_dropout = feat_proj_dropout
263
+ self.final_dropout = final_dropout
264
+ self.layerdrop = layerdrop
265
+ self.layer_norm_eps = layer_norm_eps
266
+ self.initializer_range = initializer_range
267
+ self.vocab_size = vocab_size
268
+ self.num_clusters = num_clusters
269
+ self.do_stable_layer_norm = do_stable_layer_norm
270
+ self.use_weighted_layer_sum = use_weighted_layer_sum
271
+
272
+ if (
273
+ (len(self.conv_stride) != self.num_feat_extract_layers)
274
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
275
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
276
+ ):
277
+ raise ValueError(
278
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
279
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
280
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
281
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
282
+ )
283
+
284
+ # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
285
+ self.apply_spec_augment = apply_spec_augment
286
+ self.mask_time_prob = mask_time_prob
287
+ self.mask_time_length = mask_time_length
288
+ self.mask_time_min_masks = mask_time_min_masks
289
+ self.mask_feature_prob = mask_feature_prob
290
+ self.mask_feature_length = mask_feature_length
291
+ self.mask_feature_min_masks = mask_feature_min_masks
292
+
293
+ # parameters for pretraining with codevector quantized representations
294
+ self.num_codevectors_per_group = num_codevectors_per_group
295
+ self.num_codevector_groups = num_codevector_groups
296
+ self.contrastive_logits_temperature = contrastive_logits_temperature
297
+ self.feat_quantizer_dropout = feat_quantizer_dropout
298
+ self.num_negatives = num_negatives
299
+ self.codevector_dim = codevector_dim
300
+ self.proj_codevector_dim = proj_codevector_dim
301
+ self.diversity_loss_weight = diversity_loss_weight
302
+
303
+ # ctc loss
304
+ self.ctc_loss_reduction = ctc_loss_reduction
305
+ self.ctc_zero_infinity = ctc_zero_infinity
306
+
307
+ # SequenceClassification-specific parameter. Feel free to ignore for other classes.
308
+ self.classifier_proj_size = classifier_proj_size
309
+
310
+ # XVector-specific parameters. Feel free to ignore for other classes.
311
+ self.tdnn_dim = list(tdnn_dim)
312
+ self.tdnn_kernel = list(tdnn_kernel)
313
+ self.tdnn_dilation = list(tdnn_dilation)
314
+ self.xvector_output_dim = xvector_output_dim
315
+
316
+ @property
317
+ def inputs_to_logits_ratio(self):
318
+ return functools.reduce(operator.mul, self.conv_stride, 1)
SupplementaryMaterial_Code/OPERA/transformers-4.29.2/src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
18
+ import argparse
19
+
20
+ import torch
21
+
22
+ from transformers import (
23
+ UniSpeechSatConfig,
24
+ UniSpeechSatForAudioFrameClassification,
25
+ UniSpeechSatForSequenceClassification,
26
+ UniSpeechSatForXVector,
27
+ Wav2Vec2FeatureExtractor,
28
+ logging,
29
+ )
30
+
31
+
32
+ logging.set_verbosity_info()
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ def convert_classification(base_model_name, hf_config, downstream_dict):
37
+ model = UniSpeechSatForSequenceClassification.from_pretrained(base_model_name, config=hf_config)
38
+ model.projector.weight.data = downstream_dict["projector.weight"]
39
+ model.projector.bias.data = downstream_dict["projector.bias"]
40
+ model.classifier.weight.data = downstream_dict["model.post_net.linear.weight"]
41
+ model.classifier.bias.data = downstream_dict["model.post_net.linear.bias"]
42
+ return model
43
+
44
+
45
+ def convert_diarization(base_model_name, hf_config, downstream_dict):
46
+ model = UniSpeechSatForAudioFrameClassification.from_pretrained(base_model_name, config=hf_config)
47
+ model.classifier.weight.data = downstream_dict["model.linear.weight"]
48
+ model.classifier.bias.data = downstream_dict["model.linear.bias"]
49
+ return model
50
+
51
+
52
+ def convert_xvector(base_model_name, hf_config, downstream_dict):
53
+ model = UniSpeechSatForXVector.from_pretrained(base_model_name, config=hf_config)
54
+ model.projector.weight.data = downstream_dict["connector.weight"]
55
+ model.projector.bias.data = downstream_dict["connector.bias"]
56
+ for i, kernel_size in enumerate(hf_config.tdnn_kernel):
57
+ model.tdnn[i].kernel.weight.data = downstream_dict[
58
+ f"model.framelevel_feature_extractor.module.{i}.kernel.weight"
59
+ ]
60
+ model.tdnn[i].kernel.bias.data = downstream_dict[f"model.framelevel_feature_extractor.module.{i}.kernel.bias"]
61
+
62
+ model.feature_extractor.weight.data = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"]
63
+ model.feature_extractor.bias.data = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"]
64
+ model.classifier.weight.data = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"]
65
+ model.classifier.bias.data = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"]
66
+ model.objective.weight.data = downstream_dict["objective.W"]
67
+ return model
68
+
69
+
70
+ @torch.no_grad()
71
+ def convert_s3prl_checkpoint(base_model_name, config_path, checkpoint_path, model_dump_path):
72
+ """
73
+ Copy/paste/tweak model's weights to transformers design.
74
+ """
75
+ checkpoint = torch.load(checkpoint_path, map_location="cpu")
76
+
77
+ downstream_dict = checkpoint["Downstream"]
78
+
79
+ hf_config = UniSpeechSatConfig.from_pretrained(config_path)
80
+ hf_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
81
+ base_model_name, return_attention_mask=True, do_normalize=False
82
+ )
83
+
84
+ arch = hf_config.architectures[0]
85
+ if arch.endswith("ForSequenceClassification"):
86
+ hf_model = convert_classification(base_model_name, hf_config, downstream_dict)
87
+ elif arch.endswith("ForAudioFrameClassification"):
88
+ hf_model = convert_diarization(base_model_name, hf_config, downstream_dict)
89
+ elif arch.endswith("ForXVector"):
90
+ hf_model = convert_xvector(base_model_name, hf_config, downstream_dict)
91
+ else:
92
+ raise NotImplementedError(f"S3PRL weights conversion is not supported for {arch}")
93
+
94
+ if hf_config.use_weighted_layer_sum:
95
+ hf_model.layer_weights.data = checkpoint["Featurizer"]["weights"]
96
+
97
+ hf_feature_extractor.save_pretrained(model_dump_path)
98
+ hf_model.save_pretrained(model_dump_path)
99
+
100
+
101
+ if __name__ == "__main__":
102
+ parser = argparse.ArgumentParser()
103
+ parser.add_argument(
104
+ "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model."
105
+ )
106
+ parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.")
107
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.")
108
+ parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.")
109
+ args = parser.parse_args()
110
+ convert_s3prl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)