ZTWHHH commited on
Commit
f70bca1
·
verified ·
1 Parent(s): 64f26f8

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. janus/lib/python3.10/site-packages/transformers/models/altclip/__init__.py +28 -0
  2. janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/__init__.cpython-310.pyc +0 -0
  3. janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/configuration_altclip.cpython-310.pyc +0 -0
  4. janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/modeling_altclip.cpython-310.pyc +0 -0
  5. janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/processing_altclip.cpython-310.pyc +0 -0
  6. janus/lib/python3.10/site-packages/transformers/models/altclip/configuration_altclip.py +384 -0
  7. janus/lib/python3.10/site-packages/transformers/models/altclip/modeling_altclip.py +1758 -0
  8. janus/lib/python3.10/site-packages/transformers/models/altclip/processing_altclip.py +148 -0
  9. janus/lib/python3.10/site-packages/transformers/models/deprecated/mctct/processing_mctct.py +143 -0
  10. janus/lib/python3.10/site-packages/transformers/models/deprecated/mega/__init__.py +68 -0
  11. janus/lib/python3.10/site-packages/transformers/models/deprecated/mega/modeling_mega.py +0 -0
  12. janus/lib/python3.10/site-packages/transformers/models/deprecated/tapex/tokenization_tapex.py +1467 -0
  13. janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/__pycache__/__init__.cpython-310.pyc +0 -0
  14. janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/__pycache__/configuration_tvlt.cpython-310.pyc +0 -0
  15. janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/configuration_tvlt.py +184 -0
  16. janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py +230 -0
  17. janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/image_processing_tvlt.py +435 -0
  18. janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/processing_tvlt.py +89 -0
  19. janus/lib/python3.10/site-packages/transformers/models/dinat/__init__.py +27 -0
  20. janus/lib/python3.10/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-310.pyc +0 -0
  21. janus/lib/python3.10/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-310.pyc +0 -0
  22. janus/lib/python3.10/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-310.pyc +0 -0
  23. janus/lib/python3.10/site-packages/transformers/models/dinat/configuration_dinat.py +152 -0
  24. janus/lib/python3.10/site-packages/transformers/models/dinat/modeling_dinat.py +960 -0
  25. janus/lib/python3.10/site-packages/transformers/models/donut/__init__.py +30 -0
  26. janus/lib/python3.10/site-packages/transformers/models/donut/__pycache__/image_processing_donut.cpython-310.pyc +0 -0
  27. janus/lib/python3.10/site-packages/transformers/models/donut/configuration_donut_swin.py +135 -0
  28. janus/lib/python3.10/site-packages/transformers/models/donut/image_processing_donut.py +462 -0
  29. janus/lib/python3.10/site-packages/transformers/models/donut/modeling_donut_swin.py +1011 -0
  30. janus/lib/python3.10/site-packages/transformers/models/donut/processing_donut.py +231 -0
  31. janus/lib/python3.10/site-packages/transformers/models/efficientnet/__init__.py +28 -0
  32. janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-310.pyc +0 -0
  33. janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-310.pyc +0 -0
  34. janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-310.pyc +0 -0
  35. janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-310.pyc +0 -0
  36. janus/lib/python3.10/site-packages/transformers/models/efficientnet/configuration_efficientnet.py +169 -0
  37. janus/lib/python3.10/site-packages/transformers/models/efficientnet/image_processing_efficientnet.py +369 -0
  38. janus/lib/python3.10/site-packages/transformers/models/efficientnet/modeling_efficientnet.py +647 -0
  39. janus/lib/python3.10/site-packages/transformers/models/mpnet/__init__.py +30 -0
  40. janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/__init__.cpython-310.pyc +0 -0
  41. janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-310.pyc +0 -0
  42. janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-310.pyc +0 -0
  43. janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-310.pyc +0 -0
  44. janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet_fast.cpython-310.pyc +0 -0
  45. janus/lib/python3.10/site-packages/transformers/models/mpnet/configuration_mpnet.py +116 -0
  46. janus/lib/python3.10/site-packages/transformers/models/mpnet/modeling_mpnet.py +1064 -0
  47. janus/lib/python3.10/site-packages/transformers/models/mpnet/modeling_tf_mpnet.py +1354 -0
  48. janus/lib/python3.10/site-packages/transformers/models/mpnet/tokenization_mpnet.py +537 -0
  49. janus/lib/python3.10/site-packages/transformers/models/mpnet/tokenization_mpnet_fast.py +209 -0
  50. janus/lib/python3.10/site-packages/transformers/models/nllb/__pycache__/__init__.cpython-310.pyc +0 -0
janus/lib/python3.10/site-packages/transformers/models/altclip/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_altclip import *
22
+ from .modeling_altclip import *
23
+ from .processing_altclip import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (570 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/configuration_altclip.cpython-310.pyc ADDED
Binary file (14.9 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/modeling_altclip.cpython-310.pyc ADDED
Binary file (52.8 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/altclip/__pycache__/processing_altclip.cpython-310.pyc ADDED
Binary file (6.19 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/altclip/configuration_altclip.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang 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
+ """AltCLIP model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class AltCLIPTextConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`AltCLIPTextModel`]. It is used to instantiate a
27
+ AltCLIP text model according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the AltCLIP
29
+ [BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 250002):
37
+ Vocabulary size of the AltCLIP model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`AltCLIPTextModel`].
39
+ hidden_size (`int`, *optional*, defaults to 1024):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 24):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 16):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_size (`int`, *optional*, defaults to 4096):
46
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
47
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
49
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
50
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
51
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
52
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
53
+ The dropout ratio for the attention probabilities.
54
+ max_position_embeddings (`int`, *optional*, defaults to 514):
55
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
56
+ just in case (e.g., 512 or 1024 or 2048).
57
+ type_vocab_size (`int`, *optional*, defaults to 1):
58
+ The vocabulary size of the `token_type_ids` passed when calling [`AltCLIPTextModel`]
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ initializer_factor (`float`, *optional*, defaults to 0.02):
62
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
63
+ testing).
64
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
65
+ The epsilon used by the layer normalization layers.
66
+ pad_token_id (`int`, *optional*, defaults to 1): The id of the *padding* token.
67
+ bos_token_id (`int`, *optional*, defaults to 0): The id of the *beginning-of-sequence* token.
68
+ eos_token_id (`Union[int, List[int]]`, *optional*, defaults to 2):
69
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
70
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
71
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
72
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
73
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
74
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
75
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ project_dim (`int`, *optional*, defaults to 768):
80
+ The dimensions of the teacher model before the mapping layer.
81
+
82
+ Examples:
83
+
84
+ ```python
85
+ >>> from transformers import AltCLIPTextModel, AltCLIPTextConfig
86
+
87
+ >>> # Initializing a AltCLIPTextConfig with BAAI/AltCLIP style configuration
88
+ >>> configuration = AltCLIPTextConfig()
89
+
90
+ >>> # Initializing a AltCLIPTextModel (with random weights) from the BAAI/AltCLIP style configuration
91
+ >>> model = AltCLIPTextModel(configuration)
92
+
93
+ >>> # Accessing the model configuration
94
+ >>> configuration = model.config
95
+ ```"""
96
+
97
+ model_type = "altclip_text_model"
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_size=250002,
102
+ hidden_size=1024,
103
+ num_hidden_layers=24,
104
+ num_attention_heads=16,
105
+ intermediate_size=4096,
106
+ hidden_act="gelu",
107
+ hidden_dropout_prob=0.1,
108
+ attention_probs_dropout_prob=0.1,
109
+ max_position_embeddings=514,
110
+ type_vocab_size=1,
111
+ initializer_range=0.02,
112
+ initializer_factor=0.02,
113
+ layer_norm_eps=1e-05,
114
+ pad_token_id=1,
115
+ bos_token_id=0,
116
+ eos_token_id=2,
117
+ position_embedding_type="absolute",
118
+ use_cache=True,
119
+ project_dim=768,
120
+ **kwargs,
121
+ ):
122
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
123
+
124
+ self.vocab_size = vocab_size
125
+ self.hidden_size = hidden_size
126
+ self.num_hidden_layers = num_hidden_layers
127
+ self.num_attention_heads = num_attention_heads
128
+ self.hidden_act = hidden_act
129
+ self.intermediate_size = intermediate_size
130
+ self.hidden_dropout_prob = hidden_dropout_prob
131
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
132
+ self.max_position_embeddings = max_position_embeddings
133
+ self.type_vocab_size = type_vocab_size
134
+ self.initializer_range = initializer_range
135
+ self.initializer_factor = initializer_factor
136
+ self.layer_norm_eps = layer_norm_eps
137
+ self.position_embedding_type = position_embedding_type
138
+ self.use_cache = use_cache
139
+ self.project_dim = project_dim
140
+
141
+
142
+ class AltCLIPVisionConfig(PretrainedConfig):
143
+ r"""
144
+ This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
145
+ AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
146
+ with the defaults will yield a similar configuration to that of the AltCLIP
147
+ [BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
148
+
149
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
150
+ documentation from [`PretrainedConfig`] for more information.
151
+
152
+
153
+ Args:
154
+ hidden_size (`int`, *optional*, defaults to 768):
155
+ Dimensionality of the encoder layers and the pooler layer.
156
+ intermediate_size (`int`, *optional*, defaults to 3072):
157
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
158
+ projection_dim (`int`, *optional*, defaults to 512):
159
+ Dimensionality of text and vision projection layers.
160
+ num_hidden_layers (`int`, *optional*, defaults to 12):
161
+ Number of hidden layers in the Transformer encoder.
162
+ num_attention_heads (`int`, *optional*, defaults to 12):
163
+ Number of attention heads for each attention layer in the Transformer encoder.
164
+ num_channels (`int`, *optional*, defaults to 3):
165
+ The number of input channels.
166
+ image_size (`int`, *optional*, defaults to 224):
167
+ The size (resolution) of each image.
168
+ patch_size (`int`, *optional*, defaults to 32):
169
+ The size (resolution) of each patch.
170
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
171
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
172
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
173
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
174
+ The epsilon used by the layer normalization layers.
175
+ attention_dropout (`float`, *optional*, defaults to 0.0):
176
+ The dropout ratio for the attention probabilities.
177
+ initializer_range (`float`, *optional*, defaults to 0.02):
178
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
179
+ initializer_factor (`float`, *optional*, defaults to 1.0):
180
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
181
+ testing).
182
+
183
+ Example:
184
+
185
+ ```python
186
+ >>> from transformers import AltCLIPVisionConfig, AltCLIPVisionModel
187
+
188
+ >>> # Initializing a AltCLIPVisionConfig with BAAI/AltCLIP style configuration
189
+ >>> configuration = AltCLIPVisionConfig()
190
+
191
+ >>> # Initializing a AltCLIPVisionModel (with random weights) from the BAAI/AltCLIP style configuration
192
+ >>> model = AltCLIPVisionModel(configuration)
193
+
194
+ >>> # Accessing the model configuration
195
+ >>> configuration = model.config
196
+ ```"""
197
+
198
+ model_type = "altclip_vision_model"
199
+ base_config_key = "vision_config"
200
+
201
+ def __init__(
202
+ self,
203
+ hidden_size=768,
204
+ intermediate_size=3072,
205
+ projection_dim=512,
206
+ num_hidden_layers=12,
207
+ num_attention_heads=12,
208
+ num_channels=3,
209
+ image_size=224,
210
+ patch_size=32,
211
+ hidden_act="quick_gelu",
212
+ layer_norm_eps=1e-5,
213
+ attention_dropout=0.0,
214
+ initializer_range=0.02,
215
+ initializer_factor=1.0,
216
+ **kwargs,
217
+ ):
218
+ super().__init__(**kwargs)
219
+
220
+ self.hidden_size = hidden_size
221
+ self.intermediate_size = intermediate_size
222
+ self.projection_dim = projection_dim
223
+ self.num_hidden_layers = num_hidden_layers
224
+ self.num_attention_heads = num_attention_heads
225
+ self.num_channels = num_channels
226
+ self.patch_size = patch_size
227
+ self.image_size = image_size
228
+ self.initializer_range = initializer_range
229
+ self.initializer_factor = initializer_factor
230
+ self.attention_dropout = attention_dropout
231
+ self.layer_norm_eps = layer_norm_eps
232
+ self.hidden_act = hidden_act
233
+
234
+
235
+ class AltCLIPConfig(PretrainedConfig):
236
+ r"""
237
+ This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
238
+ AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
239
+ with the defaults will yield a similar configuration to that of the AltCLIP
240
+ [BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
241
+
242
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
243
+ documentation from [`PretrainedConfig`] for more information.
244
+
245
+ Args:
246
+ text_config (`dict`, *optional*):
247
+ Dictionary of configuration options used to initialize [`AltCLIPTextConfig`].
248
+ vision_config (`dict`, *optional*):
249
+ Dictionary of configuration options used to initialize [`AltCLIPVisionConfig`].
250
+ projection_dim (`int`, *optional*, defaults to 768):
251
+ Dimensionality of text and vision projection layers.
252
+ logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
253
+ The initial value of the *logit_scale* parameter. Default is used as per the original CLIP implementation.
254
+ kwargs (*optional*):
255
+ Dictionary of keyword arguments.
256
+
257
+ Example:
258
+
259
+ ```python
260
+ >>> from transformers import AltCLIPConfig, AltCLIPModel
261
+
262
+ >>> # Initializing a AltCLIPConfig with BAAI/AltCLIP style configuration
263
+ >>> configuration = AltCLIPConfig()
264
+
265
+ >>> # Initializing a AltCLIPModel (with random weights) from the BAAI/AltCLIP style configuration
266
+ >>> model = AltCLIPModel(configuration)
267
+
268
+ >>> # Accessing the model configuration
269
+ >>> configuration = model.config
270
+
271
+ >>> # We can also initialize a AltCLIPConfig from a AltCLIPTextConfig and a AltCLIPVisionConfig
272
+
273
+ >>> # Initializing a AltCLIPText and AltCLIPVision configuration
274
+ >>> config_text = AltCLIPTextConfig()
275
+ >>> config_vision = AltCLIPVisionConfig()
276
+
277
+ >>> config = AltCLIPConfig.from_text_vision_configs(config_text, config_vision)
278
+ ```"""
279
+
280
+ model_type = "altclip"
281
+ sub_configs = {"text_config": AltCLIPTextConfig, "vision_config": AltCLIPVisionConfig}
282
+
283
+ def __init__(
284
+ self, text_config=None, vision_config=None, projection_dim=768, logit_scale_init_value=2.6592, **kwargs
285
+ ):
286
+ # If `_config_dict` exist, we use them for the backward compatibility.
287
+ # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
288
+ # of confusion!).
289
+ text_config_dict = kwargs.pop("text_config_dict", None)
290
+ vision_config_dict = kwargs.pop("vision_config_dict", None)
291
+
292
+ super().__init__(**kwargs)
293
+
294
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
295
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
296
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
297
+ if text_config_dict is not None:
298
+ if text_config is None:
299
+ text_config = {}
300
+
301
+ # This is the complete result when using `text_config_dict`.
302
+ _text_config_dict = AltCLIPTextConfig(**text_config_dict).to_dict()
303
+
304
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
305
+ for key, value in _text_config_dict.items():
306
+ if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
307
+ # If specified in `text_config_dict`
308
+ if key in text_config_dict:
309
+ message = (
310
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
311
+ f'The value `text_config_dict["{key}"]` will be used instead.'
312
+ )
313
+ # If inferred from default argument values (just to be super careful)
314
+ else:
315
+ message = (
316
+ f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
317
+ f'value `text_config["{key}"]` will be overridden.'
318
+ )
319
+ logger.info(message)
320
+
321
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
322
+ text_config.update(_text_config_dict)
323
+
324
+ if vision_config_dict is not None:
325
+ if vision_config is None:
326
+ vision_config = {}
327
+
328
+ # This is the complete result when using `vision_config_dict`.
329
+ _vision_config_dict = AltCLIPVisionConfig(**vision_config_dict).to_dict()
330
+ # convert keys to string instead of integer
331
+ if "id2label" in _vision_config_dict:
332
+ _vision_config_dict["id2label"] = {
333
+ str(key): value for key, value in _vision_config_dict["id2label"].items()
334
+ }
335
+
336
+ # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
337
+ for key, value in _vision_config_dict.items():
338
+ if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
339
+ # If specified in `vision_config_dict`
340
+ if key in vision_config_dict:
341
+ message = (
342
+ f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
343
+ f'values. The value `vision_config_dict["{key}"]` will be used instead.'
344
+ )
345
+ # If inferred from default argument values (just to be super careful)
346
+ else:
347
+ message = (
348
+ f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
349
+ f'The value `vision_config["{key}"]` will be overridden.'
350
+ )
351
+ logger.info(message)
352
+
353
+ # Update all values in `vision_config` with the ones in `_vision_config_dict`.
354
+ vision_config.update(_vision_config_dict)
355
+
356
+ if text_config is None:
357
+ text_config = {}
358
+ logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.")
359
+
360
+ if vision_config is None:
361
+ vision_config = {}
362
+ logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.")
363
+
364
+ self.text_config = AltCLIPTextConfig(**text_config)
365
+ self.vision_config = AltCLIPVisionConfig(**vision_config)
366
+
367
+ self.projection_dim = projection_dim
368
+ self.logit_scale_init_value = logit_scale_init_value
369
+ self.initializer_factor = 1.0
370
+
371
+ @classmethod
372
+ def from_text_vision_configs(cls, text_config: AltCLIPTextConfig, vision_config: AltCLIPVisionConfig, **kwargs):
373
+ r"""
374
+ Instantiate a [`AltCLIPConfig`] (or a derived class) from altclip text model configuration and altclip vision
375
+ model configuration.
376
+
377
+ Returns:
378
+ [`AltCLIPConfig`]: An instance of a configuration object
379
+ """
380
+
381
+ return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
382
+
383
+
384
+ __all__ = ["AltCLIPTextConfig", "AltCLIPVisionConfig", "AltCLIPConfig"]
janus/lib/python3.10/site-packages/transformers/models/altclip/modeling_altclip.py ADDED
@@ -0,0 +1,1758 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The BAAI Teams 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 AltCLIP model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Any, List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.utils.checkpoint
24
+
25
+ from ...activations import ACT2FN
26
+ from ...modeling_outputs import (
27
+ BaseModelOutput,
28
+ BaseModelOutputWithPastAndCrossAttentions,
29
+ BaseModelOutputWithPooling,
30
+ BaseModelOutputWithPoolingAndCrossAttentions,
31
+ BaseModelOutputWithPoolingAndProjection,
32
+ )
33
+ from ...modeling_utils import PreTrainedModel
34
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
35
+ from ...utils import ModelOutput, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, torch_int
36
+ from .configuration_altclip import AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CHECKPOINT_FOR_DOC = "BAAI/AltCLIP"
42
+ _CONFIG_FOR_DOC = "AltCLIPConfig"
43
+
44
+
45
+ ALTCLIP_START_DOCSTRING = r"""
46
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
47
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
48
+ etc.)
49
+
50
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
51
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
52
+ and behavior.
53
+
54
+ Parameters:
55
+ config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
56
+ Initializing with a config file does not load the weights associated with the model, only the
57
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
58
+ """
59
+
60
+ ALTCLIP_TEXT_INPUTS_DOCSTRING = r"""
61
+ Args:
62
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
63
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
64
+ it.
65
+
66
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
67
+ [`PreTrainedTokenizer.__call__`] for details.
68
+
69
+ [What are input IDs?](../glossary#input-ids)
70
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
71
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
72
+
73
+ - 1 for tokens that are **not masked**,
74
+ - 0 for tokens that are **masked**.
75
+
76
+ [What are attention masks?](../glossary#attention-mask)
77
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
78
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
79
+ config.max_position_embeddings - 1]`.
80
+
81
+ [What are position IDs?](../glossary#position-ids)
82
+ output_attentions (`bool`, *optional*):
83
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
84
+ tensors for more detail.
85
+ output_hidden_states (`bool`, *optional*):
86
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
87
+ more detail.
88
+ return_dict (`bool`, *optional*):
89
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
90
+ """
91
+
92
+ ALTCLIP_VISION_INPUTS_DOCSTRING = r"""
93
+ Args:
94
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
95
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
96
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
97
+ output_attentions (`bool`, *optional*):
98
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
99
+ tensors for more detail.
100
+ output_hidden_states (`bool`, *optional*):
101
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
102
+ more detail.
103
+ interpolate_pos_encoding (`bool`, *optional*, defaults `False`):
104
+ Whether to interpolate the pre-trained position encodings.
105
+ return_dict (`bool`, *optional*):
106
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
107
+ """
108
+
109
+ ALTCLIP_INPUTS_DOCSTRING = r"""
110
+ Args:
111
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
112
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
113
+ it.
114
+
115
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
116
+ [`PreTrainedTokenizer.__call__`] for details.
117
+
118
+ [What are input IDs?](../glossary#input-ids)
119
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
120
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
121
+
122
+ - 1 for tokens that are **not masked**,
123
+ - 0 for tokens that are **masked**.
124
+
125
+ [What are attention masks?](../glossary#attention-mask)
126
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
127
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
128
+ config.max_position_embeddings - 1]`.
129
+
130
+ [What are position IDs?](../glossary#position-ids)
131
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
132
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
133
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
134
+ return_loss (`bool`, *optional*):
135
+ Whether or not to return the contrastive loss.
136
+ output_attentions (`bool`, *optional*):
137
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
138
+ tensors for more detail.
139
+ output_hidden_states (`bool`, *optional*):
140
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
141
+ more detail.
142
+ interpolate_pos_encoding (`bool`, *optional*, defaults `False`):
143
+ Whether to interpolate the pre-trained position encodings.
144
+ return_dict (`bool`, *optional*):
145
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
146
+ """
147
+
148
+
149
+ # contrastive loss function, adapted from
150
+ # https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
151
+ def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
152
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
153
+
154
+
155
+ def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
156
+ caption_loss = contrastive_loss(similarity)
157
+ image_loss = contrastive_loss(similarity.t())
158
+ return (caption_loss + image_loss) / 2.0
159
+
160
+
161
+ @dataclass
162
+ # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP
163
+ class AltCLIPOutput(ModelOutput):
164
+ """
165
+ Args:
166
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
167
+ Contrastive loss for image-text similarity.
168
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
169
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
170
+ similarity scores.
171
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
172
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
173
+ similarity scores.
174
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
175
+ The text embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPTextModel`].
176
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
177
+ The image embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPVisionModel`].
178
+ text_model_output (`BaseModelOutputWithPooling`):
179
+ The output of the [`AltCLIPTextModel`].
180
+ vision_model_output (`BaseModelOutputWithPooling`):
181
+ The output of the [`AltCLIPVisionModel`].
182
+ """
183
+
184
+ loss: Optional[torch.FloatTensor] = None
185
+ logits_per_image: torch.FloatTensor = None
186
+ logits_per_text: torch.FloatTensor = None
187
+ text_embeds: torch.FloatTensor = None
188
+ image_embeds: torch.FloatTensor = None
189
+ text_model_output: BaseModelOutputWithPooling = None
190
+ vision_model_output: BaseModelOutputWithPooling = None
191
+
192
+ def to_tuple(self) -> Tuple[Any]:
193
+ return tuple(
194
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
195
+ for k in self.keys()
196
+ )
197
+
198
+
199
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->AltRoberta
200
+ class AltRobertaEmbeddings(nn.Module):
201
+ """
202
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
203
+ """
204
+
205
+ # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
206
+ def __init__(self, config):
207
+ super().__init__()
208
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
209
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
210
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
211
+
212
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
213
+ # any TensorFlow checkpoint file
214
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
215
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
216
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
217
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
218
+ self.register_buffer(
219
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
220
+ )
221
+ self.register_buffer(
222
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
223
+ )
224
+
225
+ # End copy
226
+ self.padding_idx = config.pad_token_id
227
+ self.position_embeddings = nn.Embedding(
228
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
229
+ )
230
+
231
+ def forward(
232
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
233
+ ):
234
+ if position_ids is None:
235
+ if input_ids is not None:
236
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
237
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
238
+ else:
239
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
240
+
241
+ if input_ids is not None:
242
+ input_shape = input_ids.size()
243
+ else:
244
+ input_shape = inputs_embeds.size()[:-1]
245
+
246
+ seq_length = input_shape[1]
247
+
248
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
249
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
250
+ # issue #5664
251
+ if token_type_ids is None:
252
+ if hasattr(self, "token_type_ids"):
253
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
254
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
255
+ token_type_ids = buffered_token_type_ids_expanded
256
+ else:
257
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
258
+
259
+ if inputs_embeds is None:
260
+ inputs_embeds = self.word_embeddings(input_ids)
261
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
262
+
263
+ embeddings = inputs_embeds + token_type_embeddings
264
+ if self.position_embedding_type == "absolute":
265
+ position_embeddings = self.position_embeddings(position_ids)
266
+ embeddings += position_embeddings
267
+ embeddings = self.LayerNorm(embeddings)
268
+ embeddings = self.dropout(embeddings)
269
+ return embeddings
270
+
271
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
272
+ """
273
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
274
+
275
+ Args:
276
+ inputs_embeds: torch.Tensor
277
+
278
+ Returns: torch.Tensor
279
+ """
280
+ input_shape = inputs_embeds.size()[:-1]
281
+ sequence_length = input_shape[1]
282
+
283
+ position_ids = torch.arange(
284
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
285
+ )
286
+ return position_ids.unsqueeze(0).expand(input_shape)
287
+
288
+
289
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->AltRoberta
290
+ class AltRobertaSelfAttention(nn.Module):
291
+ def __init__(self, config, position_embedding_type=None):
292
+ super().__init__()
293
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
294
+ raise ValueError(
295
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
296
+ f"heads ({config.num_attention_heads})"
297
+ )
298
+
299
+ self.num_attention_heads = config.num_attention_heads
300
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
301
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
302
+
303
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
304
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
305
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
306
+
307
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
308
+ self.position_embedding_type = position_embedding_type or getattr(
309
+ config, "position_embedding_type", "absolute"
310
+ )
311
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
312
+ self.max_position_embeddings = config.max_position_embeddings
313
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
314
+
315
+ self.is_decoder = config.is_decoder
316
+
317
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
318
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
319
+ x = x.view(new_x_shape)
320
+ return x.permute(0, 2, 1, 3)
321
+
322
+ def forward(
323
+ self,
324
+ hidden_states: torch.Tensor,
325
+ attention_mask: Optional[torch.FloatTensor] = None,
326
+ head_mask: Optional[torch.FloatTensor] = None,
327
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
328
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
329
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
330
+ output_attentions: Optional[bool] = False,
331
+ ) -> Tuple[torch.Tensor]:
332
+ mixed_query_layer = self.query(hidden_states)
333
+
334
+ # If this is instantiated as a cross-attention module, the keys
335
+ # and values come from an encoder; the attention mask needs to be
336
+ # such that the encoder's padding tokens are not attended to.
337
+ is_cross_attention = encoder_hidden_states is not None
338
+
339
+ if is_cross_attention and past_key_value is not None:
340
+ # reuse k,v, cross_attentions
341
+ key_layer = past_key_value[0]
342
+ value_layer = past_key_value[1]
343
+ attention_mask = encoder_attention_mask
344
+ elif is_cross_attention:
345
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
346
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
347
+ attention_mask = encoder_attention_mask
348
+ elif past_key_value is not None:
349
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
350
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
351
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
352
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
353
+ else:
354
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
355
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
356
+
357
+ query_layer = self.transpose_for_scores(mixed_query_layer)
358
+
359
+ use_cache = past_key_value is not None
360
+ if self.is_decoder:
361
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
362
+ # Further calls to cross_attention layer can then reuse all cross-attention
363
+ # key/value_states (first "if" case)
364
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
365
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
366
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
367
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
368
+ past_key_value = (key_layer, value_layer)
369
+
370
+ # Take the dot product between "query" and "key" to get the raw attention scores.
371
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
372
+
373
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
374
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
375
+ if use_cache:
376
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
377
+ -1, 1
378
+ )
379
+ else:
380
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
381
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
382
+ distance = position_ids_l - position_ids_r
383
+
384
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
385
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
386
+
387
+ if self.position_embedding_type == "relative_key":
388
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
389
+ attention_scores = attention_scores + relative_position_scores
390
+ elif self.position_embedding_type == "relative_key_query":
391
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
392
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
393
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
394
+
395
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
396
+ if attention_mask is not None:
397
+ # Apply the attention mask is (precomputed for all layers in AltRobertaModel forward() function)
398
+ attention_scores = attention_scores + attention_mask
399
+
400
+ # Normalize the attention scores to probabilities.
401
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
402
+
403
+ # This is actually dropping out entire tokens to attend to, which might
404
+ # seem a bit unusual, but is taken from the original Transformer paper.
405
+ attention_probs = self.dropout(attention_probs)
406
+
407
+ # Mask heads if we want to
408
+ if head_mask is not None:
409
+ attention_probs = attention_probs * head_mask
410
+
411
+ context_layer = torch.matmul(attention_probs, value_layer)
412
+
413
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
414
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
415
+ context_layer = context_layer.view(new_context_layer_shape)
416
+
417
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
418
+
419
+ if self.is_decoder:
420
+ outputs = outputs + (past_key_value,)
421
+ return outputs
422
+
423
+
424
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput
425
+ class AltRobertaSelfOutput(nn.Module):
426
+ def __init__(self, config):
427
+ super().__init__()
428
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
429
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
430
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
431
+
432
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
433
+ hidden_states = self.dense(hidden_states)
434
+ hidden_states = self.dropout(hidden_states)
435
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
436
+ return hidden_states
437
+
438
+
439
+ ALT_ROBERTA_SELF_ATTENTION_CLASSES = {
440
+ "eager": AltRobertaSelfAttention,
441
+ }
442
+
443
+
444
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaAttention with Roberta->AltRoberta,ROBERTA->ALT_ROBERTA
445
+ class AltRobertaAttention(nn.Module):
446
+ def __init__(self, config, position_embedding_type=None):
447
+ super().__init__()
448
+ self.self = ALT_ROBERTA_SELF_ATTENTION_CLASSES[config._attn_implementation](
449
+ config, position_embedding_type=position_embedding_type
450
+ )
451
+ self.output = AltRobertaSelfOutput(config)
452
+ self.pruned_heads = set()
453
+
454
+ def prune_heads(self, heads):
455
+ if len(heads) == 0:
456
+ return
457
+ heads, index = find_pruneable_heads_and_indices(
458
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
459
+ )
460
+
461
+ # Prune linear layers
462
+ self.self.query = prune_linear_layer(self.self.query, index)
463
+ self.self.key = prune_linear_layer(self.self.key, index)
464
+ self.self.value = prune_linear_layer(self.self.value, index)
465
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
466
+
467
+ # Update hyper params and store pruned heads
468
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
469
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
470
+ self.pruned_heads = self.pruned_heads.union(heads)
471
+
472
+ def forward(
473
+ self,
474
+ hidden_states: torch.Tensor,
475
+ attention_mask: Optional[torch.FloatTensor] = None,
476
+ head_mask: Optional[torch.FloatTensor] = None,
477
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
478
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
479
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
480
+ output_attentions: Optional[bool] = False,
481
+ ) -> Tuple[torch.Tensor]:
482
+ self_outputs = self.self(
483
+ hidden_states,
484
+ attention_mask,
485
+ head_mask,
486
+ encoder_hidden_states,
487
+ encoder_attention_mask,
488
+ past_key_value,
489
+ output_attentions,
490
+ )
491
+ attention_output = self.output(self_outputs[0], hidden_states)
492
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
493
+ return outputs
494
+
495
+
496
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate with Roberta->AltRoberta
497
+ class AltRobertaIntermediate(nn.Module):
498
+ def __init__(self, config):
499
+ super().__init__()
500
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
501
+ if isinstance(config.hidden_act, str):
502
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
503
+ else:
504
+ self.intermediate_act_fn = config.hidden_act
505
+
506
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
507
+ hidden_states = self.dense(hidden_states)
508
+ hidden_states = self.intermediate_act_fn(hidden_states)
509
+ return hidden_states
510
+
511
+
512
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaOutput
513
+ class AltRobertaOutput(nn.Module):
514
+ def __init__(self, config):
515
+ super().__init__()
516
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
517
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
518
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
519
+
520
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
521
+ hidden_states = self.dense(hidden_states)
522
+ hidden_states = self.dropout(hidden_states)
523
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
524
+ return hidden_states
525
+
526
+
527
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaLayer with Roberta->AltRoberta
528
+ class AltRobertaLayer(nn.Module):
529
+ def __init__(self, config):
530
+ super().__init__()
531
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
532
+ self.seq_len_dim = 1
533
+ self.attention = AltRobertaAttention(config)
534
+ self.is_decoder = config.is_decoder
535
+ self.add_cross_attention = config.add_cross_attention
536
+ if self.add_cross_attention:
537
+ if not self.is_decoder:
538
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
539
+ self.crossattention = AltRobertaAttention(config, position_embedding_type="absolute")
540
+ self.intermediate = AltRobertaIntermediate(config)
541
+ self.output = AltRobertaOutput(config)
542
+
543
+ def forward(
544
+ self,
545
+ hidden_states: torch.Tensor,
546
+ attention_mask: Optional[torch.FloatTensor] = None,
547
+ head_mask: Optional[torch.FloatTensor] = None,
548
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
549
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
550
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
551
+ output_attentions: Optional[bool] = False,
552
+ ) -> Tuple[torch.Tensor]:
553
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
554
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
555
+ self_attention_outputs = self.attention(
556
+ hidden_states,
557
+ attention_mask,
558
+ head_mask,
559
+ output_attentions=output_attentions,
560
+ past_key_value=self_attn_past_key_value,
561
+ )
562
+ attention_output = self_attention_outputs[0]
563
+
564
+ # if decoder, the last output is tuple of self-attn cache
565
+ if self.is_decoder:
566
+ outputs = self_attention_outputs[1:-1]
567
+ present_key_value = self_attention_outputs[-1]
568
+ else:
569
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
570
+
571
+ cross_attn_present_key_value = None
572
+ if self.is_decoder and encoder_hidden_states is not None:
573
+ if not hasattr(self, "crossattention"):
574
+ raise ValueError(
575
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
576
+ " by setting `config.add_cross_attention=True`"
577
+ )
578
+
579
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
580
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
581
+ cross_attention_outputs = self.crossattention(
582
+ attention_output,
583
+ attention_mask,
584
+ head_mask,
585
+ encoder_hidden_states,
586
+ encoder_attention_mask,
587
+ cross_attn_past_key_value,
588
+ output_attentions,
589
+ )
590
+ attention_output = cross_attention_outputs[0]
591
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
592
+
593
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
594
+ cross_attn_present_key_value = cross_attention_outputs[-1]
595
+ present_key_value = present_key_value + cross_attn_present_key_value
596
+
597
+ layer_output = apply_chunking_to_forward(
598
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
599
+ )
600
+ outputs = (layer_output,) + outputs
601
+
602
+ # if decoder, return the attn key/values as the last output
603
+ if self.is_decoder:
604
+ outputs = outputs + (present_key_value,)
605
+
606
+ return outputs
607
+
608
+ def feed_forward_chunk(self, attention_output):
609
+ intermediate_output = self.intermediate(attention_output)
610
+ layer_output = self.output(intermediate_output, attention_output)
611
+ return layer_output
612
+
613
+
614
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->AltRoberta
615
+ class AltRobertaEncoder(nn.Module):
616
+ def __init__(self, config):
617
+ super().__init__()
618
+ self.config = config
619
+ self.layer = nn.ModuleList([AltRobertaLayer(config) for _ in range(config.num_hidden_layers)])
620
+ self.gradient_checkpointing = False
621
+
622
+ def forward(
623
+ self,
624
+ hidden_states: torch.Tensor,
625
+ attention_mask: Optional[torch.FloatTensor] = None,
626
+ head_mask: Optional[torch.FloatTensor] = None,
627
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
628
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
629
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
630
+ use_cache: Optional[bool] = None,
631
+ output_attentions: Optional[bool] = False,
632
+ output_hidden_states: Optional[bool] = False,
633
+ return_dict: Optional[bool] = True,
634
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
635
+ all_hidden_states = () if output_hidden_states else None
636
+ all_self_attentions = () if output_attentions else None
637
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
638
+
639
+ if self.gradient_checkpointing and self.training:
640
+ if use_cache:
641
+ logger.warning_once(
642
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
643
+ )
644
+ use_cache = False
645
+
646
+ next_decoder_cache = () if use_cache else None
647
+ for i, layer_module in enumerate(self.layer):
648
+ if output_hidden_states:
649
+ all_hidden_states = all_hidden_states + (hidden_states,)
650
+
651
+ layer_head_mask = head_mask[i] if head_mask is not None else None
652
+ past_key_value = past_key_values[i] if past_key_values is not None else None
653
+
654
+ if self.gradient_checkpointing and self.training:
655
+ layer_outputs = self._gradient_checkpointing_func(
656
+ layer_module.__call__,
657
+ hidden_states,
658
+ attention_mask,
659
+ layer_head_mask,
660
+ encoder_hidden_states,
661
+ encoder_attention_mask,
662
+ past_key_value,
663
+ output_attentions,
664
+ )
665
+ else:
666
+ layer_outputs = layer_module(
667
+ hidden_states,
668
+ attention_mask,
669
+ layer_head_mask,
670
+ encoder_hidden_states,
671
+ encoder_attention_mask,
672
+ past_key_value,
673
+ output_attentions,
674
+ )
675
+
676
+ hidden_states = layer_outputs[0]
677
+ if use_cache:
678
+ next_decoder_cache += (layer_outputs[-1],)
679
+ if output_attentions:
680
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
681
+ if self.config.add_cross_attention:
682
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
683
+
684
+ if output_hidden_states:
685
+ all_hidden_states = all_hidden_states + (hidden_states,)
686
+
687
+ if not return_dict:
688
+ return tuple(
689
+ v
690
+ for v in [
691
+ hidden_states,
692
+ next_decoder_cache,
693
+ all_hidden_states,
694
+ all_self_attentions,
695
+ all_cross_attentions,
696
+ ]
697
+ if v is not None
698
+ )
699
+ return BaseModelOutputWithPastAndCrossAttentions(
700
+ last_hidden_state=hidden_states,
701
+ past_key_values=next_decoder_cache,
702
+ hidden_states=all_hidden_states,
703
+ attentions=all_self_attentions,
704
+ cross_attentions=all_cross_attentions,
705
+ )
706
+
707
+
708
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
709
+ class AltRobertaPooler(nn.Module):
710
+ def __init__(self, config):
711
+ super().__init__()
712
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
713
+ self.activation = nn.Tanh()
714
+
715
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
716
+ # We "pool" the model by simply taking the hidden state corresponding
717
+ # to the first token.
718
+ first_token_tensor = hidden_states[:, 0]
719
+ pooled_output = self.dense(first_token_tensor)
720
+ pooled_output = self.activation(pooled_output)
721
+ return pooled_output
722
+
723
+
724
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention with CLIP->AltCLIP
725
+ class AltCLIPAttention(nn.Module):
726
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
727
+
728
+ def __init__(self, config):
729
+ super().__init__()
730
+ self.config = config
731
+ self.embed_dim = config.hidden_size
732
+ self.num_heads = config.num_attention_heads
733
+ self.head_dim = self.embed_dim // self.num_heads
734
+ if self.head_dim * self.num_heads != self.embed_dim:
735
+ raise ValueError(
736
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
737
+ f" {self.num_heads})."
738
+ )
739
+ self.scale = self.head_dim**-0.5
740
+ self.dropout = config.attention_dropout
741
+
742
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
743
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
744
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
745
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
746
+
747
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
748
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
749
+
750
+ def forward(
751
+ self,
752
+ hidden_states: torch.Tensor,
753
+ attention_mask: Optional[torch.Tensor] = None,
754
+ causal_attention_mask: Optional[torch.Tensor] = None,
755
+ output_attentions: Optional[bool] = False,
756
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
757
+ """Input shape: Batch x Time x Channel"""
758
+
759
+ bsz, tgt_len, embed_dim = hidden_states.size()
760
+
761
+ # get query proj
762
+ query_states = self.q_proj(hidden_states) * self.scale
763
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
764
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
765
+
766
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
767
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
768
+ key_states = key_states.view(*proj_shape)
769
+ value_states = value_states.view(*proj_shape)
770
+
771
+ src_len = key_states.size(1)
772
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
773
+
774
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
775
+ raise ValueError(
776
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
777
+ f" {attn_weights.size()}"
778
+ )
779
+
780
+ # apply the causal_attention_mask first
781
+ if causal_attention_mask is not None:
782
+ if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
783
+ raise ValueError(
784
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
785
+ f" {causal_attention_mask.size()}"
786
+ )
787
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
788
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
789
+
790
+ if attention_mask is not None:
791
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
792
+ raise ValueError(
793
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
794
+ )
795
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
796
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
797
+
798
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
799
+
800
+ if output_attentions:
801
+ # this operation is a bit akward, but it's required to
802
+ # make sure that attn_weights keeps its gradient.
803
+ # In order to do so, attn_weights have to reshaped
804
+ # twice and have to be reused in the following
805
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
806
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
807
+ else:
808
+ attn_weights_reshaped = None
809
+
810
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
811
+
812
+ attn_output = torch.bmm(attn_probs, value_states)
813
+
814
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
815
+ raise ValueError(
816
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
817
+ f" {attn_output.size()}"
818
+ )
819
+
820
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
821
+ attn_output = attn_output.transpose(1, 2)
822
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
823
+
824
+ attn_output = self.out_proj(attn_output)
825
+
826
+ return attn_output, attn_weights_reshaped
827
+
828
+
829
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->AltCLIP
830
+ class AltCLIPMLP(nn.Module):
831
+ def __init__(self, config):
832
+ super().__init__()
833
+ self.config = config
834
+ self.activation_fn = ACT2FN[config.hidden_act]
835
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
836
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
837
+
838
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
839
+ hidden_states = self.fc1(hidden_states)
840
+ hidden_states = self.activation_fn(hidden_states)
841
+ hidden_states = self.fc2(hidden_states)
842
+ return hidden_states
843
+
844
+
845
+ class AltCLIPEncoderLayer(nn.Module):
846
+ def __init__(self, config: AltCLIPConfig):
847
+ super().__init__()
848
+ self.embed_dim = config.hidden_size
849
+ self.self_attn = AltCLIPAttention(config)
850
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
851
+ self.mlp = AltCLIPMLP(config)
852
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
853
+
854
+ def forward(
855
+ self,
856
+ hidden_states: torch.Tensor,
857
+ attention_mask: torch.Tensor,
858
+ causal_attention_mask: torch.Tensor,
859
+ output_attentions: Optional[bool] = False,
860
+ ) -> Tuple[torch.FloatTensor]:
861
+ """
862
+ Args:
863
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
864
+ attention_mask (`torch.FloatTensor`): attention mask of size
865
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
866
+ `(config.encoder_attention_heads,)`.
867
+ output_attentions (`bool`, *optional*):
868
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
869
+ returned tensors for more detail.
870
+ """
871
+ residual = hidden_states
872
+
873
+ hidden_states = self.layer_norm1(hidden_states)
874
+ hidden_states, attn_weights = self.self_attn(
875
+ hidden_states=hidden_states,
876
+ attention_mask=attention_mask,
877
+ causal_attention_mask=causal_attention_mask,
878
+ output_attentions=output_attentions,
879
+ )
880
+ hidden_states = residual + hidden_states
881
+
882
+ residual = hidden_states
883
+ hidden_states = self.layer_norm2(hidden_states)
884
+ hidden_states = self.mlp(hidden_states)
885
+ hidden_states = residual + hidden_states
886
+
887
+ outputs = (hidden_states,)
888
+
889
+ if output_attentions:
890
+ outputs += (attn_weights,)
891
+
892
+ return outputs
893
+
894
+
895
+ class AltCLIPEncoder(nn.Module):
896
+ """
897
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
898
+ [`AltCLIPEncoderLayer`].
899
+
900
+ Args:
901
+ config: AltCLIPConfig
902
+ """
903
+
904
+ def __init__(self, config: AltCLIPConfig):
905
+ super().__init__()
906
+ self.config = config
907
+ self.layers = nn.ModuleList([AltCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
908
+ self.gradient_checkpointing = False
909
+
910
+ def forward(
911
+ self,
912
+ inputs_embeds,
913
+ attention_mask: Optional[torch.Tensor] = None,
914
+ causal_attention_mask: Optional[torch.Tensor] = None,
915
+ output_attentions: Optional[bool] = None,
916
+ output_hidden_states: Optional[bool] = None,
917
+ return_dict: Optional[bool] = None,
918
+ ) -> Union[Tuple, BaseModelOutput]:
919
+ r"""
920
+ Args:
921
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
922
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
923
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
924
+ than the model's internal embedding lookup matrix.
925
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
926
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
927
+
928
+ - 1 for tokens that are **not masked**,
929
+ - 0 for tokens that are **masked**.
930
+
931
+ [What are attention masks?](../glossary#attention-mask)
932
+ causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
933
+ Causal mask for the text model. Mask values selected in `[0, 1]`:
934
+
935
+ - 1 for tokens that are **not masked**,
936
+ - 0 for tokens that are **masked**.
937
+
938
+ [What are attention masks?](../glossary#attention-mask)
939
+ output_attentions (`bool`, *optional*):
940
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
941
+ returned tensors for more detail.
942
+ output_hidden_states (`bool`, *optional*):
943
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
944
+ for more detail.
945
+ return_dict (`bool`, *optional*):
946
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
947
+ """
948
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
949
+ output_hidden_states = (
950
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
951
+ )
952
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
953
+
954
+ encoder_states = () if output_hidden_states else None
955
+ all_attentions = () if output_attentions else None
956
+
957
+ hidden_states = inputs_embeds
958
+ for idx, encoder_layer in enumerate(self.layers):
959
+ if output_hidden_states:
960
+ encoder_states = encoder_states + (hidden_states,)
961
+ if self.gradient_checkpointing and self.training:
962
+ layer_outputs = self._gradient_checkpointing_func(
963
+ encoder_layer.__call__,
964
+ hidden_states,
965
+ attention_mask,
966
+ causal_attention_mask,
967
+ output_attentions,
968
+ )
969
+ else:
970
+ layer_outputs = encoder_layer(
971
+ hidden_states,
972
+ attention_mask,
973
+ causal_attention_mask,
974
+ output_attentions=output_attentions,
975
+ )
976
+
977
+ hidden_states = layer_outputs[0]
978
+
979
+ if output_attentions:
980
+ all_attentions = all_attentions + (layer_outputs[1],)
981
+
982
+ if output_hidden_states:
983
+ encoder_states = encoder_states + (hidden_states,)
984
+
985
+ if not return_dict:
986
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
987
+ return BaseModelOutput(
988
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
989
+ )
990
+
991
+
992
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->AltCLIP
993
+ class AltCLIPVisionEmbeddings(nn.Module):
994
+ def __init__(self, config: AltCLIPVisionConfig):
995
+ super().__init__()
996
+ self.config = config
997
+ self.embed_dim = config.hidden_size
998
+ self.image_size = config.image_size
999
+ self.patch_size = config.patch_size
1000
+
1001
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
1002
+
1003
+ self.patch_embedding = nn.Conv2d(
1004
+ in_channels=config.num_channels,
1005
+ out_channels=self.embed_dim,
1006
+ kernel_size=self.patch_size,
1007
+ stride=self.patch_size,
1008
+ bias=False,
1009
+ )
1010
+
1011
+ self.num_patches = (self.image_size // self.patch_size) ** 2
1012
+ self.num_positions = self.num_patches + 1
1013
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
1014
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
1015
+
1016
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
1017
+ """
1018
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
1019
+ images. This method is also adapted to support torch.jit tracing.
1020
+
1021
+ Adapted from:
1022
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
1023
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
1024
+ """
1025
+
1026
+ num_patches = embeddings.shape[1] - 1
1027
+ position_embedding = self.position_embedding.weight.unsqueeze(0)
1028
+ num_positions = position_embedding.shape[1] - 1
1029
+
1030
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
1031
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
1032
+ return self.position_embedding(self.position_ids)
1033
+
1034
+ class_pos_embed = position_embedding[:, :1]
1035
+ patch_pos_embed = position_embedding[:, 1:]
1036
+
1037
+ dim = embeddings.shape[-1]
1038
+
1039
+ new_height = height // self.patch_size
1040
+ new_width = width // self.patch_size
1041
+
1042
+ sqrt_num_positions = torch_int(num_positions**0.5)
1043
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
1044
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
1045
+
1046
+ patch_pos_embed = nn.functional.interpolate(
1047
+ patch_pos_embed,
1048
+ size=(new_height, new_width),
1049
+ mode="bicubic",
1050
+ align_corners=False,
1051
+ )
1052
+
1053
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
1054
+
1055
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
1056
+
1057
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
1058
+ batch_size, _, height, width = pixel_values.shape
1059
+ if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
1060
+ raise ValueError(
1061
+ f"Input image size ({height}*{width}) doesn't match model" f" ({self.image_size}*{self.image_size})."
1062
+ )
1063
+ target_dtype = self.patch_embedding.weight.dtype
1064
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
1065
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
1066
+
1067
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
1068
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
1069
+ if interpolate_pos_encoding:
1070
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
1071
+ else:
1072
+ embeddings = embeddings + self.position_embedding(self.position_ids)
1073
+ return embeddings
1074
+
1075
+
1076
+ class AltCLIPPreTrainedModel(PreTrainedModel):
1077
+ """
1078
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1079
+ models.
1080
+ """
1081
+
1082
+ config_class = AltCLIPConfig
1083
+ base_model_prefix = "altclip"
1084
+ supports_gradient_checkpointing = True
1085
+ _no_split_module = []
1086
+
1087
+ def _init_weights(self, module):
1088
+ """Initialize the weights"""
1089
+ factor = self.config.initializer_factor
1090
+ if isinstance(module, AltCLIPVisionEmbeddings):
1091
+ factor = self.config.initializer_factor
1092
+ nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
1093
+ nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
1094
+ nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
1095
+ elif isinstance(module, AltCLIPAttention):
1096
+ factor = self.config.initializer_factor
1097
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
1098
+ out_proj_std = (module.embed_dim**-0.5) * factor
1099
+ nn.init.normal_(module.q_proj.weight, std=in_proj_std)
1100
+ nn.init.normal_(module.k_proj.weight, std=in_proj_std)
1101
+ nn.init.normal_(module.v_proj.weight, std=in_proj_std)
1102
+ nn.init.normal_(module.out_proj.weight, std=out_proj_std)
1103
+ elif isinstance(module, AltCLIPMLP):
1104
+ factor = self.config.initializer_factor
1105
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
1106
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
1107
+ nn.init.normal_(module.fc1.weight, std=fc_std)
1108
+ nn.init.normal_(module.fc2.weight, std=in_proj_std)
1109
+ elif isinstance(module, AltCLIPModel):
1110
+ nn.init.normal_(
1111
+ module.text_projection.weight,
1112
+ std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
1113
+ )
1114
+ module.text_projection._is_hf_initialized = True
1115
+ nn.init.normal_(
1116
+ module.visual_projection.weight,
1117
+ std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
1118
+ )
1119
+ module.visual_projection._is_hf_initialized = True
1120
+ elif isinstance(module, nn.LayerNorm):
1121
+ module.bias.data.zero_()
1122
+ module.weight.data.fill_(1.0)
1123
+ elif isinstance(module, nn.Linear):
1124
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
1125
+ if module.bias is not None:
1126
+ module.bias.data.zero_()
1127
+ elif isinstance(module, nn.Embedding):
1128
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
1129
+ if module.padding_idx is not None:
1130
+ module.weight.data[module.padding_idx].zero_()
1131
+
1132
+
1133
+ class AltCLIPVisionTransformer(nn.Module):
1134
+ def __init__(self, config: AltCLIPVisionConfig):
1135
+ super().__init__()
1136
+ self.config = config
1137
+ embed_dim = config.hidden_size
1138
+
1139
+ self.embeddings = AltCLIPVisionEmbeddings(config)
1140
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1141
+ self.encoder = AltCLIPEncoder(config)
1142
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
1143
+
1144
+ @add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
1145
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=AltCLIPVisionConfig)
1146
+ def forward(
1147
+ self,
1148
+ pixel_values: Optional[torch.FloatTensor] = None,
1149
+ output_attentions: Optional[bool] = None,
1150
+ output_hidden_states: Optional[bool] = None,
1151
+ return_dict: Optional[bool] = None,
1152
+ interpolate_pos_encoding: Optional[bool] = False,
1153
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1154
+ r"""
1155
+ Returns:
1156
+
1157
+ """
1158
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1159
+ output_hidden_states = (
1160
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1161
+ )
1162
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1163
+
1164
+ if pixel_values is None:
1165
+ raise ValueError("You have to specify pixel_values")
1166
+
1167
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
1168
+ hidden_states = self.pre_layrnorm(hidden_states)
1169
+
1170
+ encoder_outputs = self.encoder(
1171
+ inputs_embeds=hidden_states,
1172
+ output_attentions=output_attentions,
1173
+ output_hidden_states=output_hidden_states,
1174
+ return_dict=return_dict,
1175
+ )
1176
+
1177
+ last_hidden_state = encoder_outputs[0]
1178
+ pooled_output = last_hidden_state[:, 0, :]
1179
+ pooled_output = self.post_layernorm(pooled_output)
1180
+
1181
+ if not return_dict:
1182
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
1183
+
1184
+ return BaseModelOutputWithPooling(
1185
+ last_hidden_state=last_hidden_state,
1186
+ pooler_output=pooled_output,
1187
+ hidden_states=encoder_outputs.hidden_states,
1188
+ attentions=encoder_outputs.attentions,
1189
+ )
1190
+
1191
+
1192
+ class AltCLIPVisionModel(AltCLIPPreTrainedModel):
1193
+ config_class = AltCLIPVisionConfig
1194
+ main_input_name = "pixel_values"
1195
+
1196
+ def __init__(self, config: AltCLIPVisionConfig):
1197
+ super().__init__(config)
1198
+ self.vision_model = AltCLIPVisionTransformer(config)
1199
+ # Initialize weights and apply final processing
1200
+ self.post_init()
1201
+
1202
+ def get_input_embeddings(self) -> nn.Module:
1203
+ return self.vision_model.embeddings.patch_embedding
1204
+
1205
+ @add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
1206
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=AltCLIPVisionConfig)
1207
+ def forward(
1208
+ self,
1209
+ pixel_values: Optional[torch.FloatTensor] = None,
1210
+ output_attentions: Optional[bool] = None,
1211
+ output_hidden_states: Optional[bool] = None,
1212
+ interpolate_pos_encoding: bool = False,
1213
+ return_dict: Optional[bool] = None,
1214
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
1215
+ r"""
1216
+ Returns:
1217
+
1218
+ Examples:
1219
+
1220
+ ```python
1221
+ >>> from PIL import Image
1222
+ >>> import requests
1223
+ >>> from transformers import AutoProcessor, AltCLIPVisionModel
1224
+
1225
+ >>> model = AltCLIPVisionModel.from_pretrained("BAAI/AltCLIP")
1226
+ >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
1227
+
1228
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1229
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1230
+
1231
+ >>> inputs = processor(images=image, return_tensors="pt")
1232
+
1233
+ >>> outputs = model(**inputs)
1234
+ >>> last_hidden_state = outputs.last_hidden_state
1235
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
1236
+ ```"""
1237
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1238
+
1239
+ return self.vision_model(
1240
+ pixel_values=pixel_values,
1241
+ output_attentions=output_attentions,
1242
+ output_hidden_states=output_hidden_states,
1243
+ interpolate_pos_encoding=interpolate_pos_encoding,
1244
+ return_dict=return_dict,
1245
+ )
1246
+
1247
+
1248
+ class AltRobertaModel(AltCLIPPreTrainedModel):
1249
+ """
1250
+
1251
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
1252
+ cross-attention is added between the self-attention layers, following the architecture described in *Attention is
1253
+ all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
1254
+ Kaiser and Illia Polosukhin.
1255
+
1256
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
1257
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
1258
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
1259
+
1260
+ .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
1261
+
1262
+ """
1263
+
1264
+ config_class = AltCLIPTextConfig
1265
+
1266
+ # Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->AltRoberta
1267
+ def __init__(self, config, add_pooling_layer=True):
1268
+ super().__init__(config)
1269
+ self.config = config
1270
+
1271
+ self.embeddings = AltRobertaEmbeddings(config)
1272
+ self.encoder = AltRobertaEncoder(config)
1273
+
1274
+ self.pooler = AltRobertaPooler(config) if add_pooling_layer else None
1275
+
1276
+ # Initialize weights and apply final processing
1277
+ self.post_init()
1278
+
1279
+ def get_input_embeddings(self):
1280
+ return self.embeddings.word_embeddings
1281
+
1282
+ def set_input_embeddings(self, value):
1283
+ self.embeddings.word_embeddings = value
1284
+
1285
+ def _prune_heads(self, heads_to_prune):
1286
+ """
1287
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1288
+ class PreTrainedModel
1289
+ """
1290
+ for layer, heads in heads_to_prune.items():
1291
+ self.encoder.layer[layer].attention.prune_heads(heads)
1292
+
1293
+ # Copied from transformers.models.clap.modeling_clap.ClapTextModel.forward
1294
+ def forward(
1295
+ self,
1296
+ input_ids: Optional[torch.Tensor] = None,
1297
+ attention_mask: Optional[torch.Tensor] = None,
1298
+ token_type_ids: Optional[torch.Tensor] = None,
1299
+ position_ids: Optional[torch.Tensor] = None,
1300
+ head_mask: Optional[torch.Tensor] = None,
1301
+ inputs_embeds: Optional[torch.Tensor] = None,
1302
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1303
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1304
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1305
+ use_cache: Optional[bool] = None,
1306
+ output_attentions: Optional[bool] = None,
1307
+ output_hidden_states: Optional[bool] = None,
1308
+ return_dict: Optional[bool] = None,
1309
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
1310
+ r"""
1311
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1312
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1313
+ the model is configured as a decoder.
1314
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1315
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1316
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1317
+
1318
+ - 1 for tokens that are **not masked**,
1319
+ - 0 for tokens that are **masked**.
1320
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
1321
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1322
+
1323
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1324
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1325
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1326
+ use_cache (`bool`, *optional*):
1327
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1328
+ `past_key_values`).
1329
+ """
1330
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1331
+ output_hidden_states = (
1332
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1333
+ )
1334
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1335
+
1336
+ if self.config.is_decoder:
1337
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1338
+ else:
1339
+ use_cache = False
1340
+
1341
+ if input_ids is not None and inputs_embeds is not None:
1342
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1343
+ elif input_ids is not None:
1344
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1345
+ input_shape = input_ids.size()
1346
+ elif inputs_embeds is not None:
1347
+ input_shape = inputs_embeds.size()[:-1]
1348
+ else:
1349
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1350
+
1351
+ batch_size, seq_length = input_shape
1352
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1353
+
1354
+ # past_key_values_length
1355
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1356
+
1357
+ if attention_mask is None:
1358
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
1359
+
1360
+ if token_type_ids is None:
1361
+ if hasattr(self.embeddings, "token_type_ids"):
1362
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
1363
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
1364
+ token_type_ids = buffered_token_type_ids_expanded
1365
+ else:
1366
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
1367
+
1368
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
1369
+ # ourselves in which case we just need to make it broadcastable to all heads.
1370
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
1371
+
1372
+ # If a 2D or 3D attention mask is provided for the cross-attention
1373
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1374
+ if self.config.is_decoder and encoder_hidden_states is not None:
1375
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1376
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1377
+ if encoder_attention_mask is None:
1378
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1379
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1380
+ else:
1381
+ encoder_extended_attention_mask = None
1382
+
1383
+ # Prepare head mask if needed
1384
+ # 1.0 in head_mask indicate we keep the head
1385
+ # attention_probs has shape bsz x n_heads x N x N
1386
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1387
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1388
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1389
+
1390
+ embedding_output = self.embeddings(
1391
+ input_ids=input_ids,
1392
+ position_ids=position_ids,
1393
+ token_type_ids=token_type_ids,
1394
+ inputs_embeds=inputs_embeds,
1395
+ past_key_values_length=past_key_values_length,
1396
+ )
1397
+ encoder_outputs = self.encoder(
1398
+ embedding_output,
1399
+ attention_mask=extended_attention_mask,
1400
+ head_mask=head_mask,
1401
+ encoder_hidden_states=encoder_hidden_states,
1402
+ encoder_attention_mask=encoder_extended_attention_mask,
1403
+ past_key_values=past_key_values,
1404
+ use_cache=use_cache,
1405
+ output_attentions=output_attentions,
1406
+ output_hidden_states=output_hidden_states,
1407
+ return_dict=return_dict,
1408
+ )
1409
+ sequence_output = encoder_outputs[0]
1410
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1411
+
1412
+ if not return_dict:
1413
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1414
+
1415
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1416
+ last_hidden_state=sequence_output,
1417
+ pooler_output=pooled_output,
1418
+ past_key_values=encoder_outputs.past_key_values,
1419
+ hidden_states=encoder_outputs.hidden_states,
1420
+ attentions=encoder_outputs.attentions,
1421
+ cross_attentions=encoder_outputs.cross_attentions,
1422
+ )
1423
+
1424
+
1425
+ class AltCLIPTextModel(AltCLIPPreTrainedModel):
1426
+ config_class = AltCLIPTextConfig
1427
+
1428
+ def __init__(self, config):
1429
+ super().__init__(config)
1430
+ self.roberta = AltRobertaModel(config, add_pooling_layer=False)
1431
+ self.transformation = nn.Linear(config.hidden_size, config.project_dim)
1432
+ self.pre_LN = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1433
+ self.post_init()
1434
+
1435
+ def get_input_embeddings(self) -> nn.Module:
1436
+ return self.roberta.embeddings.word_embeddings
1437
+
1438
+ def set_input_embeddings(self, value: nn.Embedding) -> None:
1439
+ self.roberta.embeddings.word_embeddings = value
1440
+
1441
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
1442
+ return super().resize_token_embeddings(new_num_tokens)
1443
+
1444
+ @add_start_docstrings_to_model_forward(ALTCLIP_TEXT_INPUTS_DOCSTRING)
1445
+ @replace_return_docstrings(output_type=BaseModelOutputWithPoolingAndProjection, config_class=AltCLIPTextConfig)
1446
+ def forward(
1447
+ self,
1448
+ input_ids: Optional[torch.Tensor] = None,
1449
+ attention_mask: Optional[torch.Tensor] = None,
1450
+ token_type_ids: Optional[torch.Tensor] = None,
1451
+ position_ids: Optional[torch.Tensor] = None,
1452
+ head_mask: Optional[torch.Tensor] = None,
1453
+ inputs_embeds: Optional[torch.Tensor] = None,
1454
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1455
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1456
+ output_attentions: Optional[bool] = None,
1457
+ return_dict: Optional[bool] = None,
1458
+ output_hidden_states: Optional[bool] = None,
1459
+ ) -> Union[Tuple, BaseModelOutputWithPoolingAndProjection]:
1460
+ r"""
1461
+ Returns:
1462
+
1463
+ Examples:
1464
+
1465
+ ```python
1466
+ >>> from transformers import AutoProcessor, AltCLIPTextModel
1467
+
1468
+ >>> model = AltCLIPTextModel.from_pretrained("BAAI/AltCLIP")
1469
+ >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
1470
+
1471
+ >>> texts = ["it's a cat", "it's a dog"]
1472
+
1473
+ >>> inputs = processor(text=texts, padding=True, return_tensors="pt")
1474
+
1475
+ >>> outputs = model(**inputs)
1476
+ >>> last_hidden_state = outputs.last_hidden_state
1477
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
1478
+ ```"""
1479
+
1480
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1481
+
1482
+ outputs = self.roberta(
1483
+ input_ids=input_ids,
1484
+ attention_mask=attention_mask,
1485
+ token_type_ids=token_type_ids,
1486
+ position_ids=position_ids,
1487
+ head_mask=head_mask,
1488
+ inputs_embeds=inputs_embeds,
1489
+ encoder_hidden_states=encoder_hidden_states,
1490
+ encoder_attention_mask=encoder_attention_mask,
1491
+ output_attentions=output_attentions,
1492
+ output_hidden_states=output_hidden_states,
1493
+ return_dict=return_dict,
1494
+ )
1495
+
1496
+ # last module outputs
1497
+ sequence_output = outputs[0]
1498
+
1499
+ # project every module
1500
+ sequence_output = self.pre_LN(sequence_output)
1501
+
1502
+ # pooler
1503
+ projection_state = self.transformation(sequence_output)
1504
+ pooler_output = projection_state[:, 0]
1505
+
1506
+ if not return_dict:
1507
+ return (projection_state, pooler_output) + outputs[2:4]
1508
+
1509
+ return BaseModelOutputWithPoolingAndProjection(
1510
+ last_hidden_state=projection_state,
1511
+ pooler_output=pooler_output,
1512
+ hidden_states=outputs.hidden_states,
1513
+ attentions=outputs.attentions,
1514
+ )
1515
+
1516
+
1517
+ class AltCLIPModel(AltCLIPPreTrainedModel):
1518
+ config_class = AltCLIPConfig
1519
+
1520
+ def __init__(self, config: AltCLIPConfig):
1521
+ super().__init__(config)
1522
+
1523
+ if not isinstance(config.vision_config, AltCLIPVisionConfig):
1524
+ raise TypeError(
1525
+ "config.vision_config is expected to be of type AltCLIPVisionConfig but is of type"
1526
+ f" {type(config.vision_config)}."
1527
+ )
1528
+ if not isinstance(config.text_config, AltCLIPTextConfig):
1529
+ raise TypeError(
1530
+ "config.text_config is expected to be of type AltCLIPTextConfig but is of type"
1531
+ f" {type(config.text_config)}."
1532
+ )
1533
+
1534
+ text_config = config.text_config
1535
+ vision_config = config.vision_config
1536
+
1537
+ self.projection_dim = config.projection_dim
1538
+ self.text_embed_dim = text_config.project_dim
1539
+ self.vision_embed_dim = vision_config.hidden_size
1540
+
1541
+ self.text_model = AltCLIPTextModel(text_config)
1542
+ self.vision_model = AltCLIPVisionTransformer(vision_config)
1543
+
1544
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
1545
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
1546
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
1547
+
1548
+ # Initialize weights and apply final processing
1549
+ self.post_init()
1550
+
1551
+ @add_start_docstrings_to_model_forward(ALTCLIP_TEXT_INPUTS_DOCSTRING)
1552
+ def get_text_features(
1553
+ self,
1554
+ input_ids: Optional[torch.Tensor] = None,
1555
+ attention_mask: Optional[torch.Tensor] = None,
1556
+ position_ids: Optional[torch.Tensor] = None,
1557
+ token_type_ids=None,
1558
+ output_attentions: Optional[bool] = None,
1559
+ output_hidden_states: Optional[bool] = None,
1560
+ return_dict: Optional[bool] = None,
1561
+ ) -> torch.FloatTensor:
1562
+ r"""
1563
+ Returns:
1564
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
1565
+ applying the projection layer to the pooled output of [`AltCLIPTextModel`].
1566
+
1567
+ Examples:
1568
+
1569
+ ```python
1570
+ >>> from transformers import AutoProcessor, AltCLIPModel
1571
+
1572
+ >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
1573
+ >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
1574
+ >>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
1575
+ >>> text_features = model.get_text_features(**inputs)
1576
+ ```"""
1577
+ # Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
1578
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1579
+ output_hidden_states = (
1580
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1581
+ )
1582
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1583
+
1584
+ text_outputs = self.text_model(
1585
+ input_ids=input_ids,
1586
+ attention_mask=attention_mask,
1587
+ position_ids=position_ids,
1588
+ token_type_ids=token_type_ids,
1589
+ output_attentions=output_attentions,
1590
+ output_hidden_states=output_hidden_states,
1591
+ return_dict=return_dict,
1592
+ )
1593
+ pooled_output = text_outputs[1]
1594
+ text_features = self.text_projection(pooled_output)
1595
+
1596
+ return text_features
1597
+
1598
+ @add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
1599
+ def get_image_features(
1600
+ self,
1601
+ pixel_values: Optional[torch.FloatTensor] = None,
1602
+ output_attentions: Optional[bool] = None,
1603
+ output_hidden_states: Optional[bool] = None,
1604
+ interpolate_pos_encoding: bool = False,
1605
+ return_dict: Optional[bool] = None,
1606
+ ) -> torch.FloatTensor:
1607
+ r"""
1608
+ Returns:
1609
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1610
+ applying the projection layer to the pooled output of [`AltCLIPVisionModel`].
1611
+
1612
+ Examples:
1613
+
1614
+ ```python
1615
+ >>> from PIL import Image
1616
+ >>> import requests
1617
+ >>> from transformers import AutoProcessor, AltCLIPModel
1618
+
1619
+ >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
1620
+ >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
1621
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1622
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1623
+ >>> inputs = processor(images=image, return_tensors="pt")
1624
+ >>> image_features = model.get_image_features(**inputs)
1625
+ ```"""
1626
+ # Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
1627
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1628
+ output_hidden_states = (
1629
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1630
+ )
1631
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1632
+
1633
+ vision_outputs = self.vision_model(
1634
+ pixel_values=pixel_values,
1635
+ output_attentions=output_attentions,
1636
+ output_hidden_states=output_hidden_states,
1637
+ interpolate_pos_encoding=interpolate_pos_encoding,
1638
+ return_dict=return_dict,
1639
+ )
1640
+
1641
+ pooled_output = vision_outputs[1] # pooled_output
1642
+ image_features = self.visual_projection(pooled_output)
1643
+
1644
+ return image_features
1645
+
1646
+ @add_start_docstrings_to_model_forward(ALTCLIP_INPUTS_DOCSTRING)
1647
+ @replace_return_docstrings(output_type=AltCLIPOutput, config_class=AltCLIPConfig)
1648
+ def forward(
1649
+ self,
1650
+ input_ids: Optional[torch.LongTensor] = None,
1651
+ pixel_values: Optional[torch.FloatTensor] = None,
1652
+ attention_mask: Optional[torch.Tensor] = None,
1653
+ position_ids: Optional[torch.LongTensor] = None,
1654
+ token_type_ids: Optional[torch.Tensor] = None,
1655
+ return_loss: Optional[bool] = None,
1656
+ output_attentions: Optional[bool] = None,
1657
+ output_hidden_states: Optional[bool] = None,
1658
+ interpolate_pos_encoding: bool = False,
1659
+ return_dict: Optional[bool] = None,
1660
+ ) -> Union[Tuple, AltCLIPOutput]:
1661
+ r"""
1662
+ Returns:
1663
+
1664
+ Examples:
1665
+
1666
+ ```python
1667
+ >>> from PIL import Image
1668
+ >>> import requests
1669
+ >>> from transformers import AutoProcessor, AltCLIPModel
1670
+
1671
+ >>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
1672
+ >>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
1673
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1674
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1675
+ >>> inputs = processor(
1676
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
1677
+ ... )
1678
+ >>> outputs = model(**inputs)
1679
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
1680
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
1681
+ ```"""
1682
+ # Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
1683
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1684
+ output_hidden_states = (
1685
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1686
+ )
1687
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1688
+
1689
+ text_outputs = self.text_model(
1690
+ input_ids=input_ids,
1691
+ attention_mask=attention_mask,
1692
+ token_type_ids=token_type_ids,
1693
+ position_ids=position_ids,
1694
+ output_attentions=output_attentions,
1695
+ output_hidden_states=output_hidden_states,
1696
+ return_dict=return_dict,
1697
+ )
1698
+
1699
+ vision_outputs = self.vision_model(
1700
+ pixel_values=pixel_values,
1701
+ output_attentions=output_attentions,
1702
+ output_hidden_states=output_hidden_states,
1703
+ interpolate_pos_encoding=interpolate_pos_encoding,
1704
+ return_dict=return_dict,
1705
+ )
1706
+
1707
+ image_embeds = vision_outputs[1]
1708
+ image_embeds = self.visual_projection(image_embeds)
1709
+
1710
+ text_embeds = text_outputs[1]
1711
+ text_embeds = self.text_projection(text_embeds)
1712
+
1713
+ # normalized features
1714
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1715
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1716
+
1717
+ # cosine similarity as logits
1718
+ logit_scale = self.logit_scale.exp()
1719
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
1720
+ logits_per_image = logits_per_text.T
1721
+
1722
+ loss = None
1723
+ if return_loss:
1724
+ loss = clip_loss(logits_per_text)
1725
+
1726
+ if not return_dict:
1727
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1728
+ return ((loss,) + output) if loss is not None else output
1729
+
1730
+ return AltCLIPOutput(
1731
+ loss=loss,
1732
+ logits_per_image=logits_per_image,
1733
+ logits_per_text=logits_per_text,
1734
+ text_embeds=text_embeds,
1735
+ image_embeds=image_embeds,
1736
+ text_model_output=text_outputs,
1737
+ vision_model_output=vision_outputs,
1738
+ )
1739
+
1740
+
1741
+ # Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
1742
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
1743
+ """
1744
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1745
+ are ignored. This is modified from fairseq's `utils.make_positions`.
1746
+
1747
+ Args:
1748
+ x: torch.Tensor x:
1749
+
1750
+ Returns: torch.Tensor
1751
+ """
1752
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1753
+ mask = input_ids.ne(padding_idx).int()
1754
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
1755
+ return incremental_indices.long() + padding_idx
1756
+
1757
+
1758
+ __all__ = ["AltCLIPPreTrainedModel", "AltCLIPVisionModel", "AltCLIPTextModel", "AltCLIPModel"]
janus/lib/python3.10/site-packages/transformers/models/altclip/processing_altclip.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Image/Text processor class for AltCLIP
17
+ """
18
+
19
+ from typing import List, Union
20
+
21
+ from ...image_utils import ImageInput
22
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
23
+ from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
24
+ from ...utils.deprecation import deprecate_kwarg
25
+
26
+
27
+ class AltClipProcessorKwargs(ProcessingKwargs, total=False):
28
+ _defaults = {}
29
+
30
+
31
+ class AltCLIPProcessor(ProcessorMixin):
32
+ r"""
33
+ Constructs a AltCLIP processor which wraps a CLIP image processor and a XLM-Roberta tokenizer into a single
34
+ processor.
35
+
36
+ [`AltCLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`XLMRobertaTokenizerFast`]. See
37
+ the [`~AltCLIPProcessor.__call__`] and [`~AltCLIPProcessor.decode`] for more information.
38
+
39
+ Args:
40
+ image_processor ([`CLIPImageProcessor`], *optional*):
41
+ The image processor is a required input.
42
+ tokenizer ([`XLMRobertaTokenizerFast`], *optional*):
43
+ The tokenizer is a required input.
44
+ """
45
+
46
+ attributes = ["image_processor", "tokenizer"]
47
+ image_processor_class = "CLIPImageProcessor"
48
+ tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
49
+
50
+ @deprecate_kwarg(old_name="feature_extractor", version="5.0.0", new_name="image_processor")
51
+ def __init__(self, image_processor=None, tokenizer=None):
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
+
59
+ def __call__(
60
+ self,
61
+ images: ImageInput = None,
62
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
63
+ audio=None,
64
+ videos=None,
65
+ **kwargs: Unpack[AltClipProcessorKwargs],
66
+ ) -> BatchEncoding:
67
+ """
68
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
69
+ and `kwargs` arguments to XLMRobertaTokenizerFast's [`~XLMRobertaTokenizerFast.__call__`] if `text` is not
70
+ `None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
71
+ CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
72
+ of the above two methods for more information.
73
+
74
+ Args:
75
+
76
+ images (`ImageInput`):
77
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
78
+ tensor. Both channels-first and channels-last formats are supported.
79
+ text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
80
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
81
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
82
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
83
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
84
+ If set, will return tensors of a particular framework. Acceptable values are:
85
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
86
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
87
+ - `'np'`: Return NumPy `np.ndarray` objects.
88
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
89
+ Returns:
90
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
91
+
92
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
93
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
94
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
95
+ `None`).
96
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
97
+ """
98
+
99
+ if text is None and images is None:
100
+ raise ValueError("You must specify either text or images.")
101
+
102
+ if text is None and images is None:
103
+ raise ValueError("You must specify either text or images.")
104
+ output_kwargs = self._merge_kwargs(
105
+ AltClipProcessorKwargs,
106
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
107
+ **kwargs,
108
+ )
109
+
110
+ if text is not None:
111
+ encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
112
+ if images is not None:
113
+ image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
114
+
115
+ # BC for explicit return_tensors
116
+ if "return_tensors" in output_kwargs["common_kwargs"]:
117
+ return_tensors = output_kwargs["common_kwargs"].pop("return_tensors", None)
118
+
119
+ if text is not None and images is not None:
120
+ encoding["pixel_values"] = image_features.pixel_values
121
+ return encoding
122
+ elif text is not None:
123
+ return encoding
124
+ else:
125
+ return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
126
+
127
+ def batch_decode(self, *args, **kwargs):
128
+ """
129
+ This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`].
130
+ Please refer to the docstring of this method for more information.
131
+ """
132
+ return self.tokenizer.batch_decode(*args, **kwargs)
133
+
134
+ def decode(self, *args, **kwargs):
135
+ """
136
+ This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please
137
+ refer to the docstring of this method for more information.
138
+ """
139
+ return self.tokenizer.decode(*args, **kwargs)
140
+
141
+ @property
142
+ def model_input_names(self):
143
+ tokenizer_input_names = self.tokenizer.model_input_names
144
+ image_processor_input_names = self.image_processor.model_input_names
145
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
146
+
147
+
148
+ __all__ = ["AltCLIPProcessor"]
janus/lib/python3.10/site-packages/transformers/models/deprecated/mctct/processing_mctct.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
16
+ Speech processor class for M-CTC-T
17
+ """
18
+
19
+ import warnings
20
+ from contextlib import contextmanager
21
+
22
+ from ....processing_utils import ProcessorMixin
23
+
24
+
25
+ class MCTCTProcessor(ProcessorMixin):
26
+ r"""
27
+ Constructs a MCTCT processor which wraps a MCTCT feature extractor and a MCTCT tokenizer into a single processor.
28
+
29
+ [`MCTCTProcessor`] offers all the functionalities of [`MCTCTFeatureExtractor`] and [`AutoTokenizer`]. See the
30
+ [`~MCTCTProcessor.__call__`] and [`~MCTCTProcessor.decode`] for more information.
31
+
32
+ Args:
33
+ feature_extractor (`MCTCTFeatureExtractor`):
34
+ An instance of [`MCTCTFeatureExtractor`]. The feature extractor is a required input.
35
+ tokenizer (`AutoTokenizer`):
36
+ An instance of [`AutoTokenizer`]. The tokenizer is a required input.
37
+ """
38
+
39
+ feature_extractor_class = "MCTCTFeatureExtractor"
40
+ tokenizer_class = "AutoTokenizer"
41
+
42
+ def __init__(self, feature_extractor, tokenizer):
43
+ super().__init__(feature_extractor, tokenizer)
44
+ self.current_processor = self.feature_extractor
45
+ self._in_target_context_manager = False
46
+
47
+ def __call__(self, *args, **kwargs):
48
+ """
49
+ When used in normal mode, this method forwards all its arguments to MCTCTFeatureExtractor's
50
+ [`~MCTCTFeatureExtractor.__call__`] and returns its output. If used in the context
51
+ [`~MCTCTProcessor.as_target_processor`] this method forwards all its arguments to AutoTokenizer's
52
+ [`~AutoTokenizer.__call__`]. Please refer to the doctsring of the above two methods for more information.
53
+ """
54
+ # For backward compatibility
55
+ if self._in_target_context_manager:
56
+ return self.current_processor(*args, **kwargs)
57
+
58
+ if "raw_speech" in kwargs:
59
+ warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.")
60
+ audio = kwargs.pop("raw_speech")
61
+ else:
62
+ audio = kwargs.pop("audio", None)
63
+ sampling_rate = kwargs.pop("sampling_rate", None)
64
+ text = kwargs.pop("text", None)
65
+ if len(args) > 0:
66
+ audio = args[0]
67
+ args = args[1:]
68
+
69
+ if audio is None and text is None:
70
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
71
+
72
+ if audio is not None:
73
+ inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
74
+ if text is not None:
75
+ encodings = self.tokenizer(text, **kwargs)
76
+
77
+ if text is None:
78
+ return inputs
79
+ elif audio is None:
80
+ return encodings
81
+ else:
82
+ inputs["labels"] = encodings["input_ids"]
83
+ return inputs
84
+
85
+ def batch_decode(self, *args, **kwargs):
86
+ """
87
+ This method forwards all its arguments to AutoTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer
88
+ to the docstring of this method for more information.
89
+ """
90
+ return self.tokenizer.batch_decode(*args, **kwargs)
91
+
92
+ def pad(self, *args, **kwargs):
93
+ """
94
+ When used in normal mode, this method forwards all its arguments to MCTCTFeatureExtractor's
95
+ [`~MCTCTFeatureExtractor.pad`] and returns its output. If used in the context
96
+ [`~MCTCTProcessor.as_target_processor`] this method forwards all its arguments to PreTrainedTokenizer's
97
+ [`~PreTrainedTokenizer.pad`]. Please refer to the docstring of the above two methods for more information.
98
+ """
99
+ # For backward compatibility
100
+ if self._in_target_context_manager:
101
+ return self.current_processor.pad(*args, **kwargs)
102
+
103
+ input_features = kwargs.pop("input_features", None)
104
+ labels = kwargs.pop("labels", None)
105
+ if len(args) > 0:
106
+ input_features = args[0]
107
+ args = args[1:]
108
+
109
+ if input_features is not None:
110
+ input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
111
+ if labels is not None:
112
+ labels = self.tokenizer.pad(labels, **kwargs)
113
+
114
+ if labels is None:
115
+ return input_features
116
+ elif input_features is None:
117
+ return labels
118
+ else:
119
+ input_features["labels"] = labels["input_ids"]
120
+ return input_features
121
+
122
+ def decode(self, *args, **kwargs):
123
+ """
124
+ This method forwards all its arguments to AutoTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
125
+ docstring of this method for more information.
126
+ """
127
+ return self.tokenizer.decode(*args, **kwargs)
128
+
129
+ @contextmanager
130
+ def as_target_processor(self):
131
+ """
132
+ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning MCTCT.
133
+ """
134
+ warnings.warn(
135
+ "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
136
+ "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
137
+ "your audio inputs, or in a separate call."
138
+ )
139
+ self._in_target_context_manager = True
140
+ self.current_processor = self.tokenizer
141
+ yield
142
+ self.current_processor = self.feature_extractor
143
+ self._in_target_context_manager = False
janus/lib/python3.10/site-packages/transformers/models/deprecated/mega/__init__.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ....utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_torch_available,
21
+ )
22
+
23
+
24
+ _import_structure = {
25
+ "configuration_mega": ["MegaConfig", "MegaOnnxConfig"],
26
+ }
27
+
28
+ try:
29
+ if not is_torch_available():
30
+ raise OptionalDependencyNotAvailable()
31
+ except OptionalDependencyNotAvailable:
32
+ pass
33
+ else:
34
+ _import_structure["modeling_mega"] = [
35
+ "MegaForCausalLM",
36
+ "MegaForMaskedLM",
37
+ "MegaForMultipleChoice",
38
+ "MegaForQuestionAnswering",
39
+ "MegaForSequenceClassification",
40
+ "MegaForTokenClassification",
41
+ "MegaModel",
42
+ "MegaPreTrainedModel",
43
+ ]
44
+
45
+ if TYPE_CHECKING:
46
+ from .configuration_mega import MegaConfig, MegaOnnxConfig
47
+
48
+ try:
49
+ if not is_torch_available():
50
+ raise OptionalDependencyNotAvailable()
51
+ except OptionalDependencyNotAvailable:
52
+ pass
53
+ else:
54
+ from .modeling_mega import (
55
+ MegaForCausalLM,
56
+ MegaForMaskedLM,
57
+ MegaForMultipleChoice,
58
+ MegaForQuestionAnswering,
59
+ MegaForSequenceClassification,
60
+ MegaForTokenClassification,
61
+ MegaModel,
62
+ MegaPreTrainedModel,
63
+ )
64
+
65
+ else:
66
+ import sys
67
+
68
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/deprecated/mega/modeling_mega.py ADDED
The diff for this file is too large to render. See raw diff
 
janus/lib/python3.10/site-packages/transformers/models/deprecated/tapex/tokenization_tapex.py ADDED
@@ -0,0 +1,1467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
40
+ class TapexTruncationStrategy(ExplicitEnum):
41
+ """
42
+ Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
43
+ """
44
+
45
+ DROP_ROWS_TO_FIT = "drop_rows_to_fit"
46
+
47
+
48
+ TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
49
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
50
+ Whether or not to encode the sequences with the special tokens relative to their model.
51
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
52
+ Activates and controls padding. Accepts the following values:
53
+
54
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
55
+ sequence if provided).
56
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
57
+ acceptable input length for the model if that argument is not provided.
58
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
59
+ lengths).
60
+ truncation (`bool`, `str`, [`TapexTruncationStrategy`] or [`~tokenization_utils_base.TruncationStrategy`],
61
+ *optional*, defaults to `False`):
62
+
63
+ Activates and controls truncation. Accepts the following values:
64
+
65
+ - `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` or to the
66
+ maximum acceptable input length for the model if that argument is not provided. This will truncate
67
+ row by row, removing rows from the table.
68
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
69
+ to the maximum acceptable input length for the model if that argument is not provided. This will
70
+ truncate token by token, removing a token from the longest sequence in the pair if a pair of
71
+ sequences (or a batch of pairs) is provided.
72
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
73
+ maximum acceptable input length for the model if that argument is not provided. This will only
74
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
75
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
76
+ maximum acceptable input length for the model if that argument is not provided. This will only
77
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
78
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
79
+ greater than the model maximum admissible input size).
80
+ max_length (`int`, *optional*):
81
+ Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
82
+ `None`, this will use the predefined model maximum length if a maximum length is required by one of the
83
+ truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
84
+ truncation/padding to a maximum length will be deactivated.
85
+ stride (`int`, *optional*, defaults to 0):
86
+ If set to a number along with `max_length`, the overflowing tokens returned when
87
+ `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
88
+ returned to provide some overlap between truncated and overflowing sequences. The value of this
89
+ argument defines the number of overlapping tokens.
90
+ pad_to_multiple_of (`int`, *optional*):
91
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
92
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
93
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
94
+ If set, will return tensors instead of list of python integers. Acceptable values are:
95
+
96
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
97
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
98
+ - `'np'`: Return Numpy `np.ndarray` objects.
99
+ """
100
+
101
+
102
+ @lru_cache()
103
+ def bytes_to_unicode():
104
+ """
105
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
106
+ characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
107
+ of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
108
+ you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
109
+ vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
110
+ """
111
+ bs = (
112
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
113
+ )
114
+ cs = bs[:]
115
+ n = 0
116
+ for b in range(2**8):
117
+ if b not in bs:
118
+ bs.append(b)
119
+ cs.append(2**8 + n)
120
+ n += 1
121
+ cs = [chr(n) for n in cs]
122
+ return dict(zip(bs, cs))
123
+
124
+
125
+ def get_pairs(word):
126
+ """
127
+ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
128
+ strings).
129
+ """
130
+ pairs = set()
131
+ prev_char = word[0]
132
+ for char in word[1:]:
133
+ pairs.add((prev_char, char))
134
+ prev_char = char
135
+ return pairs
136
+
137
+
138
+ class IndexedRowTableLinearize:
139
+ """
140
+ FORMAT: col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
141
+ """
142
+
143
+ def process_table(self, table_content: Dict):
144
+ """
145
+ Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
146
+ """
147
+ assert "header" in table_content and "rows" in table_content, self.PROMPT_MESSAGE
148
+ # process header
149
+ table_str = self.process_header(table_content["header"]) + " "
150
+ # process rows
151
+ for i, row_example in enumerate(table_content["rows"]):
152
+ # NOTE: the row should start from row 1 instead of 0
153
+ table_str += self.process_row(row_example, row_index=i + 1) + " "
154
+ return table_str.strip()
155
+
156
+ def process_header(self, headers: List):
157
+ """
158
+ Given a list of headers, TableLinearize aims at converting it into a flatten sequence with special symbols.
159
+ """
160
+ return "col : " + " | ".join(headers)
161
+
162
+ def process_row(self, row: List, row_index: int):
163
+ """
164
+ Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
165
+ """
166
+ row_str = ""
167
+ row_cell_values = []
168
+ for cell_value in row:
169
+ if isinstance(cell_value, int):
170
+ row_cell_values.append(str(cell_value))
171
+ else:
172
+ row_cell_values.append(cell_value)
173
+ row_str += " | ".join(row_cell_values)
174
+ return "row " + str(row_index) + " : " + row_str
175
+
176
+
177
+ class TapexTokenizer(PreTrainedTokenizer):
178
+ r"""
179
+ Construct a TAPEX tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).
180
+
181
+ This tokenizer can be used to flatten one or more table(s) and concatenate them with one or more related sentences
182
+ to be used by TAPEX models. The format that the TAPEX tokenizer creates is the following:
183
+
184
+ sentence col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
185
+
186
+ The tokenizer supports a single table + single query, a single table and multiple queries (in which case the table
187
+ will be duplicated for every query), a single query and multiple tables (in which case the query will be duplicated
188
+ for every table), and multiple tables and queries. In other words, you can provide a batch of tables + questions to
189
+ the tokenizer for instance to prepare them for the model.
190
+
191
+ Tokenization itself is based on the BPE algorithm. It is identical to the one used by BART, RoBERTa and GPT-2.
192
+
193
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
194
+ this superclass for more information regarding those methods.
195
+
196
+ Args:
197
+ vocab_file (`str`):
198
+ Path to the vocabulary file.
199
+ merges_file (`str`):
200
+ Path to the merges file.
201
+ do_lower_case (`bool`, *optional*, defaults to `True`):
202
+ Whether or not to lowercase the input when tokenizing.
203
+ errors (`str`, *optional*, defaults to `"replace"`):
204
+ Paradigm to follow when decoding bytes to UTF-8. See
205
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
206
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
207
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
208
+
209
+ <Tip>
210
+
211
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
212
+ sequence. The token used is the `cls_token`.
213
+
214
+ </Tip>
215
+
216
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
217
+ The end of sequence token.
218
+
219
+ <Tip>
220
+
221
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
222
+ The token used is the `sep_token`.
223
+
224
+ </Tip>
225
+
226
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
227
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
228
+ sequence classification or for a text and a question for question answering. It is also used as the last
229
+ token of a sequence built with special tokens.
230
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
231
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
232
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
233
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
234
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
235
+ token instead.
236
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
237
+ The token used for padding, for example when batching sequences of different lengths.
238
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
239
+ The token used for masking values. This is the token used when training this model with masked language
240
+ modeling. This is the token which the model will try to predict.
241
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
242
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
243
+ other word. (BART tokenizer detect beginning of words by the preceding space).
244
+ max_cell_length (`int`, *optional*, defaults to 15):
245
+ Maximum number of characters per cell when linearizing a table. If this number is exceeded, truncation
246
+ takes place.
247
+ """
248
+
249
+ vocab_files_names = VOCAB_FILES_NAMES
250
+ model_input_names = ["input_ids", "attention_mask"]
251
+
252
+ def __init__(
253
+ self,
254
+ vocab_file,
255
+ merges_file,
256
+ do_lower_case=True,
257
+ errors="replace",
258
+ bos_token="<s>",
259
+ eos_token="</s>",
260
+ sep_token="</s>",
261
+ cls_token="<s>",
262
+ unk_token="<unk>",
263
+ pad_token="<pad>",
264
+ mask_token="<mask>",
265
+ add_prefix_space=False,
266
+ max_cell_length=15,
267
+ **kwargs,
268
+ ):
269
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
270
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
271
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
272
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
273
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
274
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
275
+
276
+ # Mask token behave like a normal word, i.e. include the space before it
277
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
278
+
279
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
280
+ self.encoder = json.load(vocab_handle)
281
+ self.decoder = {v: k for k, v in self.encoder.items()}
282
+ self.errors = errors # how to handle errors in decoding
283
+ self.byte_encoder = bytes_to_unicode()
284
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
285
+ with open(merges_file, encoding="utf-8") as merges_handle:
286
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
287
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
288
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
289
+ self.cache = {}
290
+ self.add_prefix_space = add_prefix_space
291
+ self.do_lower_case = do_lower_case
292
+
293
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
294
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
295
+
296
+ # additional properties
297
+
298
+ super().__init__(
299
+ vocab_file=vocab_file,
300
+ merges_file=merges_file,
301
+ do_lower_case=do_lower_case,
302
+ errors=errors,
303
+ bos_token=bos_token,
304
+ eos_token=eos_token,
305
+ unk_token=unk_token,
306
+ sep_token=sep_token,
307
+ cls_token=cls_token,
308
+ pad_token=pad_token,
309
+ mask_token=mask_token,
310
+ add_prefix_space=add_prefix_space,
311
+ max_cell_length=max_cell_length,
312
+ **kwargs,
313
+ )
314
+
315
+ self.max_cell_length = max_cell_length
316
+ self.table_linearize = IndexedRowTableLinearize()
317
+
318
+ def build_inputs_with_special_tokens(
319
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
320
+ ) -> List[int]:
321
+ """
322
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
323
+ adding special tokens. A TAPEX sequence has the following format:
324
+ - single sequence: `<s> X </s>`
325
+ - pair of sequences: `<s> A </s></s> B </s>`
326
+
327
+ Args:
328
+ token_ids_0 (`List[int]`):
329
+ List of IDs to which the special tokens will be added.
330
+ token_ids_1 (`List[int]`, *optional*):
331
+ Optional second list of IDs for sequence pairs.
332
+ Returns:
333
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
334
+ """
335
+ if token_ids_1 is None:
336
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
337
+ cls = [self.cls_token_id]
338
+ sep = [self.sep_token_id]
339
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
340
+
341
+ def get_special_tokens_mask(
342
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
343
+ ) -> List[int]:
344
+ """
345
+ Args:
346
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
347
+ special tokens using the tokenizer `prepare_for_model` method.
348
+ token_ids_0 (`List[int]`):
349
+ List of IDs.
350
+ token_ids_1 (`List[int]`, *optional*):
351
+ Optional second list of IDs for sequence pairs.
352
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
353
+ Whether or not the token list is already formatted with special tokens for the model.
354
+ Returns:
355
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
356
+ """
357
+ if already_has_special_tokens:
358
+ return super().get_special_tokens_mask(
359
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
360
+ )
361
+
362
+ if token_ids_1 is None:
363
+ return [1] + ([0] * len(token_ids_0)) + [1]
364
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
365
+
366
+ def create_token_type_ids_from_sequences(
367
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
368
+ ) -> List[int]:
369
+ """
370
+ Args:
371
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
372
+ make use of token type ids, therefore a list of zeros is returned.
373
+ token_ids_0 (`List[int]`):
374
+ List of IDs.
375
+ token_ids_1 (`List[int]`, *optional*):
376
+ Optional second list of IDs for sequence pairs.
377
+ Returns:
378
+ `List[int]`: List of zeros.
379
+ """
380
+ sep = [self.sep_token_id]
381
+ cls = [self.cls_token_id]
382
+
383
+ if token_ids_1 is None:
384
+ return len(cls + token_ids_0 + sep) * [0]
385
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
386
+
387
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
388
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
389
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
390
+ text = " " + text
391
+ return (text, kwargs)
392
+
393
+ @property
394
+ def vocab_size(self):
395
+ return len(self.encoder)
396
+
397
+ def get_vocab(self):
398
+ return dict(self.encoder, **self.added_tokens_encoder)
399
+
400
+ def bpe(self, token):
401
+ if token in self.cache:
402
+ return self.cache[token]
403
+ word = tuple(token)
404
+ pairs = get_pairs(word)
405
+
406
+ if not pairs:
407
+ return token
408
+
409
+ while True:
410
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
411
+ if bigram not in self.bpe_ranks:
412
+ break
413
+ first, second = bigram
414
+ new_word = []
415
+ i = 0
416
+ while i < len(word):
417
+ try:
418
+ j = word.index(first, i)
419
+ except ValueError:
420
+ new_word.extend(word[i:])
421
+ break
422
+ else:
423
+ new_word.extend(word[i:j])
424
+ i = j
425
+
426
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
427
+ new_word.append(first + second)
428
+ i += 2
429
+ else:
430
+ new_word.append(word[i])
431
+ i += 1
432
+ new_word = tuple(new_word)
433
+ word = new_word
434
+ if len(word) == 1:
435
+ break
436
+ else:
437
+ pairs = get_pairs(word)
438
+ word = " ".join(word)
439
+ self.cache[token] = word
440
+ return word
441
+
442
+ def _tokenize(self, text):
443
+ """Tokenize a string."""
444
+ bpe_tokens = []
445
+ for token in re.findall(self.pat, text):
446
+ token = "".join(
447
+ self.byte_encoder[b] for b in token.encode("utf-8")
448
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
449
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
450
+ return bpe_tokens
451
+
452
+ def _convert_token_to_id(self, token):
453
+ """Converts a token (str) in an id using the vocab."""
454
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
455
+
456
+ def _convert_id_to_token(self, index):
457
+ """Converts an index (integer) in a token (str) using the vocab."""
458
+ return self.decoder.get(index)
459
+
460
+ def convert_tokens_to_string(self, tokens):
461
+ """Converts a sequence of tokens (string) in a single string."""
462
+ text = "".join(tokens)
463
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
464
+ return text
465
+
466
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
467
+ if not os.path.isdir(save_directory):
468
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
469
+ return
470
+ vocab_file = os.path.join(
471
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
472
+ )
473
+ merge_file = os.path.join(
474
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
475
+ )
476
+
477
+ with open(vocab_file, "w", encoding="utf-8") as f:
478
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
479
+
480
+ index = 0
481
+ with open(merge_file, "w", encoding="utf-8") as writer:
482
+ writer.write("#version: 0.2\n")
483
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
484
+ if index != token_index:
485
+ logger.warning(
486
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
487
+ " Please check that the tokenizer is not corrupted!"
488
+ )
489
+ index = token_index
490
+ writer.write(" ".join(bpe_tokens) + "\n")
491
+ index += 1
492
+
493
+ return vocab_file, merge_file
494
+
495
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
496
+ def __call__(
497
+ self,
498
+ table: Union["pd.DataFrame", List["pd.DataFrame"]] = None,
499
+ query: Optional[Union[TextInput, List[TextInput]]] = None,
500
+ answer: Union[str, List[str]] = None,
501
+ add_special_tokens: bool = True,
502
+ padding: Union[bool, str, PaddingStrategy] = False,
503
+ truncation: Union[bool, str, TruncationStrategy] = None,
504
+ max_length: Optional[int] = None,
505
+ stride: int = 0,
506
+ pad_to_multiple_of: Optional[int] = None,
507
+ return_tensors: Optional[Union[str, TensorType]] = None,
508
+ return_token_type_ids: Optional[bool] = None,
509
+ return_attention_mask: Optional[bool] = None,
510
+ return_overflowing_tokens: bool = False,
511
+ return_special_tokens_mask: bool = False,
512
+ return_offsets_mapping: bool = False,
513
+ return_length: bool = False,
514
+ verbose: bool = True,
515
+ **kwargs,
516
+ ) -> BatchEncoding:
517
+ """
518
+ Main method to tokenize and prepare for the model one or several table-sequence pair(s).
519
+
520
+ Args:
521
+ table (`pd.DataFrame`, `List[pd.DataFrame]`):
522
+ Table(s) containing tabular data.
523
+ query (`str` or `List[str]`, *optional*):
524
+ Sentence or batch of sentences related to one or more table(s) to be encoded. Note that the number of
525
+ sentences must match the number of tables.
526
+ answer (`str` or `List[str]`, *optional*):
527
+ Optionally, the corresponding answer to the questions as supervision.
528
+ """
529
+
530
+ if table is not None:
531
+ return self.source_call_func(
532
+ table=table,
533
+ query=query,
534
+ answer=answer,
535
+ add_special_tokens=add_special_tokens,
536
+ padding=padding,
537
+ truncation=truncation,
538
+ max_length=max_length,
539
+ stride=stride,
540
+ pad_to_multiple_of=pad_to_multiple_of,
541
+ return_tensors=return_tensors,
542
+ return_token_type_ids=return_token_type_ids,
543
+ return_attention_mask=return_attention_mask,
544
+ return_overflowing_tokens=return_overflowing_tokens,
545
+ return_special_tokens_mask=return_special_tokens_mask,
546
+ return_offsets_mapping=return_offsets_mapping,
547
+ return_length=return_length,
548
+ verbose=verbose,
549
+ **kwargs,
550
+ )
551
+ elif answer is not None:
552
+ return self.target_call_func(
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
+ else:
571
+ raise ValueError("You need to provide either a `table` or an `answer`.")
572
+
573
+ def source_call_func(
574
+ self,
575
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
576
+ query: Optional[Union[TextInput, List[TextInput]]] = None,
577
+ answer: Union[str, List[str]] = None,
578
+ add_special_tokens: bool = True,
579
+ padding: Union[bool, str, PaddingStrategy] = False,
580
+ truncation: Union[bool, str, TruncationStrategy] = None,
581
+ max_length: Optional[int] = None,
582
+ stride: int = 0,
583
+ pad_to_multiple_of: Optional[int] = None,
584
+ return_tensors: Optional[Union[str, TensorType]] = None,
585
+ return_token_type_ids: Optional[bool] = None,
586
+ return_attention_mask: Optional[bool] = None,
587
+ return_overflowing_tokens: bool = False,
588
+ return_special_tokens_mask: bool = False,
589
+ return_offsets_mapping: bool = False,
590
+ return_length: bool = False,
591
+ verbose: bool = True,
592
+ **kwargs,
593
+ ) -> BatchEncoding:
594
+ # Input type checking for clearer error
595
+ valid_table = False
596
+ valid_query = False
597
+
598
+ # Check that table have a valid type
599
+ if isinstance(table, pd.DataFrame):
600
+ valid_table = True
601
+ elif isinstance(table, (list, tuple)) and isinstance(table[0], pd.DataFrame):
602
+ valid_table = True
603
+
604
+ # Check that query have a valid type
605
+ if query is None or isinstance(query, str):
606
+ valid_query = True
607
+ elif isinstance(query, (list, tuple)):
608
+ if len(query) == 0 or isinstance(query[0], str):
609
+ valid_query = True
610
+
611
+ if not valid_table:
612
+ raise ValueError(
613
+ "table input must of type `pd.DataFrame` (single example), `List[pd.DataFrame]` (batch of examples). "
614
+ )
615
+ if not valid_query:
616
+ raise ValueError("query input must of type `str` (single example), `List[str]` (batch of examples). ")
617
+ is_batched = isinstance(table, (list, tuple)) or isinstance(query, (list, tuple))
618
+
619
+ if is_batched:
620
+ return self.batch_encode_plus(
621
+ table=table,
622
+ query=query,
623
+ answer=answer,
624
+ add_special_tokens=add_special_tokens,
625
+ padding=padding,
626
+ truncation=truncation,
627
+ max_length=max_length,
628
+ pad_to_multiple_of=pad_to_multiple_of,
629
+ return_tensors=return_tensors,
630
+ return_token_type_ids=return_token_type_ids,
631
+ return_attention_mask=return_attention_mask,
632
+ return_overflowing_tokens=return_overflowing_tokens,
633
+ return_special_tokens_mask=return_special_tokens_mask,
634
+ return_offsets_mapping=return_offsets_mapping,
635
+ return_length=return_length,
636
+ verbose=verbose,
637
+ **kwargs,
638
+ )
639
+ else:
640
+ return self.encode_plus(
641
+ table=table,
642
+ query=query,
643
+ answer=answer,
644
+ add_special_tokens=add_special_tokens,
645
+ padding=padding,
646
+ truncation=truncation,
647
+ max_length=max_length,
648
+ pad_to_multiple_of=pad_to_multiple_of,
649
+ return_tensors=return_tensors,
650
+ return_token_type_ids=return_token_type_ids,
651
+ return_attention_mask=return_attention_mask,
652
+ return_overflowing_tokens=return_overflowing_tokens,
653
+ return_special_tokens_mask=return_special_tokens_mask,
654
+ return_offsets_mapping=return_offsets_mapping,
655
+ return_length=return_length,
656
+ verbose=verbose,
657
+ **kwargs,
658
+ )
659
+
660
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
661
+ def batch_encode_plus(
662
+ self,
663
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
664
+ query: Optional[List[TextInput]] = None,
665
+ answer: List[str] = None,
666
+ add_special_tokens: bool = True,
667
+ padding: Union[bool, str, PaddingStrategy] = False,
668
+ truncation: Union[bool, str] = None,
669
+ max_length: Optional[int] = None,
670
+ pad_to_multiple_of: Optional[int] = None,
671
+ return_tensors: Optional[Union[str, TensorType]] = None,
672
+ return_token_type_ids: Optional[bool] = None,
673
+ return_attention_mask: Optional[bool] = None,
674
+ return_overflowing_tokens: bool = False,
675
+ return_special_tokens_mask: bool = False,
676
+ return_offsets_mapping: bool = False,
677
+ return_length: bool = False,
678
+ verbose: bool = True,
679
+ **kwargs,
680
+ ) -> BatchEncoding:
681
+ """
682
+ <Tip warning={true}>
683
+
684
+ This method is deprecated, `__call__` should be used instead.
685
+
686
+ </Tip>
687
+ """
688
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
689
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
690
+ padding=padding,
691
+ truncation=truncation,
692
+ max_length=max_length,
693
+ pad_to_multiple_of=pad_to_multiple_of,
694
+ verbose=verbose,
695
+ **kwargs,
696
+ )
697
+
698
+ return self._batch_encode_plus(
699
+ table=table,
700
+ query=query,
701
+ answer=answer,
702
+ add_special_tokens=add_special_tokens,
703
+ padding_strategy=padding_strategy,
704
+ truncation_strategy=truncation_strategy,
705
+ max_length=max_length,
706
+ pad_to_multiple_of=pad_to_multiple_of,
707
+ return_tensors=return_tensors,
708
+ return_token_type_ids=return_token_type_ids,
709
+ return_attention_mask=return_attention_mask,
710
+ return_overflowing_tokens=return_overflowing_tokens,
711
+ return_special_tokens_mask=return_special_tokens_mask,
712
+ return_offsets_mapping=return_offsets_mapping,
713
+ return_length=return_length,
714
+ verbose=verbose,
715
+ **kwargs,
716
+ )
717
+
718
+ def _batch_encode_plus(
719
+ self,
720
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
721
+ query: Optional[List[TextInput]] = None,
722
+ answer: Optional[List[str]] = None,
723
+ add_special_tokens: bool = True,
724
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
725
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
726
+ max_length: Optional[int] = None,
727
+ stride: int = 0,
728
+ pad_to_multiple_of: Optional[int] = None,
729
+ return_tensors: Optional[Union[str, TensorType]] = None,
730
+ return_token_type_ids: Optional[bool] = None,
731
+ return_attention_mask: Optional[bool] = None,
732
+ return_overflowing_tokens: bool = False,
733
+ return_special_tokens_mask: bool = False,
734
+ return_offsets_mapping: bool = False,
735
+ return_length: bool = False,
736
+ verbose: bool = True,
737
+ **kwargs,
738
+ ) -> BatchEncoding:
739
+ if return_offsets_mapping:
740
+ raise NotImplementedError(
741
+ "return_offset_mapping is not available when using Python tokenizers. "
742
+ "To use this feature, change your tokenizer to one deriving from "
743
+ "transformers.PreTrainedTokenizerFast."
744
+ )
745
+
746
+ if isinstance(table, pd.DataFrame) and isinstance(query, (list, tuple)):
747
+ # single table, many queries case
748
+ # duplicate table for every query
749
+ table = [table] * len(query)
750
+ if isinstance(table, (list, tuple)) and isinstance(query, str):
751
+ # many tables, single query case
752
+ # duplicate query for every table
753
+ query = [query] * len(table)
754
+
755
+ batch_outputs = self._batch_prepare_for_model(
756
+ table=table,
757
+ query=query,
758
+ answer=answer,
759
+ add_special_tokens=add_special_tokens,
760
+ padding_strategy=padding_strategy,
761
+ truncation_strategy=truncation_strategy,
762
+ max_length=max_length,
763
+ stride=stride,
764
+ pad_to_multiple_of=pad_to_multiple_of,
765
+ return_attention_mask=return_attention_mask,
766
+ return_token_type_ids=return_token_type_ids,
767
+ return_overflowing_tokens=return_overflowing_tokens,
768
+ return_special_tokens_mask=return_special_tokens_mask,
769
+ return_length=return_length,
770
+ return_tensors=return_tensors,
771
+ verbose=verbose,
772
+ )
773
+
774
+ return BatchEncoding(batch_outputs)
775
+
776
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
777
+ def _batch_prepare_for_model(
778
+ self,
779
+ table: Union["pd.DataFrame", List["pd.DataFrame"]],
780
+ query: Optional[Union[TextInput, List[TextInput]]] = None,
781
+ answer: Optional[Union[str, List[str]]] = None,
782
+ add_special_tokens: bool = True,
783
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
784
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
785
+ max_length: Optional[int] = None,
786
+ stride: int = 0,
787
+ pad_to_multiple_of: Optional[int] = None,
788
+ return_tensors: Optional[str] = None,
789
+ return_token_type_ids: Optional[bool] = None,
790
+ return_attention_mask: Optional[bool] = None,
791
+ return_overflowing_tokens: bool = False,
792
+ return_special_tokens_mask: bool = False,
793
+ return_length: bool = False,
794
+ verbose: bool = True,
795
+ ) -> BatchEncoding:
796
+ """
797
+ This method adds special tokens, truncates sequences if overflowing while taking into account the special
798
+ tokens and manages a moving window (with user defined stride) for overflowing tokens.
799
+ """
800
+ batch_outputs = {}
801
+ if answer is None:
802
+ answer = [None] * len(table)
803
+ for _table, _query, _answer in zip(table, query, answer):
804
+ text = self.prepare_table_query(
805
+ _table, _query, _answer, truncation_strategy=truncation_strategy, max_length=max_length
806
+ )
807
+
808
+ if self.do_lower_case:
809
+ text = text.lower()
810
+
811
+ tokens = self.tokenize(text)
812
+ outputs = self.prepare_for_model(
813
+ ids=self.convert_tokens_to_ids(tokens),
814
+ add_special_tokens=add_special_tokens,
815
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
816
+ truncation=truncation_strategy.value,
817
+ max_length=max_length,
818
+ stride=stride,
819
+ pad_to_multiple_of=None, # we pad in batch afterwards
820
+ return_attention_mask=False, # we pad in batch afterwards
821
+ return_token_type_ids=return_token_type_ids,
822
+ return_overflowing_tokens=return_overflowing_tokens,
823
+ return_special_tokens_mask=return_special_tokens_mask,
824
+ return_length=return_length,
825
+ return_tensors=None, # We convert the whole batch to tensors at the end
826
+ prepend_batch_axis=False,
827
+ verbose=verbose,
828
+ )
829
+
830
+ for key, value in outputs.items():
831
+ if key not in batch_outputs:
832
+ batch_outputs[key] = []
833
+ batch_outputs[key].append(value)
834
+
835
+ batch_outputs = self.pad(
836
+ batch_outputs,
837
+ padding=padding_strategy.value,
838
+ max_length=max_length,
839
+ pad_to_multiple_of=pad_to_multiple_of,
840
+ return_attention_mask=return_attention_mask,
841
+ )
842
+
843
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
844
+
845
+ return batch_outputs
846
+
847
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
848
+ def encode(
849
+ self,
850
+ table: "pd.DataFrame",
851
+ query: Optional[TextInput] = None,
852
+ answer: Optional[str] = None,
853
+ add_special_tokens: bool = True,
854
+ padding: Union[bool, str, PaddingStrategy] = False,
855
+ truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
856
+ max_length: Optional[int] = None,
857
+ return_tensors: Optional[Union[str, TensorType]] = None,
858
+ **kwargs,
859
+ ) -> List[int]:
860
+ """
861
+ Prepare a table, a string and possible answer for the model. This method does not return token type IDs,
862
+ attention masks, etc. which are necessary for the model to work correctly. Use this method if you want to build
863
+ your processing on your own, otherwise refer to `__call__`.
864
+ """
865
+ encoded_inputs = self.encode_plus(
866
+ table,
867
+ query=query,
868
+ answer=answer,
869
+ add_special_tokens=add_special_tokens,
870
+ padding=padding,
871
+ truncation=truncation,
872
+ max_length=max_length,
873
+ return_tensors=return_tensors,
874
+ **kwargs,
875
+ )
876
+
877
+ return encoded_inputs["input_ids"]
878
+
879
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
880
+ def encode_plus(
881
+ self,
882
+ table: "pd.DataFrame",
883
+ query: Optional[TextInput] = None,
884
+ answer: Optional[str] = None,
885
+ add_special_tokens: bool = True,
886
+ padding: Union[bool, str, PaddingStrategy] = False,
887
+ truncation: Union[bool, str] = None,
888
+ max_length: Optional[int] = None,
889
+ pad_to_multiple_of: Optional[int] = None,
890
+ return_tensors: Optional[Union[str, TensorType]] = None,
891
+ return_token_type_ids: Optional[bool] = None,
892
+ return_attention_mask: Optional[bool] = None,
893
+ return_special_tokens_mask: bool = False,
894
+ return_offsets_mapping: bool = False,
895
+ return_length: bool = False,
896
+ verbose: bool = True,
897
+ **kwargs,
898
+ ) -> BatchEncoding:
899
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
900
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
901
+ padding=padding,
902
+ truncation=truncation,
903
+ max_length=max_length,
904
+ pad_to_multiple_of=pad_to_multiple_of,
905
+ verbose=verbose,
906
+ **kwargs,
907
+ )
908
+
909
+ return self._encode_plus(
910
+ table=table,
911
+ query=query,
912
+ answer=answer,
913
+ add_special_tokens=add_special_tokens,
914
+ padding_strategy=padding_strategy,
915
+ truncation_strategy=truncation_strategy,
916
+ max_length=max_length,
917
+ pad_to_multiple_of=pad_to_multiple_of,
918
+ return_tensors=return_tensors,
919
+ return_token_type_ids=return_token_type_ids,
920
+ return_attention_mask=return_attention_mask,
921
+ return_special_tokens_mask=return_special_tokens_mask,
922
+ return_offsets_mapping=return_offsets_mapping,
923
+ return_length=return_length,
924
+ verbose=verbose,
925
+ **kwargs,
926
+ )
927
+
928
+ def _encode_plus(
929
+ self,
930
+ table: "pd.DataFrame",
931
+ query: Optional[TextInput] = None,
932
+ answer: Optional[str] = None,
933
+ add_special_tokens: bool = True,
934
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
935
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
936
+ max_length: Optional[int] = None,
937
+ stride: int = 0,
938
+ pad_to_multiple_of: Optional[int] = None,
939
+ return_tensors: Optional[Union[str, TensorType]] = None,
940
+ return_token_type_ids: Optional[bool] = None,
941
+ return_attention_mask: Optional[bool] = None,
942
+ return_overflowing_tokens: bool = False,
943
+ return_special_tokens_mask: bool = False,
944
+ return_offsets_mapping: bool = False,
945
+ return_length: bool = False,
946
+ verbose: bool = True,
947
+ **kwargs,
948
+ ) -> BatchEncoding:
949
+ if return_offsets_mapping:
950
+ raise NotImplementedError(
951
+ "return_offset_mapping is not available when using Python tokenizers. "
952
+ "To use this feature, change your tokenizer to one deriving from "
953
+ "transformers.PreTrainedTokenizerFast. "
954
+ "More information on available tokenizers at "
955
+ "https://github.com/huggingface/transformers/pull/2674"
956
+ )
957
+
958
+ text = self.prepare_table_query(
959
+ table, query, answer, truncation_strategy=truncation_strategy, max_length=max_length
960
+ )
961
+
962
+ # if necessary, perform lower case
963
+ if self.do_lower_case:
964
+ text = text.lower()
965
+
966
+ tokens = self.tokenize(text)
967
+
968
+ return self.prepare_for_model(
969
+ ids=self.convert_tokens_to_ids(tokens),
970
+ add_special_tokens=add_special_tokens,
971
+ padding=padding_strategy.value,
972
+ truncation=truncation_strategy.value,
973
+ max_length=max_length,
974
+ stride=stride,
975
+ pad_to_multiple_of=pad_to_multiple_of,
976
+ return_tensors=return_tensors,
977
+ prepend_batch_axis=True,
978
+ return_attention_mask=return_attention_mask,
979
+ return_token_type_ids=return_token_type_ids,
980
+ return_overflowing_tokens=return_overflowing_tokens,
981
+ return_special_tokens_mask=return_special_tokens_mask,
982
+ return_length=return_length,
983
+ verbose=verbose,
984
+ )
985
+
986
+ def target_call_func(
987
+ self,
988
+ answer: Union[str, List[str]],
989
+ add_special_tokens: bool = True,
990
+ padding: Union[bool, str, PaddingStrategy] = False,
991
+ truncation: Union[bool, str, TruncationStrategy] = None,
992
+ max_length: Optional[int] = None,
993
+ stride: int = 0,
994
+ pad_to_multiple_of: Optional[int] = None,
995
+ return_tensors: Optional[Union[str, TensorType]] = None,
996
+ return_token_type_ids: Optional[bool] = None,
997
+ return_attention_mask: Optional[bool] = None,
998
+ return_overflowing_tokens: bool = False,
999
+ return_special_tokens_mask: bool = False,
1000
+ return_offsets_mapping: bool = False,
1001
+ return_length: bool = False,
1002
+ verbose: bool = True,
1003
+ **kwargs,
1004
+ ) -> BatchEncoding:
1005
+ """
1006
+ The method tokenizes and prepares the answer label for the model.
1007
+
1008
+ Args:
1009
+ answer (`str` or `List[str]`):
1010
+ Corresponding answer supervision to the queries for training the model.
1011
+ """
1012
+ is_batched = isinstance(answer, (list, tuple))
1013
+
1014
+ if is_batched:
1015
+ return self.target_batch_encode_plus(
1016
+ answer=answer,
1017
+ add_special_tokens=add_special_tokens,
1018
+ padding=padding,
1019
+ truncation=truncation,
1020
+ max_length=max_length,
1021
+ pad_to_multiple_of=pad_to_multiple_of,
1022
+ return_tensors=return_tensors,
1023
+ return_token_type_ids=return_token_type_ids,
1024
+ return_attention_mask=return_attention_mask,
1025
+ return_overflowing_tokens=return_overflowing_tokens,
1026
+ return_special_tokens_mask=return_special_tokens_mask,
1027
+ return_offsets_mapping=return_offsets_mapping,
1028
+ return_length=return_length,
1029
+ verbose=verbose,
1030
+ **kwargs,
1031
+ )
1032
+ else:
1033
+ return self.target_encode_plus(
1034
+ answer=answer,
1035
+ add_special_tokens=add_special_tokens,
1036
+ padding=padding,
1037
+ truncation=truncation,
1038
+ max_length=max_length,
1039
+ pad_to_multiple_of=pad_to_multiple_of,
1040
+ return_tensors=return_tensors,
1041
+ return_token_type_ids=return_token_type_ids,
1042
+ return_attention_mask=return_attention_mask,
1043
+ return_overflowing_tokens=return_overflowing_tokens,
1044
+ return_special_tokens_mask=return_special_tokens_mask,
1045
+ return_offsets_mapping=return_offsets_mapping,
1046
+ return_length=return_length,
1047
+ verbose=verbose,
1048
+ **kwargs,
1049
+ )
1050
+
1051
+ def target_batch_encode_plus(
1052
+ self,
1053
+ answer: List[str],
1054
+ add_special_tokens: bool = True,
1055
+ padding: Union[bool, str, PaddingStrategy] = False,
1056
+ truncation: Union[bool, str] = None,
1057
+ max_length: Optional[int] = None,
1058
+ pad_to_multiple_of: Optional[int] = None,
1059
+ return_tensors: Optional[Union[str, TensorType]] = None,
1060
+ return_token_type_ids: Optional[bool] = None,
1061
+ return_attention_mask: Optional[bool] = None,
1062
+ return_overflowing_tokens: bool = False,
1063
+ return_special_tokens_mask: bool = False,
1064
+ return_offsets_mapping: bool = False,
1065
+ return_length: bool = False,
1066
+ verbose: bool = True,
1067
+ **kwargs,
1068
+ ) -> BatchEncoding:
1069
+ """
1070
+ Prepare answer strings for the model.
1071
+
1072
+ Args:
1073
+ answer `List[str]`:
1074
+ Corresponding answer supervision to the queries for training the model.
1075
+ """
1076
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
1077
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
1078
+ padding=padding,
1079
+ truncation=truncation,
1080
+ max_length=max_length,
1081
+ pad_to_multiple_of=pad_to_multiple_of,
1082
+ verbose=verbose,
1083
+ **kwargs,
1084
+ )
1085
+
1086
+ return self._target_batch_encode_plus(
1087
+ answer=answer,
1088
+ add_special_tokens=add_special_tokens,
1089
+ padding_strategy=padding_strategy,
1090
+ truncation_strategy=truncation_strategy,
1091
+ max_length=max_length,
1092
+ pad_to_multiple_of=pad_to_multiple_of,
1093
+ return_tensors=return_tensors,
1094
+ return_token_type_ids=return_token_type_ids,
1095
+ return_attention_mask=return_attention_mask,
1096
+ return_overflowing_tokens=return_overflowing_tokens,
1097
+ return_special_tokens_mask=return_special_tokens_mask,
1098
+ return_offsets_mapping=return_offsets_mapping,
1099
+ return_length=return_length,
1100
+ verbose=verbose,
1101
+ **kwargs,
1102
+ )
1103
+
1104
+ def _target_batch_encode_plus(
1105
+ self,
1106
+ answer: List[str],
1107
+ add_special_tokens: bool = True,
1108
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1109
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
1110
+ max_length: Optional[int] = None,
1111
+ stride: int = 0,
1112
+ pad_to_multiple_of: Optional[int] = None,
1113
+ return_tensors: Optional[Union[str, TensorType]] = None,
1114
+ return_token_type_ids: Optional[bool] = None,
1115
+ return_attention_mask: Optional[bool] = None,
1116
+ return_overflowing_tokens: bool = False,
1117
+ return_special_tokens_mask: bool = False,
1118
+ return_offsets_mapping: bool = False,
1119
+ return_length: bool = False,
1120
+ verbose: bool = True,
1121
+ **kwargs,
1122
+ ) -> BatchEncoding:
1123
+ batch_outputs = {}
1124
+ for text in answer:
1125
+ if self.do_lower_case:
1126
+ text = text.lower()
1127
+
1128
+ tokens = self.tokenize(text)
1129
+ outputs = self.prepare_for_model(
1130
+ ids=self.convert_tokens_to_ids(tokens),
1131
+ add_special_tokens=add_special_tokens,
1132
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
1133
+ truncation=truncation_strategy.value,
1134
+ max_length=max_length,
1135
+ stride=stride,
1136
+ pad_to_multiple_of=None, # we pad in batch afterwards
1137
+ return_attention_mask=False, # we pad in batch afterwards
1138
+ return_token_type_ids=return_token_type_ids,
1139
+ return_overflowing_tokens=return_overflowing_tokens,
1140
+ return_special_tokens_mask=return_special_tokens_mask,
1141
+ return_length=return_length,
1142
+ return_tensors=None, # We convert the whole batch to tensors at the end
1143
+ prepend_batch_axis=False,
1144
+ verbose=verbose,
1145
+ )
1146
+
1147
+ for key, value in outputs.items():
1148
+ if key not in batch_outputs:
1149
+ batch_outputs[key] = []
1150
+ batch_outputs[key].append(value)
1151
+
1152
+ batch_outputs = self.pad(
1153
+ batch_outputs,
1154
+ padding=padding_strategy.value,
1155
+ max_length=max_length,
1156
+ pad_to_multiple_of=pad_to_multiple_of,
1157
+ return_attention_mask=return_attention_mask,
1158
+ )
1159
+
1160
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
1161
+
1162
+ return BatchEncoding(batch_outputs)
1163
+
1164
+ def target_encode(
1165
+ self,
1166
+ answer: str,
1167
+ add_special_tokens: bool = True,
1168
+ padding: Union[bool, str, PaddingStrategy] = False,
1169
+ truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
1170
+ max_length: Optional[int] = None,
1171
+ return_tensors: Optional[Union[str, TensorType]] = None,
1172
+ **kwargs,
1173
+ ) -> List[int]:
1174
+ """
1175
+ Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
1176
+ which are necessary for the model to work correctly. Use this method if you want to build your processing on
1177
+ your own, otherwise refer to `__call__`.
1178
+
1179
+ Args:
1180
+ answer `str`:
1181
+ Corresponding answer supervision to the queries for training the model
1182
+ """
1183
+ encoded_outputs = self.target_encode_plus(
1184
+ answer=answer,
1185
+ add_special_tokens=add_special_tokens,
1186
+ padding=padding,
1187
+ truncation=truncation,
1188
+ max_length=max_length,
1189
+ return_tensors=return_tensors,
1190
+ **kwargs,
1191
+ )
1192
+
1193
+ return encoded_outputs["input_ids"]
1194
+
1195
+ def target_encode_plus(
1196
+ self,
1197
+ answer: str,
1198
+ add_special_tokens: bool = True,
1199
+ padding: Union[bool, str, PaddingStrategy] = False,
1200
+ truncation: Union[bool, str] = None,
1201
+ max_length: Optional[int] = None,
1202
+ pad_to_multiple_of: Optional[int] = None,
1203
+ return_tensors: Optional[Union[str, TensorType]] = None,
1204
+ return_token_type_ids: Optional[bool] = None,
1205
+ return_attention_mask: Optional[bool] = None,
1206
+ return_special_tokens_mask: bool = False,
1207
+ return_offsets_mapping: bool = False,
1208
+ return_length: bool = False,
1209
+ verbose: bool = True,
1210
+ **kwargs,
1211
+ ) -> BatchEncoding:
1212
+ """
1213
+ Prepare a answer string for the model.
1214
+
1215
+ Args:
1216
+ answer `str`:
1217
+ Corresponding answer supervision to the queries for training the model.
1218
+ """
1219
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
1220
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
1221
+ padding=padding,
1222
+ truncation=truncation,
1223
+ max_length=max_length,
1224
+ pad_to_multiple_of=pad_to_multiple_of,
1225
+ verbose=verbose,
1226
+ **kwargs,
1227
+ )
1228
+
1229
+ return self._target_encode_plus(
1230
+ answer=answer,
1231
+ add_special_tokens=add_special_tokens,
1232
+ padding_strategy=padding_strategy,
1233
+ truncation_strategy=truncation_strategy,
1234
+ max_length=max_length,
1235
+ pad_to_multiple_of=pad_to_multiple_of,
1236
+ return_tensors=return_tensors,
1237
+ return_token_type_ids=return_token_type_ids,
1238
+ return_attention_mask=return_attention_mask,
1239
+ return_special_tokens_mask=return_special_tokens_mask,
1240
+ return_offsets_mapping=return_offsets_mapping,
1241
+ return_length=return_length,
1242
+ verbose=verbose,
1243
+ **kwargs,
1244
+ )
1245
+
1246
+ def _target_encode_plus(
1247
+ self,
1248
+ answer: str,
1249
+ add_special_tokens: bool = True,
1250
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
1251
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
1252
+ max_length: Optional[int] = None,
1253
+ stride: int = 0,
1254
+ pad_to_multiple_of: Optional[int] = None,
1255
+ return_tensors: Optional[Union[str, TensorType]] = None,
1256
+ return_token_type_ids: Optional[bool] = None,
1257
+ return_attention_mask: Optional[bool] = None,
1258
+ return_overflowing_tokens: bool = False,
1259
+ return_special_tokens_mask: bool = False,
1260
+ return_offsets_mapping: bool = False,
1261
+ return_length: bool = False,
1262
+ verbose: bool = True,
1263
+ **kwargs,
1264
+ ) -> BatchEncoding:
1265
+ if return_offsets_mapping:
1266
+ raise NotImplementedError(
1267
+ "return_offset_mapping is not available when using Python tokenizers. "
1268
+ "To use this feature, change your tokenizer to one deriving from "
1269
+ "transformers.PreTrainedTokenizerFast. "
1270
+ "More information on available tokenizers at "
1271
+ "https://github.com/huggingface/transformers/pull/2674"
1272
+ )
1273
+
1274
+ text = answer
1275
+
1276
+ # if necessary, perform lower case
1277
+ if self.do_lower_case:
1278
+ text = text.lower()
1279
+
1280
+ tokens = self.tokenize(text)
1281
+
1282
+ return self.prepare_for_model(
1283
+ ids=self.convert_tokens_to_ids(tokens),
1284
+ add_special_tokens=add_special_tokens,
1285
+ padding=padding_strategy.value,
1286
+ truncation=truncation_strategy.value,
1287
+ max_length=max_length,
1288
+ stride=stride,
1289
+ pad_to_multiple_of=pad_to_multiple_of,
1290
+ return_tensors=return_tensors,
1291
+ prepend_batch_axis=True,
1292
+ return_attention_mask=return_attention_mask,
1293
+ return_token_type_ids=return_token_type_ids,
1294
+ return_overflowing_tokens=return_overflowing_tokens,
1295
+ return_special_tokens_mask=return_special_tokens_mask,
1296
+ return_length=return_length,
1297
+ verbose=verbose,
1298
+ )
1299
+
1300
+ def prepare_table_query(
1301
+ self,
1302
+ table,
1303
+ query,
1304
+ answer=None,
1305
+ truncation_strategy=Union[str, TruncationStrategy, TapexTruncationStrategy],
1306
+ max_length=None,
1307
+ ):
1308
+ """
1309
+ This method can be used to linearize a table and add a corresponding query.
1310
+
1311
+ Optionally, it also handles truncation of the table (cells).
1312
+
1313
+ An answer can be provided for more precise truncation.
1314
+ """
1315
+ if not table.empty:
1316
+ # step 1: create table dictionary
1317
+ table_content = {"header": list(table.columns), "rows": [list(row.values) for i, row in table.iterrows()]}
1318
+
1319
+ # step 2: modify table internally
1320
+ # always truncate table cells based on self.max_cell_length
1321
+ # optionally truncate rows if truncation_strategy is set to it
1322
+ self.truncate_table_cells(table_content, query, answer)
1323
+ if truncation_strategy == TapexTruncationStrategy.DROP_ROWS_TO_FIT:
1324
+ self.truncate_table_rows(table_content, query, answer, max_length=max_length)
1325
+
1326
+ # step 3: linearize table
1327
+ linear_table = self.table_linearize.process_table(table_content)
1328
+ else:
1329
+ linear_table = ""
1330
+
1331
+ if linear_table == "":
1332
+ logger.warning(
1333
+ "You provide an empty table, or all cells contain much tokens (e.g., >= 1024 tokens). "
1334
+ + f"Please carefully check the corresponding table with the query : {query}."
1335
+ )
1336
+ if query == "":
1337
+ logger.warning("You provide nothing to query with respect to the table.")
1338
+ # step 4: concatenate query with linear_table
1339
+ separator = " " if query and linear_table else ""
1340
+ joint_input = (query + separator + linear_table) if query else linear_table
1341
+
1342
+ return joint_input
1343
+
1344
+ def truncate_table_cells(self, table_content: Dict, question: str, answer: List):
1345
+ # TODO (Qian): is it possible to revert the original cell if it is in the final answer?
1346
+ cell_mapping = {}
1347
+ for row in table_content["rows"]:
1348
+ for i, cell in enumerate(row):
1349
+ truncate_cell = self.truncate_cell(cell)
1350
+ if truncate_cell is not None:
1351
+ cell_mapping[cell] = truncate_cell
1352
+ row[i] = truncate_cell
1353
+
1354
+ # modify the answer list
1355
+ if answer is not None:
1356
+ for i, case in enumerate(answer):
1357
+ if case in cell_mapping.keys():
1358
+ answer[i] = cell_mapping[case]
1359
+
1360
+ def truncate_cell(self, cell_value):
1361
+ # do not process on these cases
1362
+ if isinstance(cell_value, int) or isinstance(cell_value, float):
1363
+ return cell_value
1364
+ if cell_value.strip() != "":
1365
+ try_tokens = self.tokenize(cell_value)
1366
+ if len(try_tokens) >= self.max_cell_length:
1367
+ retain_tokens = try_tokens[: self.max_cell_length]
1368
+ retain_cell_value = self.convert_tokens_to_string(retain_tokens)
1369
+ return retain_cell_value
1370
+ else:
1371
+ return None
1372
+ else:
1373
+ return cell_value
1374
+
1375
+ def truncate_table_rows(
1376
+ self, table_content: Dict, question: str, answer: Optional[Union[str, List[str]]] = None, max_length=None
1377
+ ):
1378
+ """
1379
+ Args:
1380
+ table_content:
1381
+ {"header": xxx, "rows": xxx, "id" (Optionally): xxx}
1382
+
1383
+ question:
1384
+ natural language sentence
1385
+
1386
+ answer:
1387
+ if for training, is the supervision; otherwise will be empty
1388
+ """
1389
+ delete_ratio, remain_token_len = self.estimate_delete_ratio(table_content, question, max_length)
1390
+ # randomly delete unrelated rows
1391
+ self.delete_unrelated_rows(table_content, question, answer, delete_ratio)
1392
+ # guarantee the result < max_length
1393
+ maximum_keep_rows = 0
1394
+ for ind, row_example in enumerate(table_content["rows"]):
1395
+ value_string = self.table_linearize.process_row(row_example, ind + 1)
1396
+ value_token_len = len(self.tokenize(value_string))
1397
+ # over the size limit, and take action
1398
+ if value_token_len > remain_token_len:
1399
+ break
1400
+ remain_token_len -= value_token_len
1401
+ maximum_keep_rows += 1
1402
+ del table_content["rows"][maximum_keep_rows:]
1403
+
1404
+ def estimate_delete_ratio(self, table_content: Dict, question: str, max_length=None):
1405
+ if "header" not in table_content or "rows" not in table_content:
1406
+ raise ValueError("The table content should contain both 'header' and 'rows' keys.")
1407
+ # calculate the tokens of header, special tokens will only be pre-prepended into question
1408
+ question_tokens = self.tokenize(question, add_special_tokens=True)
1409
+ # calculate the tokens of header
1410
+ header_string = self.table_linearize.process_header(table_content["header"])
1411
+ header_tokens = self.tokenize(header_string, add_special_tokens=False)
1412
+ # split all cell values into tokens and see how many can be accommodated
1413
+ used_token_len = len(question_tokens) + len(header_tokens)
1414
+ # remaining token space for rows
1415
+ remain_token_len = max_length - used_token_len
1416
+
1417
+ value_string = ""
1418
+ for _, row_example in enumerate(table_content["rows"]):
1419
+ # use a general index to roughly estimate the overall token len
1420
+ value_string += self.table_linearize.process_row(row_example, 100) + " "
1421
+ value_token_len = len(self.tokenize(value_string))
1422
+
1423
+ if value_token_len < remain_token_len:
1424
+ # no row will be deleted
1425
+ return 0.0, remain_token_len
1426
+ else:
1427
+ # calc a roughly delete rate
1428
+ return 1.0 - remain_token_len / value_token_len, remain_token_len
1429
+
1430
+ def delete_unrelated_rows(self, table_content: Dict, question: str, answer: List, delete_ratio: float):
1431
+ """
1432
+ The argument answer is used only during training.
1433
+ """
1434
+ truncated_unrelated_indices = []
1435
+ related_indices = []
1436
+ if answer is None or len(answer) == 0:
1437
+ answer_set = set()
1438
+ else:
1439
+ answer_set = {ans_ex.lower() for ans_ex in answer}
1440
+ # add question key words into answer set
1441
+ if question is not None:
1442
+ answer_set.update(question.split())
1443
+ question_set = set(question.strip("?!.,").split(" "))
1444
+ row_max_len = len(table_content["rows"])
1445
+ for _row_idx, row in enumerate(table_content["rows"]):
1446
+ lower_row = {str(cell).lower() for cell in row}
1447
+ if len(lower_row & answer_set) == 0 and len(lower_row & question_set) == 0:
1448
+ truncated_unrelated_indices.append(_row_idx)
1449
+ else:
1450
+ # add neighbours to preserve information aggressively
1451
+ related_indices.extend([_row_idx - 2, _row_idx - 1, _row_idx, _row_idx + 1, _row_idx + 2])
1452
+
1453
+ # remove the neighbours
1454
+ truncated_unrelated_indices = [
1455
+ _row_idx for _row_idx in truncated_unrelated_indices if _row_idx not in related_indices
1456
+ ]
1457
+ # select some cases to drop
1458
+ drop_items = min(len(truncated_unrelated_indices), int(len(table_content["rows"]) * delete_ratio))
1459
+ drop_row_indices = random.choices(truncated_unrelated_indices, k=drop_items)
1460
+
1461
+ for _row_idx in reversed(range(row_max_len)):
1462
+ if _row_idx in drop_row_indices:
1463
+ del table_content["rows"][_row_idx]
1464
+
1465
+ # only when the drop ratio is too large, logging for warning.
1466
+ if "id" in table_content and len(drop_row_indices) > 0:
1467
+ logger.warning("Delete {:.2f} rows in table {}".format(len(drop_row_indices), table_content["id"]))
janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.23 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/__pycache__/configuration_tvlt.cpython-310.pyc ADDED
Binary file (7.14 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/configuration_tvlt.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
24
+ class TvltConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`TvltModel`]. It is used to instantiate a TVLT
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the TVLT
29
+ [ZinengTang/tvlt-base](https://huggingface.co/ZinengTang/tvlt-base) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ image_size (`int`, *optional*, defaults to 224):
36
+ The size (resolution) of each image.
37
+ spectrogram_length (`int`, *optional*, defaults to 2048):
38
+ The time length of each audio spectrogram.
39
+ frequency_length (`int`, *optional*, defaults to 128):
40
+ The frequency length of audio spectrogram.
41
+ image_patch_size (`List[int]`, *optional*, defaults to `[16, 16]`):
42
+ The size (resolution) of each image patch.
43
+ audio_patch_size (`List[int]`, *optional*, defaults to `[16, 16]`):
44
+ The size (resolution) of each audio patch.
45
+ num_image_channels (`int`, *optional*, defaults to 3):
46
+ The number of input image channels.
47
+ num_audio_channels (`int`, *optional*, defaults to 1):
48
+ The number of input audio channels.
49
+ num_frames (`int`, *optional*, defaults to 8):
50
+ The maximum number of frames for an input video.
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_prob (`float`, *optional*, defaults to 0.0):
63
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
64
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
65
+ The dropout ratio for the attention probabilities.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the layer normalization layers.
70
+ qkv_bias (`bool`, *optional*, defaults to `True`):
71
+ Whether to add a bias to the queries, keys and values.
72
+ use_mean_pooling (`bool`, *optional*, defaults to `False`):
73
+ Whether to mean pool the final hidden states instead of using the final hidden state of the [CLS] token.
74
+ decoder_num_attention_heads (`int`, *optional*, defaults to 16):
75
+ Number of attention heads for each attention layer in the decoder.
76
+ decoder_hidden_size (`int`, *optional*, defaults to 512):
77
+ Dimensionality of the decoder.
78
+ decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
79
+ Number of hidden layers in the decoder.
80
+ decoder_intermediate_size (`int`, *optional*, defaults to 2048):
81
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
82
+ pixel_mask_ratio (`float`, *optional*, defaults to 0.75):
83
+ Image patch masking ratio.
84
+ audio_mask_ratio (`float`, *optional*, defaults to 0.15):
85
+ Audio patch masking ratio.
86
+ audio_mask_type (`str`, *optional*, defaults to `"frame-level"`):
87
+ Audio patch masking type, choose between "frame-level" and "patch-level".
88
+ task_matching (`bool`, *optional*, defaults to `True`):
89
+ Whether to use vision audio matching task in pretraining.
90
+ task_mae (`bool`, *optional*, defaults to `True`):
91
+ Whether to use the masked auto-encoder (MAE) in pretraining.
92
+ loss_type (`str`, *optional*, defaults to `"classification"`):
93
+ Loss types including regression and classification.
94
+
95
+ Example:
96
+
97
+ ```python
98
+ >>> from transformers import TvltConfig, TvltModel
99
+
100
+ >>> # # Initializing a TVLT ZinengTang/tvlt-base style configuration
101
+ >>> configuration = TvltConfig()
102
+
103
+ >>> # # Initializing a model (with random weights) from the ZinengTang/tvlt-base style configuration
104
+ >>> model = TvltModel(configuration)
105
+
106
+ >>> # Accessing the model configuration
107
+ >>> configuration = model.config
108
+ ```"""
109
+
110
+ model_type = "tvlt"
111
+
112
+ def __init__(
113
+ self,
114
+ image_size=224,
115
+ spectrogram_length=2048,
116
+ frequency_length=128,
117
+ image_patch_size=[16, 16],
118
+ audio_patch_size=[16, 16],
119
+ num_image_channels=3,
120
+ num_audio_channels=1,
121
+ num_frames=8,
122
+ hidden_size=768,
123
+ num_hidden_layers=12,
124
+ num_attention_heads=12,
125
+ intermediate_size=3072,
126
+ hidden_act="gelu",
127
+ hidden_dropout_prob=0.0,
128
+ attention_probs_dropout_prob=0.0,
129
+ initializer_range=0.02,
130
+ layer_norm_eps=1e-6,
131
+ qkv_bias=True,
132
+ use_mean_pooling=False,
133
+ decoder_num_attention_heads=16,
134
+ decoder_hidden_size=512,
135
+ decoder_num_hidden_layers=8,
136
+ decoder_intermediate_size=2048,
137
+ pixel_mask_ratio=0.75,
138
+ audio_mask_ratio=0.15,
139
+ audio_mask_type="frame-level",
140
+ task_matching=True,
141
+ task_mae=True,
142
+ loss_type="classification",
143
+ **kwargs,
144
+ ):
145
+ super().__init__(**kwargs)
146
+
147
+ if audio_mask_type not in ("frame-level", "patch_level"):
148
+ raise ValueError(
149
+ "audio_mask_type must be one of two acceptable strategies - {'frame_level', 'patch-level') "
150
+ f"got {audio_mask_type}"
151
+ )
152
+
153
+ self.image_size = image_size
154
+ self.spectrogram_length = spectrogram_length
155
+ self.frequency_length = frequency_length
156
+ self.image_patch_size = image_patch_size
157
+ self.audio_patch_size = audio_patch_size
158
+ self.num_image_channels = num_image_channels
159
+ self.num_audio_channels = num_audio_channels
160
+ self.num_frames = num_frames
161
+
162
+ self.hidden_size = hidden_size
163
+ self.num_hidden_layers = num_hidden_layers
164
+ self.num_attention_heads = num_attention_heads
165
+ self.intermediate_size = intermediate_size
166
+ self.hidden_act = hidden_act
167
+ self.hidden_dropout_prob = hidden_dropout_prob
168
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
169
+ self.initializer_range = initializer_range
170
+ self.layer_norm_eps = layer_norm_eps
171
+ self.qkv_bias = qkv_bias
172
+ self.use_mean_pooling = use_mean_pooling
173
+
174
+ self.decoder_num_attention_heads = decoder_num_attention_heads
175
+ self.decoder_hidden_size = decoder_hidden_size
176
+ self.decoder_num_hidden_layers = decoder_num_hidden_layers
177
+ self.decoder_intermediate_size = decoder_intermediate_size
178
+ self.pixel_mask_ratio = pixel_mask_ratio
179
+ self.audio_mask_ratio = audio_mask_ratio
180
+ self.audio_mask_type = audio_mask_type
181
+
182
+ self.task_matching = task_matching
183
+ self.task_mae = task_mae
184
+ self.loss_type = loss_type
janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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`, *optional*, defaults to 128):
45
+ The frequency length of audio spectrogram.
46
+ sampling_rate (`int`, *optional*, 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`, *optional*, 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`, *optional*, 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. Must be mono channel audio, not
133
+ stereo, i.e. single float per timestep.
134
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
135
+ If set, will return tensors instead of list of python integers. Acceptable values are:
136
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
137
+ - `'np'`: Return Numpy `np.ndarray` objects.
138
+ return_attention_mask (`bool`, *optional*, default to `True`):
139
+ Whether to return the attention mask. If left to the default, will return the attention mask according
140
+ to the specific feature_extractor's default. [What are attention masks?](../glossary#attention-mask)
141
+
142
+ <Tip>
143
+
144
+ For TvltTransformer models, `attention_mask` should alwys be passed for batched inference, to avoid
145
+ subtle bugs.
146
+
147
+ </Tip>
148
+
149
+ sampling_rate (`int`, *optional*):
150
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
151
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
152
+ pipeline. Current model supports sampling rate 16000 and 44100.
153
+ resample (`bool`, *optional*, defaults to `False`):
154
+ If the sampling rate is not matched, resample the input audio to match.
155
+ mask_audio (`bool`, *optional*, defaults to `False`):
156
+ Whether or not to mask input audio for MAE task.
157
+
158
+ Returns:
159
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
160
+
161
+ - **audio_values** -- Audio values to be fed to a model, of shape (batch_size, num_channels, height,
162
+ width).
163
+
164
+ - **audio_mask** -- Audio masks to be fed to a model, of shape (batch_size, num_audio_patches).
165
+ """
166
+
167
+ if sampling_rate is not None:
168
+ if sampling_rate != self.sampling_rate:
169
+ raise ValueError(
170
+ "This feature extractor is set to support sampling rate"
171
+ f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
172
+ f" with {self.sampling_rate} and not {sampling_rate}."
173
+ )
174
+ else:
175
+ logger.warning(
176
+ "It is strongly recommended to pass the `sampling_rate` argument to this function. "
177
+ "Failing to do so can result in silent errors that might be hard to debug."
178
+ )
179
+
180
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
181
+ if is_batched_numpy and len(raw_speech.shape) > 2:
182
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
183
+ is_batched = is_batched_numpy or (
184
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
185
+ )
186
+ if is_batched:
187
+ raw_speech = [np.asarray([speech], dtype=np.float32).T for speech in raw_speech]
188
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
189
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
190
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
191
+ raw_speech = raw_speech.astype(np.float32)
192
+ # always return batch
193
+ if not is_batched:
194
+ raw_speech = [np.asarray([raw_speech]).T]
195
+
196
+ # Convert audio signals to log mel spectrograms, truncate by time axis
197
+ audio_features = [
198
+ self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
199
+ ]
200
+ if isinstance(audio_features[0], List):
201
+ audio_features = [np.asarray(feature, dtype=np.float32) for feature in audio_features]
202
+
203
+ # Create audio attention mask
204
+ max_patch_len = max(
205
+ [ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features]
206
+ ) # The maximum number of audio patches in a batch
207
+ if return_attention_mask:
208
+ audio_mask = [
209
+ (ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
210
+ + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
211
+ for feature in audio_features
212
+ ]
213
+ audio_mask = np.array(audio_mask).astype(np.float32)
214
+
215
+ # convert into correct format for padding
216
+ max_time_len = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch
217
+ padded_audio_features = np.ones([len(audio_features), 1, max_time_len, self.feature_size]).astype(np.float32)
218
+ padded_audio_features = padded_audio_features * self.padding_value
219
+ for i in range(len(audio_features)):
220
+ feature = audio_features[i]
221
+ padded_audio_features[i, :, : feature.shape[0], :] = feature
222
+
223
+ # return as BatchFeature
224
+ if return_attention_mask:
225
+ data = {"audio_values": padded_audio_features, "audio_mask": audio_mask}
226
+ else:
227
+ data = {"audio_values": padded_audio_features}
228
+
229
+ encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
230
+ return encoded_inputs
janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/image_processing_tvlt.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ....image_transforms import (
23
+ get_resize_output_image_size,
24
+ resize,
25
+ to_channel_dimension_format,
26
+ )
27
+ from ....image_utils import (
28
+ IMAGENET_STANDARD_MEAN,
29
+ IMAGENET_STANDARD_STD,
30
+ ChannelDimension,
31
+ ImageInput,
32
+ PILImageResampling,
33
+ infer_channel_dimension_format,
34
+ is_scaled_image,
35
+ is_valid_image,
36
+ to_numpy_array,
37
+ valid_images,
38
+ validate_kwargs,
39
+ validate_preprocess_arguments,
40
+ )
41
+ from ....utils import TensorType, logging
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+
47
+ def make_batched(videos) -> List[List[ImageInput]]:
48
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)):
49
+ return videos
50
+
51
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
52
+ videos_dim = np.array(videos[0]).ndim
53
+ if videos_dim == 3:
54
+ return [videos]
55
+ elif videos_dim == 4:
56
+ return videos
57
+
58
+ elif is_valid_image(videos):
59
+ videos_dim = np.array(videos).ndim
60
+ if videos_dim == 3:
61
+ return [[videos]]
62
+ elif videos_dim == 4:
63
+ return [videos]
64
+ elif videos_dim == 5:
65
+ return videos
66
+
67
+ raise ValueError(f"Could not make batched video from {videos}")
68
+
69
+
70
+ class TvltImageProcessor(BaseImageProcessor):
71
+ r"""
72
+ Constructs a TVLT image processor.
73
+
74
+ This processor can be used to prepare either videos or images for the model by converting images to 1-frame videos.
75
+
76
+ Args:
77
+ do_resize (`bool`, *optional*, defaults to `True`):
78
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
79
+ `do_resize` parameter in the `preprocess` method.
80
+ size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
81
+ Size of the output image after resizing. The shortest edge of the image will be resized to
82
+ `size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overriden by
83
+ `size` in the `preprocess` method.
84
+ patch_size (`List[int]` *optional*, defaults to [16,16]):
85
+ The patch size of image patch embedding.
86
+ num_frames (`int` *optional*, defaults to 8):
87
+ The maximum number of video frames.
88
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
89
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
90
+ `preprocess` method.
91
+ do_center_crop (`bool`, *optional*, defaults to `True`):
92
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
93
+ parameter in the `preprocess` method.
94
+ crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
95
+ Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
96
+ `preprocess` method.
97
+ do_rescale (`bool`, *optional*, defaults to `True`):
98
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
99
+ parameter in the `preprocess` method.
100
+ rescale_factor (`int` or `float`, *optional*, defaults to 1/255):
101
+ Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
102
+ in the `preprocess` method.
103
+ do_normalize (`bool`, *optional*, defaults to `True`):
104
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
105
+ method.
106
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
107
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
108
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
109
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
110
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
111
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
112
+ """
113
+
114
+ model_input_names = [
115
+ "pixel_values",
116
+ "pixel_mask",
117
+ "pixel_values_mixed",
118
+ "pixel_mask_mixed",
119
+ ]
120
+
121
+ def __init__(
122
+ self,
123
+ do_resize: bool = True,
124
+ size: Dict[str, int] = None,
125
+ patch_size: List[int] = [16, 16],
126
+ num_frames: int = 8,
127
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
128
+ do_center_crop: bool = True,
129
+ crop_size: Dict[str, int] = None,
130
+ do_rescale: bool = True,
131
+ rescale_factor: Union[int, float] = 1 / 255,
132
+ do_normalize: bool = True,
133
+ image_mean: Optional[Union[float, List[float]]] = IMAGENET_STANDARD_MEAN,
134
+ image_std: Optional[Union[float, List[float]]] = IMAGENET_STANDARD_STD,
135
+ init_mask_generator=False,
136
+ **kwargs,
137
+ ) -> None:
138
+ super().__init__(**kwargs)
139
+ size = size if size is not None else {"shortest_edge": 224}
140
+ size = get_size_dict(size, default_to_square=False)
141
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
142
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
143
+
144
+ self.do_resize = do_resize
145
+ self.size = size
146
+ self.patch_size = patch_size
147
+ self.num_frames = num_frames
148
+ self.do_center_crop = do_center_crop
149
+ self.crop_size = crop_size
150
+ self.resample = resample
151
+ self.do_rescale = do_rescale
152
+ self.rescale_factor = rescale_factor
153
+ self.do_normalize = do_normalize
154
+ self.image_mean = image_mean
155
+ self.image_std = image_std
156
+ self._valid_processor_keys = [
157
+ "videos",
158
+ "do_resize",
159
+ "size",
160
+ "patch_size",
161
+ "num_frames",
162
+ "resample",
163
+ "do_center_crop",
164
+ "crop_size",
165
+ "do_rescale",
166
+ "rescale_factor",
167
+ "do_normalize",
168
+ "image_mean",
169
+ "image_std",
170
+ "is_mixed",
171
+ "return_tensors",
172
+ "data_format",
173
+ "input_data_format",
174
+ ]
175
+
176
+ def resize(
177
+ self,
178
+ image: np.ndarray,
179
+ size: Dict[str, int],
180
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
181
+ data_format: Optional[Union[str, ChannelDimension]] = None,
182
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
183
+ **kwargs,
184
+ ) -> np.ndarray:
185
+ """
186
+ Resize an image.
187
+
188
+ Args:
189
+ image (`np.ndarray`):
190
+ Image to resize.
191
+ size (`Dict[str, int]`):
192
+ Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
193
+ have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
194
+ shortest edge of length `s` while keeping the aspect ratio of the original image.
195
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
196
+ Resampling filter to use when resiizing the image.
197
+ data_format (`str` or `ChannelDimension`, *optional*):
198
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
199
+ input_data_format (`str` or `ChannelDimension`, *optional*):
200
+ The channel dimension format of the input image. If not provided, it will be inferred.
201
+ """
202
+ size = get_size_dict(size, default_to_square=False)
203
+ if "shortest_edge" in size:
204
+ output_size = get_resize_output_image_size(
205
+ image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
206
+ )
207
+ elif "height" in size and "width" in size:
208
+ output_size = (size["height"], size["width"])
209
+ else:
210
+ raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
211
+ return resize(
212
+ image,
213
+ size=output_size,
214
+ resample=resample,
215
+ data_format=data_format,
216
+ input_data_format=input_data_format,
217
+ **kwargs,
218
+ )
219
+
220
+ def _preprocess_image(
221
+ self,
222
+ image: ImageInput,
223
+ do_resize: bool = None,
224
+ size: Dict[str, int] = None,
225
+ resample: PILImageResampling = None,
226
+ do_center_crop: bool = None,
227
+ crop_size: Dict[str, int] = None,
228
+ do_rescale: bool = None,
229
+ rescale_factor: float = None,
230
+ do_normalize: bool = None,
231
+ image_mean: Optional[Union[float, List[float]]] = None,
232
+ image_std: Optional[Union[float, List[float]]] = None,
233
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
234
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
235
+ ) -> np.ndarray:
236
+ """Preprocesses a single image."""
237
+
238
+ validate_preprocess_arguments(
239
+ do_rescale=do_rescale,
240
+ rescale_factor=rescale_factor,
241
+ do_normalize=do_normalize,
242
+ image_mean=image_mean,
243
+ image_std=image_std,
244
+ do_center_crop=do_center_crop,
245
+ crop_size=crop_size,
246
+ do_resize=do_resize,
247
+ size=size,
248
+ resample=resample,
249
+ )
250
+
251
+ # All transformations expect numpy arrays.
252
+ image = to_numpy_array(image)
253
+
254
+ if do_rescale and is_scaled_image(image):
255
+ logger.warning_once(
256
+ "It looks like you are trying to rescale already rescaled images. If the input"
257
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
258
+ )
259
+
260
+ if input_data_format is None:
261
+ input_data_format = infer_channel_dimension_format(image)
262
+
263
+ if do_resize:
264
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
265
+
266
+ if do_center_crop:
267
+ image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
268
+
269
+ if do_rescale:
270
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
271
+
272
+ if do_normalize:
273
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
274
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
275
+ return image
276
+
277
+ def preprocess(
278
+ self,
279
+ videos: ImageInput,
280
+ do_resize: bool = None,
281
+ size: Dict[str, int] = None,
282
+ patch_size: List[int] = None,
283
+ num_frames: int = None,
284
+ resample: PILImageResampling = None,
285
+ do_center_crop: bool = None,
286
+ crop_size: Dict[str, int] = None,
287
+ do_rescale: bool = None,
288
+ rescale_factor: float = None,
289
+ do_normalize: bool = None,
290
+ image_mean: Optional[Union[float, List[float]]] = None,
291
+ image_std: Optional[Union[float, List[float]]] = None,
292
+ is_mixed: bool = False,
293
+ return_tensors: Optional[Union[str, TensorType]] = None,
294
+ data_format: ChannelDimension = ChannelDimension.FIRST,
295
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
296
+ **kwargs,
297
+ ) -> BatchFeature:
298
+ """
299
+ Preprocess an videos or image or batch of videos or images.
300
+
301
+ Args:
302
+ videos (`ImageInput`):
303
+ Images or videos to preprocess. Expects a single or batch of frames with pixel values ranging from 0 to
304
+ 255. If passing in frames with pixel values between 0 and 1, set `do_rescale=False`.
305
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
306
+ Whether to resize the image.
307
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
308
+ Size of the image after applying resize.
309
+ patch_size (`List[int]` *optional*, defaults to self.patch_size):
310
+ The patch size of image patch embedding.
311
+ num_frames (`int` *optional*, defaults to self.num_frames):
312
+ The maximum number of video frames.
313
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
314
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
315
+ has an effect if `do_resize` is set to `True`.
316
+ do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
317
+ Whether to centre crop the image.
318
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
319
+ Size of the image after applying the centre crop.
320
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
321
+ Whether to rescale the image values between [0 - 1].
322
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
323
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
324
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
325
+ Whether to normalize the image.
326
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
327
+ Image mean.
328
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
329
+ Image standard deviation.
330
+ is_mixed (`bool`, *optional*):
331
+ If the input video has negative samples.
332
+ return_tensors (`str` or `TensorType`, *optional*):
333
+ The type of tensors to return. Can be one of:
334
+ - Unset: Return a list of `np.ndarray`.
335
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
336
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
337
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
338
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
339
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
340
+ The channel dimension format for the output image. Can be one of:
341
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
342
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
343
+ - Unset: Use the inferred channel dimension format of the input image.
344
+ input_data_format (`ChannelDimension` or `str`, *optional*):
345
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
346
+ from the input image. Can be one of:
347
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
348
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
349
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
350
+
351
+ Returns:
352
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
353
+
354
+ - **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
355
+ width).
356
+
357
+ - **pixel_mask** -- Pixel masks to be fed to a model, of shape (batch_size, num_pixel_patches).
358
+
359
+ - **pixel_values_mixed** -- Pixel values with both postive or negative to be fed to a model, of shape
360
+ (batch_size, num_channels, height, width).
361
+
362
+ - **pixel_mask_mixed** -- Pixel masks with both postive or negative to be fed to a model, of shape
363
+ (batch_size, num_pixel_patches).
364
+ """
365
+ do_resize = do_resize if do_resize is not None else self.do_resize
366
+ resample = resample if resample is not None else self.resample
367
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
368
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
369
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
370
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
371
+ image_mean = image_mean if image_mean is not None else self.image_mean
372
+ image_std = image_std if image_std is not None else self.image_std
373
+
374
+ size = size if size is not None else self.size
375
+ size = get_size_dict(size, default_to_square=False)
376
+ crop_size = crop_size if crop_size is not None else self.crop_size
377
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
378
+ patch_size = patch_size if patch_size is not None else self.patch_size
379
+ num_frames = num_frames if patch_size is not None else self.num_frames
380
+
381
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
382
+
383
+ if not valid_images(videos):
384
+ raise ValueError(
385
+ "Invalid image or video type. Must be of type PIL.Image.Image, numpy.ndarray, "
386
+ "torch.Tensor, tf.Tensor or jax.ndarray."
387
+ )
388
+
389
+ videos = make_batched(videos)
390
+
391
+ # Check number of frames is fewer than maximum frames
392
+ for video in videos:
393
+ if len(video) > self.num_frames:
394
+ raise ValueError(
395
+ f"number of frames must not be greater than the maximum frames of the model {self.num_frames}."
396
+ )
397
+
398
+ max_num_frames = max([len(video) for video in videos])
399
+ num_patches_per_image = (size["shortest_edge"] // patch_size[0]) ** 2
400
+ video_masks = np.array(
401
+ [
402
+ len(video) * num_patches_per_image * [1] + (max_num_frames - len(video)) * num_patches_per_image * [0]
403
+ for video in videos
404
+ ]
405
+ )
406
+
407
+ videos = [
408
+ [
409
+ self._preprocess_image(
410
+ image=img,
411
+ do_resize=do_resize,
412
+ size=size,
413
+ resample=resample,
414
+ do_center_crop=do_center_crop,
415
+ crop_size=crop_size,
416
+ do_rescale=do_rescale,
417
+ rescale_factor=rescale_factor,
418
+ do_normalize=do_normalize,
419
+ image_mean=image_mean,
420
+ image_std=image_std,
421
+ data_format=data_format,
422
+ input_data_format=input_data_format,
423
+ )
424
+ for img in video
425
+ ]
426
+ for video in videos
427
+ ]
428
+
429
+ # If videos contain both positive/negative, use mixed key for video-audio matching task
430
+ if is_mixed:
431
+ data = {"pixel_values_mixed": videos, "pixel_mask_mixed": video_masks}
432
+ else:
433
+ data = {"pixel_values": videos, "pixel_mask": video_masks}
434
+
435
+ return BatchFeature(data=data, tensor_type=return_tensors)
janus/lib/python3.10/site-packages/transformers/models/deprecated/tvlt/processing_tvlt.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
36
+ attributes = ["image_processor", "feature_extractor"]
37
+ image_processor_class = "TvltImageProcessor"
38
+ feature_extractor_class = "TvltFeatureExtractor"
39
+
40
+ def __init__(self, image_processor, feature_extractor):
41
+ super().__init__(image_processor=image_processor, feature_extractor=feature_extractor)
42
+
43
+ self.image_processor = image_processor
44
+ self.feature_extractor = feature_extractor
45
+
46
+ def __call__(
47
+ self,
48
+ images=None,
49
+ audio=None,
50
+ images_mixed=None,
51
+ sampling_rate=None,
52
+ mask_audio=False,
53
+ mask_pixel=False,
54
+ *args,
55
+ **kwargs,
56
+ ):
57
+ """
58
+ Forwards the `images` argument to TvltImageProcessor's [`~TvltImageProcessor.preprocess`] and the `audio`
59
+ argument to TvltFeatureExtractor's [`~TvltFeatureExtractor.__call__`]. Please refer to the docstring of the
60
+ above two methods for more information.
61
+ """
62
+
63
+ if images is None and audio is None:
64
+ raise ValueError("You need to specify either an `images` or `audio` input to process.")
65
+
66
+ images_mixed_dict = None
67
+ if images is not None:
68
+ images_dict = self.image_processor(images, mask_pixel=mask_pixel, *args, **kwargs)
69
+ if images_mixed is not None:
70
+ images_mixed_dict = self.image_processor(images_mixed, is_mixed=True, *args, **kwargs)
71
+ if audio is not None:
72
+ audio_dict = self.feature_extractor(
73
+ audio, *args, sampling_rate=sampling_rate, mask_audio=mask_audio, **kwargs
74
+ )
75
+
76
+ output_dict = {}
77
+ if audio is not None:
78
+ output_dict.update(audio_dict)
79
+ if images is not None:
80
+ output_dict.update(images_dict)
81
+ if images_mixed_dict is not None:
82
+ output_dict.update(images_mixed_dict)
83
+ return output_dict
84
+
85
+ @property
86
+ def model_input_names(self):
87
+ image_processor_input_names = self.image_processor.model_input_names
88
+ feature_extractor_input_names = self.feature_extractor.model_input_names
89
+ return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
janus/lib/python3.10/site-packages/transformers/models/dinat/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_dinat import *
22
+ from .modeling_dinat import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (534 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-310.pyc ADDED
Binary file (6.48 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-310.pyc ADDED
Binary file (32.5 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/dinat/configuration_dinat.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Dilated Neighborhood Attention Transformer model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+ from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class DinatConfig(BackboneConfigMixin, PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`DinatModel`]. It is used to instantiate a Dinat
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
29
+ defaults will yield a similar configuration to that of the Dinat
30
+ [shi-labs/dinat-mini-in1k-224](https://huggingface.co/shi-labs/dinat-mini-in1k-224) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ patch_size (`int`, *optional*, defaults to 4):
37
+ The size (resolution) of each patch. NOTE: Only patch size of 4 is supported at the moment.
38
+ num_channels (`int`, *optional*, defaults to 3):
39
+ The number of input channels.
40
+ embed_dim (`int`, *optional*, defaults to 64):
41
+ Dimensionality of patch embedding.
42
+ depths (`List[int]`, *optional*, defaults to `[3, 4, 6, 5]`):
43
+ Number of layers in each level of the encoder.
44
+ num_heads (`List[int]`, *optional*, defaults to `[2, 4, 8, 16]`):
45
+ Number of attention heads in each layer of the Transformer encoder.
46
+ kernel_size (`int`, *optional*, defaults to 7):
47
+ Neighborhood Attention kernel size.
48
+ dilations (`List[List[int]]`, *optional*, defaults to `[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]]`):
49
+ Dilation value of each NA layer in the Transformer encoder.
50
+ mlp_ratio (`float`, *optional*, defaults to 3.0):
51
+ Ratio of MLP hidden dimensionality to embedding dimensionality.
52
+ qkv_bias (`bool`, *optional*, defaults to `True`):
53
+ Whether or not a learnable bias should be added to the queries, keys and values.
54
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
55
+ The dropout probability for all fully connected layers in the embeddings and encoder.
56
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
57
+ The dropout ratio for the attention probabilities.
58
+ drop_path_rate (`float`, *optional*, defaults to 0.1):
59
+ Stochastic depth rate.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
61
+ The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
62
+ `"selu"` and `"gelu_new"` are supported.
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-05):
66
+ The epsilon used by the layer normalization layers.
67
+ layer_scale_init_value (`float`, *optional*, defaults to 0.0):
68
+ The initial value for the layer scale. Disabled if <=0.
69
+ out_features (`List[str]`, *optional*):
70
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
71
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
72
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
73
+ same order as defined in the `stage_names` attribute.
74
+ out_indices (`List[int]`, *optional*):
75
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
76
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
77
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
78
+ same order as defined in the `stage_names` attribute.
79
+
80
+ Example:
81
+
82
+ ```python
83
+ >>> from transformers import DinatConfig, DinatModel
84
+
85
+ >>> # Initializing a Dinat shi-labs/dinat-mini-in1k-224 style configuration
86
+ >>> configuration = DinatConfig()
87
+
88
+ >>> # Initializing a model (with random weights) from the shi-labs/dinat-mini-in1k-224 style configuration
89
+ >>> model = DinatModel(configuration)
90
+
91
+ >>> # Accessing the model configuration
92
+ >>> configuration = model.config
93
+ ```"""
94
+
95
+ model_type = "dinat"
96
+
97
+ attribute_map = {
98
+ "num_attention_heads": "num_heads",
99
+ "num_hidden_layers": "num_layers",
100
+ }
101
+
102
+ def __init__(
103
+ self,
104
+ patch_size=4,
105
+ num_channels=3,
106
+ embed_dim=64,
107
+ depths=[3, 4, 6, 5],
108
+ num_heads=[2, 4, 8, 16],
109
+ kernel_size=7,
110
+ dilations=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]],
111
+ mlp_ratio=3.0,
112
+ qkv_bias=True,
113
+ hidden_dropout_prob=0.0,
114
+ attention_probs_dropout_prob=0.0,
115
+ drop_path_rate=0.1,
116
+ hidden_act="gelu",
117
+ initializer_range=0.02,
118
+ layer_norm_eps=1e-5,
119
+ layer_scale_init_value=0.0,
120
+ out_features=None,
121
+ out_indices=None,
122
+ **kwargs,
123
+ ):
124
+ super().__init__(**kwargs)
125
+
126
+ self.patch_size = patch_size
127
+ self.num_channels = num_channels
128
+ self.embed_dim = embed_dim
129
+ self.depths = depths
130
+ self.num_layers = len(depths)
131
+ self.num_heads = num_heads
132
+ self.kernel_size = kernel_size
133
+ self.dilations = dilations
134
+ self.mlp_ratio = mlp_ratio
135
+ self.qkv_bias = qkv_bias
136
+ self.hidden_dropout_prob = hidden_dropout_prob
137
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
138
+ self.drop_path_rate = drop_path_rate
139
+ self.hidden_act = hidden_act
140
+ self.layer_norm_eps = layer_norm_eps
141
+ self.initializer_range = initializer_range
142
+ # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel
143
+ # this indicates the channel dimension after the last stage of the model
144
+ self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))
145
+ self.layer_scale_init_value = layer_scale_init_value
146
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
147
+ self._out_features, self._out_indices = get_aligned_output_features_output_indices(
148
+ out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
149
+ )
150
+
151
+
152
+ __all__ = ["DinatConfig"]
janus/lib/python3.10/site-packages/transformers/models/dinat/modeling_dinat.py ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 SHI Labs 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 Dilated Neighborhood Attention Transformer model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...modeling_outputs import BackboneOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
30
+ from ...utils import (
31
+ ModelOutput,
32
+ OptionalDependencyNotAvailable,
33
+ add_code_sample_docstrings,
34
+ add_start_docstrings,
35
+ add_start_docstrings_to_model_forward,
36
+ is_natten_available,
37
+ logging,
38
+ replace_return_docstrings,
39
+ requires_backends,
40
+ )
41
+ from ...utils.backbone_utils import BackboneMixin
42
+ from .configuration_dinat import DinatConfig
43
+
44
+
45
+ if is_natten_available():
46
+ from natten.functional import natten2dav, natten2dqkrpb
47
+ else:
48
+
49
+ def natten2dqkrpb(*args, **kwargs):
50
+ raise OptionalDependencyNotAvailable()
51
+
52
+ def natten2dav(*args, **kwargs):
53
+ raise OptionalDependencyNotAvailable()
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ # General docstring
59
+ _CONFIG_FOR_DOC = "DinatConfig"
60
+
61
+ # Base docstring
62
+ _CHECKPOINT_FOR_DOC = "shi-labs/dinat-mini-in1k-224"
63
+ _EXPECTED_OUTPUT_SHAPE = [1, 7, 7, 512]
64
+
65
+ # Image classification docstring
66
+ _IMAGE_CLASS_CHECKPOINT = "shi-labs/dinat-mini-in1k-224"
67
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
68
+
69
+
70
+ # drop_path and DinatDropPath are from the timm library.
71
+
72
+
73
+ @dataclass
74
+ class DinatEncoderOutput(ModelOutput):
75
+ """
76
+ Dinat encoder's outputs, with potential hidden states and attentions.
77
+
78
+ Args:
79
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
80
+ Sequence of hidden-states at the output of the last layer of the model.
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 stage) 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 stage) 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
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
93
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
94
+ shape `(batch_size, hidden_size, height, width)`.
95
+
96
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
97
+ include the spatial dimensions.
98
+ """
99
+
100
+ last_hidden_state: torch.FloatTensor = None
101
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
102
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
103
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
104
+
105
+
106
+ @dataclass
107
+ class DinatModelOutput(ModelOutput):
108
+ """
109
+ Dinat model's outputs that also contains a pooling of the last hidden states.
110
+
111
+ Args:
112
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
113
+ Sequence of hidden-states at the output of the last layer of the model.
114
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
115
+ Average pooling of the last layer hidden-state.
116
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
117
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
118
+ shape `(batch_size, sequence_length, hidden_size)`.
119
+
120
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
121
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
122
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
123
+ sequence_length)`.
124
+
125
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
126
+ heads.
127
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
128
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
129
+ shape `(batch_size, hidden_size, height, width)`.
130
+
131
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
132
+ include the spatial dimensions.
133
+ """
134
+
135
+ last_hidden_state: torch.FloatTensor = None
136
+ pooler_output: Optional[torch.FloatTensor] = None
137
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
138
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
139
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
140
+
141
+
142
+ @dataclass
143
+ class DinatImageClassifierOutput(ModelOutput):
144
+ """
145
+ Dinat outputs for image classification.
146
+
147
+ Args:
148
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
149
+ Classification (or regression if config.num_labels==1) loss.
150
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
151
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
152
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
153
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
154
+ shape `(batch_size, sequence_length, hidden_size)`.
155
+
156
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
157
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
158
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
159
+ sequence_length)`.
160
+
161
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
162
+ heads.
163
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
164
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
165
+ shape `(batch_size, hidden_size, height, width)`.
166
+
167
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
168
+ include the spatial dimensions.
169
+ """
170
+
171
+ loss: Optional[torch.FloatTensor] = None
172
+ logits: torch.FloatTensor = None
173
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
174
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
175
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
176
+
177
+
178
+ class DinatEmbeddings(nn.Module):
179
+ """
180
+ Construct the patch and position embeddings.
181
+ """
182
+
183
+ def __init__(self, config):
184
+ super().__init__()
185
+
186
+ self.patch_embeddings = DinatPatchEmbeddings(config)
187
+
188
+ self.norm = nn.LayerNorm(config.embed_dim)
189
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
190
+
191
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor]:
192
+ embeddings = self.patch_embeddings(pixel_values)
193
+ embeddings = self.norm(embeddings)
194
+
195
+ embeddings = self.dropout(embeddings)
196
+
197
+ return embeddings
198
+
199
+
200
+ class DinatPatchEmbeddings(nn.Module):
201
+ """
202
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
203
+ `hidden_states` (patch embeddings) of shape `(batch_size, height, width, hidden_size)` to be consumed by a
204
+ Transformer.
205
+ """
206
+
207
+ def __init__(self, config):
208
+ super().__init__()
209
+ patch_size = config.patch_size
210
+ num_channels, hidden_size = config.num_channels, config.embed_dim
211
+ self.num_channels = num_channels
212
+
213
+ if patch_size == 4:
214
+ pass
215
+ else:
216
+ # TODO: Support arbitrary patch sizes.
217
+ raise ValueError("Dinat only supports patch size of 4 at the moment.")
218
+
219
+ self.projection = nn.Sequential(
220
+ nn.Conv2d(self.num_channels, hidden_size // 2, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
221
+ nn.Conv2d(hidden_size // 2, hidden_size, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
222
+ )
223
+
224
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> torch.Tensor:
225
+ _, num_channels, height, width = pixel_values.shape
226
+ if num_channels != self.num_channels:
227
+ raise ValueError(
228
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
229
+ )
230
+ embeddings = self.projection(pixel_values)
231
+ embeddings = embeddings.permute(0, 2, 3, 1)
232
+
233
+ return embeddings
234
+
235
+
236
+ class DinatDownsampler(nn.Module):
237
+ """
238
+ Convolutional Downsampling Layer.
239
+
240
+ Args:
241
+ dim (`int`):
242
+ Number of input channels.
243
+ norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
244
+ Normalization layer class.
245
+ """
246
+
247
+ def __init__(self, dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
248
+ super().__init__()
249
+ self.dim = dim
250
+ self.reduction = nn.Conv2d(dim, 2 * dim, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
251
+ self.norm = norm_layer(2 * dim)
252
+
253
+ def forward(self, input_feature: torch.Tensor) -> torch.Tensor:
254
+ input_feature = self.reduction(input_feature.permute(0, 3, 1, 2)).permute(0, 2, 3, 1)
255
+ input_feature = self.norm(input_feature)
256
+ return input_feature
257
+
258
+
259
+ # Copied from transformers.models.beit.modeling_beit.drop_path
260
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
261
+ """
262
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
263
+
264
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
265
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
266
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
267
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
268
+ argument.
269
+ """
270
+ if drop_prob == 0.0 or not training:
271
+ return input
272
+ keep_prob = 1 - drop_prob
273
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
274
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
275
+ random_tensor.floor_() # binarize
276
+ output = input.div(keep_prob) * random_tensor
277
+ return output
278
+
279
+
280
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->Dinat
281
+ class DinatDropPath(nn.Module):
282
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
283
+
284
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
285
+ super().__init__()
286
+ self.drop_prob = drop_prob
287
+
288
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
289
+ return drop_path(hidden_states, self.drop_prob, self.training)
290
+
291
+ def extra_repr(self) -> str:
292
+ return "p={}".format(self.drop_prob)
293
+
294
+
295
+ class NeighborhoodAttention(nn.Module):
296
+ def __init__(self, config, dim, num_heads, kernel_size, dilation):
297
+ super().__init__()
298
+ if dim % num_heads != 0:
299
+ raise ValueError(
300
+ f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
301
+ )
302
+
303
+ self.num_attention_heads = num_heads
304
+ self.attention_head_size = int(dim / num_heads)
305
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
306
+ self.kernel_size = kernel_size
307
+ self.dilation = dilation
308
+
309
+ # rpb is learnable relative positional biases; same concept is used Swin.
310
+ self.rpb = nn.Parameter(torch.zeros(num_heads, (2 * self.kernel_size - 1), (2 * self.kernel_size - 1)))
311
+
312
+ self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
313
+ self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
314
+ self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
315
+
316
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
317
+
318
+ def transpose_for_scores(self, x):
319
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
320
+ x = x.view(new_x_shape)
321
+ return x.permute(0, 3, 1, 2, 4)
322
+
323
+ def forward(
324
+ self,
325
+ hidden_states: torch.Tensor,
326
+ output_attentions: Optional[bool] = False,
327
+ ) -> Tuple[torch.Tensor]:
328
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
329
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
330
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
331
+
332
+ # Apply the scale factor before computing attention weights. It's usually more efficient because
333
+ # attention weights are typically a bigger tensor compared to query.
334
+ # It gives identical results because scalars are commutable in matrix multiplication.
335
+ query_layer = query_layer / math.sqrt(self.attention_head_size)
336
+
337
+ # Compute NA between "query" and "key" to get the raw attention scores, and add relative positional biases.
338
+ attention_scores = natten2dqkrpb(query_layer, key_layer, self.rpb, self.kernel_size, self.dilation)
339
+
340
+ # Normalize the attention scores to probabilities.
341
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
342
+
343
+ # This is actually dropping out entire tokens to attend to, which might
344
+ # seem a bit unusual, but is taken from the original Transformer paper.
345
+ attention_probs = self.dropout(attention_probs)
346
+
347
+ context_layer = natten2dav(attention_probs, value_layer, self.kernel_size, self.dilation)
348
+ context_layer = context_layer.permute(0, 2, 3, 1, 4).contiguous()
349
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
350
+ context_layer = context_layer.view(new_context_layer_shape)
351
+
352
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
353
+
354
+ return outputs
355
+
356
+
357
+ class NeighborhoodAttentionOutput(nn.Module):
358
+ def __init__(self, config, dim):
359
+ super().__init__()
360
+ self.dense = nn.Linear(dim, dim)
361
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
362
+
363
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
364
+ hidden_states = self.dense(hidden_states)
365
+ hidden_states = self.dropout(hidden_states)
366
+
367
+ return hidden_states
368
+
369
+
370
+ class NeighborhoodAttentionModule(nn.Module):
371
+ def __init__(self, config, dim, num_heads, kernel_size, dilation):
372
+ super().__init__()
373
+ self.self = NeighborhoodAttention(config, dim, num_heads, kernel_size, dilation)
374
+ self.output = NeighborhoodAttentionOutput(config, dim)
375
+ self.pruned_heads = set()
376
+
377
+ def prune_heads(self, heads):
378
+ if len(heads) == 0:
379
+ return
380
+ heads, index = find_pruneable_heads_and_indices(
381
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
382
+ )
383
+
384
+ # Prune linear layers
385
+ self.self.query = prune_linear_layer(self.self.query, index)
386
+ self.self.key = prune_linear_layer(self.self.key, index)
387
+ self.self.value = prune_linear_layer(self.self.value, index)
388
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
389
+
390
+ # Update hyper params and store pruned heads
391
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
392
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
393
+ self.pruned_heads = self.pruned_heads.union(heads)
394
+
395
+ def forward(
396
+ self,
397
+ hidden_states: torch.Tensor,
398
+ output_attentions: Optional[bool] = False,
399
+ ) -> Tuple[torch.Tensor]:
400
+ self_outputs = self.self(hidden_states, output_attentions)
401
+ attention_output = self.output(self_outputs[0], hidden_states)
402
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
403
+ return outputs
404
+
405
+
406
+ class DinatIntermediate(nn.Module):
407
+ def __init__(self, config, dim):
408
+ super().__init__()
409
+ self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
410
+ if isinstance(config.hidden_act, str):
411
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
412
+ else:
413
+ self.intermediate_act_fn = config.hidden_act
414
+
415
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
416
+ hidden_states = self.dense(hidden_states)
417
+ hidden_states = self.intermediate_act_fn(hidden_states)
418
+ return hidden_states
419
+
420
+
421
+ class DinatOutput(nn.Module):
422
+ def __init__(self, config, dim):
423
+ super().__init__()
424
+ self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
425
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
426
+
427
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
428
+ hidden_states = self.dense(hidden_states)
429
+ hidden_states = self.dropout(hidden_states)
430
+ return hidden_states
431
+
432
+
433
+ class DinatLayer(nn.Module):
434
+ def __init__(self, config, dim, num_heads, dilation, drop_path_rate=0.0):
435
+ super().__init__()
436
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
437
+ self.kernel_size = config.kernel_size
438
+ self.dilation = dilation
439
+ self.window_size = self.kernel_size * self.dilation
440
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
441
+ self.attention = NeighborhoodAttentionModule(
442
+ config, dim, num_heads, kernel_size=self.kernel_size, dilation=self.dilation
443
+ )
444
+ self.drop_path = DinatDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
445
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
446
+ self.intermediate = DinatIntermediate(config, dim)
447
+ self.output = DinatOutput(config, dim)
448
+ self.layer_scale_parameters = (
449
+ nn.Parameter(config.layer_scale_init_value * torch.ones((2, dim)), requires_grad=True)
450
+ if config.layer_scale_init_value > 0
451
+ else None
452
+ )
453
+
454
+ def maybe_pad(self, hidden_states, height, width):
455
+ window_size = self.window_size
456
+ pad_values = (0, 0, 0, 0, 0, 0)
457
+ if height < window_size or width < window_size:
458
+ pad_l = pad_t = 0
459
+ pad_r = max(0, window_size - width)
460
+ pad_b = max(0, window_size - height)
461
+ pad_values = (0, 0, pad_l, pad_r, pad_t, pad_b)
462
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
463
+ return hidden_states, pad_values
464
+
465
+ def forward(
466
+ self,
467
+ hidden_states: torch.Tensor,
468
+ output_attentions: Optional[bool] = False,
469
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
470
+ batch_size, height, width, channels = hidden_states.size()
471
+ shortcut = hidden_states
472
+
473
+ hidden_states = self.layernorm_before(hidden_states)
474
+ # pad hidden_states if they are smaller than kernel size x dilation
475
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
476
+
477
+ _, height_pad, width_pad, _ = hidden_states.shape
478
+
479
+ attention_outputs = self.attention(hidden_states, output_attentions=output_attentions)
480
+
481
+ attention_output = attention_outputs[0]
482
+
483
+ was_padded = pad_values[3] > 0 or pad_values[5] > 0
484
+ if was_padded:
485
+ attention_output = attention_output[:, :height, :width, :].contiguous()
486
+
487
+ if self.layer_scale_parameters is not None:
488
+ attention_output = self.layer_scale_parameters[0] * attention_output
489
+
490
+ hidden_states = shortcut + self.drop_path(attention_output)
491
+
492
+ layer_output = self.layernorm_after(hidden_states)
493
+ layer_output = self.output(self.intermediate(layer_output))
494
+
495
+ if self.layer_scale_parameters is not None:
496
+ layer_output = self.layer_scale_parameters[1] * layer_output
497
+
498
+ layer_output = hidden_states + self.drop_path(layer_output)
499
+
500
+ layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
501
+ return layer_outputs
502
+
503
+
504
+ class DinatStage(nn.Module):
505
+ def __init__(self, config, dim, depth, num_heads, dilations, drop_path_rate, downsample):
506
+ super().__init__()
507
+ self.config = config
508
+ self.dim = dim
509
+ self.layers = nn.ModuleList(
510
+ [
511
+ DinatLayer(
512
+ config=config,
513
+ dim=dim,
514
+ num_heads=num_heads,
515
+ dilation=dilations[i],
516
+ drop_path_rate=drop_path_rate[i],
517
+ )
518
+ for i in range(depth)
519
+ ]
520
+ )
521
+
522
+ # patch merging layer
523
+ if downsample is not None:
524
+ self.downsample = downsample(dim=dim, norm_layer=nn.LayerNorm)
525
+ else:
526
+ self.downsample = None
527
+
528
+ self.pointing = False
529
+
530
+ def forward(
531
+ self,
532
+ hidden_states: torch.Tensor,
533
+ output_attentions: Optional[bool] = False,
534
+ ) -> Tuple[torch.Tensor]:
535
+ _, height, width, _ = hidden_states.size()
536
+ for i, layer_module in enumerate(self.layers):
537
+ layer_outputs = layer_module(hidden_states, output_attentions)
538
+ hidden_states = layer_outputs[0]
539
+
540
+ hidden_states_before_downsampling = hidden_states
541
+ if self.downsample is not None:
542
+ hidden_states = self.downsample(hidden_states_before_downsampling)
543
+
544
+ stage_outputs = (hidden_states, hidden_states_before_downsampling)
545
+
546
+ if output_attentions:
547
+ stage_outputs += layer_outputs[1:]
548
+ return stage_outputs
549
+
550
+
551
+ class DinatEncoder(nn.Module):
552
+ def __init__(self, config):
553
+ super().__init__()
554
+ self.num_levels = len(config.depths)
555
+ self.config = config
556
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
557
+ self.levels = nn.ModuleList(
558
+ [
559
+ DinatStage(
560
+ config=config,
561
+ dim=int(config.embed_dim * 2**i_layer),
562
+ depth=config.depths[i_layer],
563
+ num_heads=config.num_heads[i_layer],
564
+ dilations=config.dilations[i_layer],
565
+ drop_path_rate=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
566
+ downsample=DinatDownsampler if (i_layer < self.num_levels - 1) else None,
567
+ )
568
+ for i_layer in range(self.num_levels)
569
+ ]
570
+ )
571
+
572
+ def forward(
573
+ self,
574
+ hidden_states: torch.Tensor,
575
+ output_attentions: Optional[bool] = False,
576
+ output_hidden_states: Optional[bool] = False,
577
+ output_hidden_states_before_downsampling: Optional[bool] = False,
578
+ return_dict: Optional[bool] = True,
579
+ ) -> Union[Tuple, DinatEncoderOutput]:
580
+ all_hidden_states = () if output_hidden_states else None
581
+ all_reshaped_hidden_states = () if output_hidden_states else None
582
+ all_self_attentions = () if output_attentions else None
583
+
584
+ if output_hidden_states:
585
+ # rearrange b h w c -> b c h w
586
+ reshaped_hidden_state = hidden_states.permute(0, 3, 1, 2)
587
+ all_hidden_states += (hidden_states,)
588
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
589
+
590
+ for i, layer_module in enumerate(self.levels):
591
+ layer_outputs = layer_module(hidden_states, output_attentions)
592
+
593
+ hidden_states = layer_outputs[0]
594
+ hidden_states_before_downsampling = layer_outputs[1]
595
+
596
+ if output_hidden_states and output_hidden_states_before_downsampling:
597
+ # rearrange b h w c -> b c h w
598
+ reshaped_hidden_state = hidden_states_before_downsampling.permute(0, 3, 1, 2)
599
+ all_hidden_states += (hidden_states_before_downsampling,)
600
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
601
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
602
+ # rearrange b h w c -> b c h w
603
+ reshaped_hidden_state = hidden_states.permute(0, 3, 1, 2)
604
+ all_hidden_states += (hidden_states,)
605
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
606
+
607
+ if output_attentions:
608
+ all_self_attentions += layer_outputs[2:]
609
+
610
+ if not return_dict:
611
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
612
+
613
+ return DinatEncoderOutput(
614
+ last_hidden_state=hidden_states,
615
+ hidden_states=all_hidden_states,
616
+ attentions=all_self_attentions,
617
+ reshaped_hidden_states=all_reshaped_hidden_states,
618
+ )
619
+
620
+
621
+ class DinatPreTrainedModel(PreTrainedModel):
622
+ """
623
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
624
+ models.
625
+ """
626
+
627
+ config_class = DinatConfig
628
+ base_model_prefix = "dinat"
629
+ main_input_name = "pixel_values"
630
+
631
+ def _init_weights(self, module):
632
+ """Initialize the weights"""
633
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
634
+ # Slightly different from the TF version which uses truncated_normal for initialization
635
+ # cf https://github.com/pytorch/pytorch/pull/5617
636
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
637
+ if module.bias is not None:
638
+ module.bias.data.zero_()
639
+ elif isinstance(module, nn.LayerNorm):
640
+ module.bias.data.zero_()
641
+ module.weight.data.fill_(1.0)
642
+
643
+
644
+ DINAT_START_DOCSTRING = r"""
645
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
646
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
647
+ behavior.
648
+
649
+ Parameters:
650
+ config ([`DinatConfig`]): Model configuration class with all the parameters of the model.
651
+ Initializing with a config file does not load the weights associated with the model, only the
652
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
653
+ """
654
+
655
+ DINAT_INPUTS_DOCSTRING = r"""
656
+ Args:
657
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
658
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ViTImageProcessor.__call__`]
659
+ for details.
660
+
661
+ output_attentions (`bool`, *optional*):
662
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
663
+ tensors for more detail.
664
+ output_hidden_states (`bool`, *optional*):
665
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
666
+ more detail.
667
+ return_dict (`bool`, *optional*):
668
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
669
+ """
670
+
671
+
672
+ @add_start_docstrings(
673
+ "The bare Dinat Model transformer outputting raw hidden-states without any specific head on top.",
674
+ DINAT_START_DOCSTRING,
675
+ )
676
+ class DinatModel(DinatPreTrainedModel):
677
+ def __init__(self, config, add_pooling_layer=True):
678
+ super().__init__(config)
679
+
680
+ requires_backends(self, ["natten"])
681
+
682
+ self.config = config
683
+ self.num_levels = len(config.depths)
684
+ self.num_features = int(config.embed_dim * 2 ** (self.num_levels - 1))
685
+
686
+ self.embeddings = DinatEmbeddings(config)
687
+ self.encoder = DinatEncoder(config)
688
+
689
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
690
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
691
+
692
+ # Initialize weights and apply final processing
693
+ self.post_init()
694
+
695
+ def get_input_embeddings(self):
696
+ return self.embeddings.patch_embeddings
697
+
698
+ def _prune_heads(self, heads_to_prune):
699
+ """
700
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
701
+ class PreTrainedModel
702
+ """
703
+ for layer, heads in heads_to_prune.items():
704
+ self.encoder.layer[layer].attention.prune_heads(heads)
705
+
706
+ @add_start_docstrings_to_model_forward(DINAT_INPUTS_DOCSTRING)
707
+ @add_code_sample_docstrings(
708
+ checkpoint=_CHECKPOINT_FOR_DOC,
709
+ output_type=DinatModelOutput,
710
+ config_class=_CONFIG_FOR_DOC,
711
+ modality="vision",
712
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
713
+ )
714
+ def forward(
715
+ self,
716
+ pixel_values: Optional[torch.FloatTensor] = None,
717
+ output_attentions: Optional[bool] = None,
718
+ output_hidden_states: Optional[bool] = None,
719
+ return_dict: Optional[bool] = None,
720
+ ) -> Union[Tuple, DinatModelOutput]:
721
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
722
+ output_hidden_states = (
723
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
724
+ )
725
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
726
+
727
+ if pixel_values is None:
728
+ raise ValueError("You have to specify pixel_values")
729
+
730
+ embedding_output = self.embeddings(pixel_values)
731
+
732
+ encoder_outputs = self.encoder(
733
+ embedding_output,
734
+ output_attentions=output_attentions,
735
+ output_hidden_states=output_hidden_states,
736
+ return_dict=return_dict,
737
+ )
738
+
739
+ sequence_output = encoder_outputs[0]
740
+ sequence_output = self.layernorm(sequence_output)
741
+
742
+ pooled_output = None
743
+ if self.pooler is not None:
744
+ pooled_output = self.pooler(sequence_output.flatten(1, 2).transpose(1, 2))
745
+ pooled_output = torch.flatten(pooled_output, 1)
746
+
747
+ if not return_dict:
748
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
749
+
750
+ return output
751
+
752
+ return DinatModelOutput(
753
+ last_hidden_state=sequence_output,
754
+ pooler_output=pooled_output,
755
+ hidden_states=encoder_outputs.hidden_states,
756
+ attentions=encoder_outputs.attentions,
757
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
758
+ )
759
+
760
+
761
+ @add_start_docstrings(
762
+ """
763
+ Dinat Model transformer with an image classification head on top (a linear layer on top of the final hidden state
764
+ of the [CLS] token) e.g. for ImageNet.
765
+ """,
766
+ DINAT_START_DOCSTRING,
767
+ )
768
+ class DinatForImageClassification(DinatPreTrainedModel):
769
+ def __init__(self, config):
770
+ super().__init__(config)
771
+
772
+ requires_backends(self, ["natten"])
773
+
774
+ self.num_labels = config.num_labels
775
+ self.dinat = DinatModel(config)
776
+
777
+ # Classifier head
778
+ self.classifier = (
779
+ nn.Linear(self.dinat.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
780
+ )
781
+
782
+ # Initialize weights and apply final processing
783
+ self.post_init()
784
+
785
+ @add_start_docstrings_to_model_forward(DINAT_INPUTS_DOCSTRING)
786
+ @add_code_sample_docstrings(
787
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
788
+ output_type=DinatImageClassifierOutput,
789
+ config_class=_CONFIG_FOR_DOC,
790
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
791
+ )
792
+ def forward(
793
+ self,
794
+ pixel_values: Optional[torch.FloatTensor] = None,
795
+ labels: Optional[torch.LongTensor] = None,
796
+ output_attentions: Optional[bool] = None,
797
+ output_hidden_states: Optional[bool] = None,
798
+ return_dict: Optional[bool] = None,
799
+ ) -> Union[Tuple, DinatImageClassifierOutput]:
800
+ r"""
801
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
802
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
803
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
804
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
805
+ """
806
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
807
+
808
+ outputs = self.dinat(
809
+ pixel_values,
810
+ output_attentions=output_attentions,
811
+ output_hidden_states=output_hidden_states,
812
+ return_dict=return_dict,
813
+ )
814
+
815
+ pooled_output = outputs[1]
816
+
817
+ logits = self.classifier(pooled_output)
818
+
819
+ loss = None
820
+ if labels is not None:
821
+ if self.config.problem_type is None:
822
+ if self.num_labels == 1:
823
+ self.config.problem_type = "regression"
824
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
825
+ self.config.problem_type = "single_label_classification"
826
+ else:
827
+ self.config.problem_type = "multi_label_classification"
828
+
829
+ if self.config.problem_type == "regression":
830
+ loss_fct = MSELoss()
831
+ if self.num_labels == 1:
832
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
833
+ else:
834
+ loss = loss_fct(logits, labels)
835
+ elif self.config.problem_type == "single_label_classification":
836
+ loss_fct = CrossEntropyLoss()
837
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
838
+ elif self.config.problem_type == "multi_label_classification":
839
+ loss_fct = BCEWithLogitsLoss()
840
+ loss = loss_fct(logits, labels)
841
+
842
+ if not return_dict:
843
+ output = (logits,) + outputs[2:]
844
+ return ((loss,) + output) if loss is not None else output
845
+
846
+ return DinatImageClassifierOutput(
847
+ loss=loss,
848
+ logits=logits,
849
+ hidden_states=outputs.hidden_states,
850
+ attentions=outputs.attentions,
851
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
852
+ )
853
+
854
+
855
+ @add_start_docstrings(
856
+ "NAT backbone, to be used with frameworks like DETR and MaskFormer.",
857
+ DINAT_START_DOCSTRING,
858
+ )
859
+ class DinatBackbone(DinatPreTrainedModel, BackboneMixin):
860
+ def __init__(self, config):
861
+ super().__init__(config)
862
+ super()._init_backbone(config)
863
+
864
+ requires_backends(self, ["natten"])
865
+
866
+ self.embeddings = DinatEmbeddings(config)
867
+ self.encoder = DinatEncoder(config)
868
+ self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))]
869
+
870
+ # Add layer norms to hidden states of out_features
871
+ hidden_states_norms = {}
872
+ for stage, num_channels in zip(self._out_features, self.channels):
873
+ hidden_states_norms[stage] = nn.LayerNorm(num_channels)
874
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
875
+
876
+ # Initialize weights and apply final processing
877
+ self.post_init()
878
+
879
+ def get_input_embeddings(self):
880
+ return self.embeddings.patch_embeddings
881
+
882
+ @add_start_docstrings_to_model_forward(DINAT_INPUTS_DOCSTRING)
883
+ @replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
884
+ def forward(
885
+ self,
886
+ pixel_values: torch.Tensor,
887
+ output_hidden_states: Optional[bool] = None,
888
+ output_attentions: Optional[bool] = None,
889
+ return_dict: Optional[bool] = None,
890
+ ) -> BackboneOutput:
891
+ """
892
+ Returns:
893
+
894
+ Examples:
895
+
896
+ ```python
897
+ >>> from transformers import AutoImageProcessor, AutoBackbone
898
+ >>> import torch
899
+ >>> from PIL import Image
900
+ >>> import requests
901
+
902
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
903
+ >>> image = Image.open(requests.get(url, stream=True).raw)
904
+
905
+ >>> processor = AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224")
906
+ >>> model = AutoBackbone.from_pretrained(
907
+ ... "shi-labs/nat-mini-in1k-224", out_features=["stage1", "stage2", "stage3", "stage4"]
908
+ ... )
909
+
910
+ >>> inputs = processor(image, return_tensors="pt")
911
+
912
+ >>> outputs = model(**inputs)
913
+
914
+ >>> feature_maps = outputs.feature_maps
915
+ >>> list(feature_maps[-1].shape)
916
+ [1, 512, 7, 7]
917
+ ```"""
918
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
919
+ output_hidden_states = (
920
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
921
+ )
922
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
923
+
924
+ embedding_output = self.embeddings(pixel_values)
925
+
926
+ outputs = self.encoder(
927
+ embedding_output,
928
+ output_attentions=output_attentions,
929
+ output_hidden_states=True,
930
+ output_hidden_states_before_downsampling=True,
931
+ return_dict=True,
932
+ )
933
+
934
+ hidden_states = outputs.reshaped_hidden_states
935
+
936
+ feature_maps = ()
937
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
938
+ if stage in self.out_features:
939
+ batch_size, num_channels, height, width = hidden_state.shape
940
+ hidden_state = hidden_state.permute(0, 2, 3, 1).contiguous()
941
+ hidden_state = hidden_state.view(batch_size, height * width, num_channels)
942
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
943
+ hidden_state = hidden_state.view(batch_size, height, width, num_channels)
944
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
945
+ feature_maps += (hidden_state,)
946
+
947
+ if not return_dict:
948
+ output = (feature_maps,)
949
+ if output_hidden_states:
950
+ output += (outputs.hidden_states,)
951
+ return output
952
+
953
+ return BackboneOutput(
954
+ feature_maps=feature_maps,
955
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
956
+ attentions=outputs.attentions,
957
+ )
958
+
959
+
960
+ __all__ = ["DinatForImageClassification", "DinatModel", "DinatPreTrainedModel", "DinatBackbone"]
janus/lib/python3.10/site-packages/transformers/models/donut/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_donut_swin import *
22
+ from .feature_extraction_donut import *
23
+ from .image_processing_donut import *
24
+ from .modeling_donut_swin import *
25
+ from .processing_donut import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/donut/__pycache__/image_processing_donut.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/donut/configuration_donut_swin.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Donut Swin Transformer model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class DonutSwinConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`DonutSwinModel`]. It is used to instantiate a
27
+ Donut model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the Donut
29
+ [naver-clova-ix/donut-base](https://huggingface.co/naver-clova-ix/donut-base) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ image_size (`int`, *optional*, defaults to 224):
36
+ The size (resolution) of each image.
37
+ patch_size (`int`, *optional*, defaults to 4):
38
+ The size (resolution) of each patch.
39
+ num_channels (`int`, *optional*, defaults to 3):
40
+ The number of input channels.
41
+ embed_dim (`int`, *optional*, defaults to 96):
42
+ Dimensionality of patch embedding.
43
+ depths (`list(int)`, *optional*, defaults to `[2, 2, 6, 2]`):
44
+ Depth of each layer in the Transformer encoder.
45
+ num_heads (`list(int)`, *optional*, defaults to `[3, 6, 12, 24]`):
46
+ Number of attention heads in each layer of the Transformer encoder.
47
+ window_size (`int`, *optional*, defaults to 7):
48
+ Size of windows.
49
+ mlp_ratio (`float`, *optional*, defaults to 4.0):
50
+ Ratio of MLP hidden dimensionality to embedding dimensionality.
51
+ qkv_bias (`bool`, *optional*, defaults to `True`):
52
+ Whether or not a learnable bias should be added to the queries, keys and values.
53
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
54
+ The dropout probability for all fully connected layers in the embeddings and encoder.
55
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
56
+ The dropout ratio for the attention probabilities.
57
+ drop_path_rate (`float`, *optional*, defaults to 0.1):
58
+ Stochastic depth rate.
59
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
60
+ The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
61
+ `"selu"` and `"gelu_new"` are supported.
62
+ use_absolute_embeddings (`bool`, *optional*, defaults to `False`):
63
+ Whether or not to add absolute position embeddings to the patch embeddings.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
67
+ The epsilon used by the layer normalization layers.
68
+
69
+ Example:
70
+
71
+ ```python
72
+ >>> from transformers import DonutSwinConfig, DonutSwinModel
73
+
74
+ >>> # Initializing a Donut naver-clova-ix/donut-base style configuration
75
+ >>> configuration = DonutSwinConfig()
76
+
77
+ >>> # Randomly initializing a model from the naver-clova-ix/donut-base style configuration
78
+ >>> model = DonutSwinModel(configuration)
79
+
80
+ >>> # Accessing the model configuration
81
+ >>> configuration = model.config
82
+ ```"""
83
+
84
+ model_type = "donut-swin"
85
+
86
+ attribute_map = {
87
+ "num_attention_heads": "num_heads",
88
+ "num_hidden_layers": "num_layers",
89
+ }
90
+
91
+ def __init__(
92
+ self,
93
+ image_size=224,
94
+ patch_size=4,
95
+ num_channels=3,
96
+ embed_dim=96,
97
+ depths=[2, 2, 6, 2],
98
+ num_heads=[3, 6, 12, 24],
99
+ window_size=7,
100
+ mlp_ratio=4.0,
101
+ qkv_bias=True,
102
+ hidden_dropout_prob=0.0,
103
+ attention_probs_dropout_prob=0.0,
104
+ drop_path_rate=0.1,
105
+ hidden_act="gelu",
106
+ use_absolute_embeddings=False,
107
+ initializer_range=0.02,
108
+ layer_norm_eps=1e-5,
109
+ **kwargs,
110
+ ):
111
+ super().__init__(**kwargs)
112
+
113
+ self.image_size = image_size
114
+ self.patch_size = patch_size
115
+ self.num_channels = num_channels
116
+ self.embed_dim = embed_dim
117
+ self.depths = depths
118
+ self.num_layers = len(depths)
119
+ self.num_heads = num_heads
120
+ self.window_size = window_size
121
+ self.mlp_ratio = mlp_ratio
122
+ self.qkv_bias = qkv_bias
123
+ self.hidden_dropout_prob = hidden_dropout_prob
124
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
125
+ self.drop_path_rate = drop_path_rate
126
+ self.hidden_act = hidden_act
127
+ self.use_absolute_embeddings = use_absolute_embeddings
128
+ self.layer_norm_eps = layer_norm_eps
129
+ self.initializer_range = initializer_range
130
+ # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
131
+ # this indicates the channel dimension after the last stage of the model
132
+ self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))
133
+
134
+
135
+ __all__ = ["DonutSwinConfig"]
janus/lib/python3.10/site-packages/transformers/models/donut/image_processing_donut.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Image processor class for Donut."""
16
+
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import (
23
+ get_resize_output_image_size,
24
+ pad,
25
+ resize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from ...image_utils import (
29
+ IMAGENET_STANDARD_MEAN,
30
+ IMAGENET_STANDARD_STD,
31
+ ChannelDimension,
32
+ ImageInput,
33
+ PILImageResampling,
34
+ get_image_size,
35
+ infer_channel_dimension_format,
36
+ is_scaled_image,
37
+ make_list_of_images,
38
+ to_numpy_array,
39
+ valid_images,
40
+ validate_preprocess_arguments,
41
+ )
42
+ from ...utils import TensorType, filter_out_non_signature_kwargs, logging
43
+ from ...utils.import_utils import is_vision_available
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ if is_vision_available():
50
+ import PIL
51
+
52
+
53
+ class DonutImageProcessor(BaseImageProcessor):
54
+ r"""
55
+ Constructs a Donut image processor.
56
+
57
+ Args:
58
+ do_resize (`bool`, *optional*, defaults to `True`):
59
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
60
+ `do_resize` in the `preprocess` method.
61
+ size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
62
+ Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
63
+ the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
64
+ method.
65
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
66
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
67
+ do_thumbnail (`bool`, *optional*, defaults to `True`):
68
+ Whether to resize the image using thumbnail method.
69
+ do_align_long_axis (`bool`, *optional*, defaults to `False`):
70
+ Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
71
+ do_pad (`bool`, *optional*, defaults to `True`):
72
+ Whether to pad the image. If `random_padding` is set to `True` in `preprocess`, each image is padded with a
73
+ random amont of padding on each size, up to the largest image size in the batch. Otherwise, all images are
74
+ padded to the largest image size in the batch.
75
+ do_rescale (`bool`, *optional*, defaults to `True`):
76
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
77
+ the `preprocess` method.
78
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
79
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
80
+ method.
81
+ do_normalize (`bool`, *optional*, defaults to `True`):
82
+ Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
83
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
84
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
85
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
86
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
87
+ Image standard deviation.
88
+ """
89
+
90
+ model_input_names = ["pixel_values"]
91
+
92
+ def __init__(
93
+ self,
94
+ do_resize: bool = True,
95
+ size: Dict[str, int] = None,
96
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
97
+ do_thumbnail: bool = True,
98
+ do_align_long_axis: bool = False,
99
+ do_pad: bool = True,
100
+ do_rescale: bool = True,
101
+ rescale_factor: Union[int, float] = 1 / 255,
102
+ do_normalize: bool = True,
103
+ image_mean: Optional[Union[float, List[float]]] = None,
104
+ image_std: Optional[Union[float, List[float]]] = None,
105
+ **kwargs,
106
+ ) -> None:
107
+ super().__init__(**kwargs)
108
+
109
+ size = size if size is not None else {"height": 2560, "width": 1920}
110
+ if isinstance(size, (tuple, list)):
111
+ # The previous feature extractor size parameter was in (width, height) format
112
+ size = size[::-1]
113
+ size = get_size_dict(size)
114
+
115
+ self.do_resize = do_resize
116
+ self.size = size
117
+ self.resample = resample
118
+ self.do_thumbnail = do_thumbnail
119
+ self.do_align_long_axis = do_align_long_axis
120
+ self.do_pad = do_pad
121
+ self.do_rescale = do_rescale
122
+ self.rescale_factor = rescale_factor
123
+ self.do_normalize = do_normalize
124
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
125
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
126
+
127
+ def align_long_axis(
128
+ self,
129
+ image: np.ndarray,
130
+ size: Dict[str, int],
131
+ data_format: Optional[Union[str, ChannelDimension]] = None,
132
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
133
+ ) -> np.ndarray:
134
+ """
135
+ Align the long axis of the image to the longest axis of the specified size.
136
+
137
+ Args:
138
+ image (`np.ndarray`):
139
+ The image to be aligned.
140
+ size (`Dict[str, int]`):
141
+ The size `{"height": h, "width": w}` to align the long axis to.
142
+ data_format (`str` or `ChannelDimension`, *optional*):
143
+ The data format of the output image. If unset, the same format as the input image is used.
144
+ input_data_format (`ChannelDimension` or `str`, *optional*):
145
+ The channel dimension format of the input image. If not provided, it will be inferred.
146
+
147
+ Returns:
148
+ `np.ndarray`: The aligned image.
149
+ """
150
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
151
+ output_height, output_width = size["height"], size["width"]
152
+
153
+ if (output_width < output_height and input_width > input_height) or (
154
+ output_width > output_height and input_width < input_height
155
+ ):
156
+ image = np.rot90(image, 3)
157
+
158
+ if data_format is not None:
159
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
160
+
161
+ return image
162
+
163
+ def pad_image(
164
+ self,
165
+ image: np.ndarray,
166
+ size: Dict[str, int],
167
+ random_padding: bool = False,
168
+ data_format: Optional[Union[str, ChannelDimension]] = None,
169
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
170
+ ) -> np.ndarray:
171
+ """
172
+ Pad the image to the specified size.
173
+
174
+ Args:
175
+ image (`np.ndarray`):
176
+ The image to be padded.
177
+ size (`Dict[str, int]`):
178
+ The size `{"height": h, "width": w}` to pad the image to.
179
+ random_padding (`bool`, *optional*, defaults to `False`):
180
+ Whether to use random padding or not.
181
+ data_format (`str` or `ChannelDimension`, *optional*):
182
+ The data format of the output image. If unset, the same format as the input image is used.
183
+ input_data_format (`ChannelDimension` or `str`, *optional*):
184
+ The channel dimension format of the input image. If not provided, it will be inferred.
185
+ """
186
+ output_height, output_width = size["height"], size["width"]
187
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
188
+
189
+ delta_width = output_width - input_width
190
+ delta_height = output_height - input_height
191
+
192
+ if random_padding:
193
+ pad_top = np.random.randint(low=0, high=delta_height + 1)
194
+ pad_left = np.random.randint(low=0, high=delta_width + 1)
195
+ else:
196
+ pad_top = delta_height // 2
197
+ pad_left = delta_width // 2
198
+
199
+ pad_bottom = delta_height - pad_top
200
+ pad_right = delta_width - pad_left
201
+
202
+ padding = ((pad_top, pad_bottom), (pad_left, pad_right))
203
+ return pad(image, padding, data_format=data_format, input_data_format=input_data_format)
204
+
205
+ def pad(self, *args, **kwargs):
206
+ logger.info("pad is deprecated and will be removed in version 4.27. Please use pad_image instead.")
207
+ return self.pad_image(*args, **kwargs)
208
+
209
+ def thumbnail(
210
+ self,
211
+ image: np.ndarray,
212
+ size: Dict[str, int],
213
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
214
+ data_format: Optional[Union[str, ChannelDimension]] = None,
215
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
216
+ **kwargs,
217
+ ) -> np.ndarray:
218
+ """
219
+ Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any
220
+ corresponding dimension of the specified size.
221
+
222
+ Args:
223
+ image (`np.ndarray`):
224
+ The image to be resized.
225
+ size (`Dict[str, int]`):
226
+ The size `{"height": h, "width": w}` to resize the image to.
227
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
228
+ The resampling filter to use.
229
+ data_format (`Optional[Union[str, ChannelDimension]]`, *optional*):
230
+ The data format of the output image. If unset, the same format as the input image is used.
231
+ input_data_format (`ChannelDimension` or `str`, *optional*):
232
+ The channel dimension format of the input image. If not provided, it will be inferred.
233
+ """
234
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
235
+ output_height, output_width = size["height"], size["width"]
236
+
237
+ # We always resize to the smallest of either the input or output size.
238
+ height = min(input_height, output_height)
239
+ width = min(input_width, output_width)
240
+
241
+ if height == input_height and width == input_width:
242
+ return image
243
+
244
+ if input_height > input_width:
245
+ width = int(input_width * height / input_height)
246
+ elif input_width > input_height:
247
+ height = int(input_height * width / input_width)
248
+
249
+ return resize(
250
+ image,
251
+ size=(height, width),
252
+ resample=resample,
253
+ reducing_gap=2.0,
254
+ data_format=data_format,
255
+ input_data_format=input_data_format,
256
+ **kwargs,
257
+ )
258
+
259
+ def resize(
260
+ self,
261
+ image: np.ndarray,
262
+ size: Dict[str, int],
263
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
264
+ data_format: Optional[Union[str, ChannelDimension]] = None,
265
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
266
+ **kwargs,
267
+ ) -> np.ndarray:
268
+ """
269
+ Resizes `image` to `(height, width)` specified by `size` using the PIL library.
270
+
271
+ Args:
272
+ image (`np.ndarray`):
273
+ Image to resize.
274
+ size (`Dict[str, int]`):
275
+ Size of the output image.
276
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
277
+ Resampling filter to use when resiizing the image.
278
+ data_format (`str` or `ChannelDimension`, *optional*):
279
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
280
+ input_data_format (`ChannelDimension` or `str`, *optional*):
281
+ The channel dimension format of the input image. If not provided, it will be inferred.
282
+ """
283
+ size = get_size_dict(size)
284
+ shortest_edge = min(size["height"], size["width"])
285
+ output_size = get_resize_output_image_size(
286
+ image, size=shortest_edge, default_to_square=False, input_data_format=input_data_format
287
+ )
288
+ resized_image = resize(
289
+ image,
290
+ size=output_size,
291
+ resample=resample,
292
+ data_format=data_format,
293
+ input_data_format=input_data_format,
294
+ **kwargs,
295
+ )
296
+ return resized_image
297
+
298
+ @filter_out_non_signature_kwargs()
299
+ def preprocess(
300
+ self,
301
+ images: ImageInput,
302
+ do_resize: bool = None,
303
+ size: Dict[str, int] = None,
304
+ resample: PILImageResampling = None,
305
+ do_thumbnail: bool = None,
306
+ do_align_long_axis: bool = None,
307
+ do_pad: bool = None,
308
+ random_padding: bool = False,
309
+ do_rescale: bool = None,
310
+ rescale_factor: float = None,
311
+ do_normalize: bool = None,
312
+ image_mean: Optional[Union[float, List[float]]] = None,
313
+ image_std: Optional[Union[float, List[float]]] = None,
314
+ return_tensors: Optional[Union[str, TensorType]] = None,
315
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
316
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
317
+ ) -> PIL.Image.Image:
318
+ """
319
+ Preprocess an image or batch of images.
320
+
321
+ Args:
322
+ images (`ImageInput`):
323
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
324
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
325
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
326
+ Whether to resize the image.
327
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
328
+ Size of the image after resizing. Shortest edge of the image is resized to min(size["height"],
329
+ size["width"]) with the longest edge resized to keep the input aspect ratio.
330
+ resample (`int`, *optional*, defaults to `self.resample`):
331
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
332
+ has an effect if `do_resize` is set to `True`.
333
+ do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`):
334
+ Whether to resize the image using thumbnail method.
335
+ do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`):
336
+ Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees.
337
+ do_pad (`bool`, *optional*, defaults to `self.do_pad`):
338
+ Whether to pad the image. If `random_padding` is set to `True`, each image is padded with a random
339
+ amont of padding on each size, up to the largest image size in the batch. Otherwise, all images are
340
+ padded to the largest image size in the batch.
341
+ random_padding (`bool`, *optional*, defaults to `self.random_padding`):
342
+ Whether to use random padding when padding the image. If `True`, each image in the batch with be padded
343
+ with a random amount of padding on each side up to the size of the largest image in the batch.
344
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
345
+ Whether to rescale the image pixel values.
346
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
347
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
348
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
349
+ Whether to normalize the image.
350
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
351
+ Image mean to use for normalization.
352
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
353
+ Image standard deviation to use for normalization.
354
+ return_tensors (`str` or `TensorType`, *optional*):
355
+ The type of tensors to return. Can be one of:
356
+ - Unset: Return a list of `np.ndarray`.
357
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
358
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
359
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
360
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
361
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
362
+ The channel dimension format for the output image. Can be one of:
363
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
364
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
365
+ - Unset: defaults to the channel dimension format of the input image.
366
+ input_data_format (`ChannelDimension` or `str`, *optional*):
367
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
368
+ from the input image. Can be one of:
369
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
370
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
371
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
372
+ """
373
+ do_resize = do_resize if do_resize is not None else self.do_resize
374
+ size = size if size is not None else self.size
375
+ if isinstance(size, (tuple, list)):
376
+ # Previous feature extractor had size in (width, height) format
377
+ size = size[::-1]
378
+ size = get_size_dict(size)
379
+ resample = resample if resample is not None else self.resample
380
+ do_thumbnail = do_thumbnail if do_thumbnail is not None else self.do_thumbnail
381
+ do_align_long_axis = do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
382
+ do_pad = do_pad if do_pad is not None else self.do_pad
383
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
384
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
385
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
386
+ image_mean = image_mean if image_mean is not None else self.image_mean
387
+ image_std = image_std if image_std is not None else self.image_std
388
+
389
+ images = make_list_of_images(images)
390
+
391
+ if not valid_images(images):
392
+ raise ValueError(
393
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
394
+ "torch.Tensor, tf.Tensor or jax.ndarray."
395
+ )
396
+ validate_preprocess_arguments(
397
+ do_rescale=do_rescale,
398
+ rescale_factor=rescale_factor,
399
+ do_normalize=do_normalize,
400
+ image_mean=image_mean,
401
+ image_std=image_std,
402
+ do_pad=do_pad,
403
+ size_divisibility=size, # There is no pad divisibility in this processor, but pad requires the size arg.
404
+ do_resize=do_resize,
405
+ size=size,
406
+ resample=resample,
407
+ )
408
+
409
+ # All transformations expect numpy arrays.
410
+ images = [to_numpy_array(image) for image in images]
411
+
412
+ if do_rescale and is_scaled_image(images[0]):
413
+ logger.warning_once(
414
+ "It looks like you are trying to rescale already rescaled images. If the input"
415
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
416
+ )
417
+
418
+ if input_data_format is None:
419
+ # We assume that all images have the same channel dimension format.
420
+ input_data_format = infer_channel_dimension_format(images[0])
421
+
422
+ if do_align_long_axis:
423
+ images = [self.align_long_axis(image, size=size, input_data_format=input_data_format) for image in images]
424
+
425
+ if do_resize:
426
+ images = [
427
+ self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
428
+ for image in images
429
+ ]
430
+
431
+ if do_thumbnail:
432
+ images = [self.thumbnail(image=image, size=size, input_data_format=input_data_format) for image in images]
433
+
434
+ if do_pad:
435
+ images = [
436
+ self.pad_image(
437
+ image=image, size=size, random_padding=random_padding, input_data_format=input_data_format
438
+ )
439
+ for image in images
440
+ ]
441
+
442
+ if do_rescale:
443
+ images = [
444
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
445
+ for image in images
446
+ ]
447
+
448
+ if do_normalize:
449
+ images = [
450
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
451
+ for image in images
452
+ ]
453
+
454
+ images = [
455
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
456
+ ]
457
+
458
+ data = {"pixel_values": images}
459
+ return BatchFeature(data=data, tensor_type=return_tensors)
460
+
461
+
462
+ __all__ = ["DonutImageProcessor"]
janus/lib/python3.10/site-packages/transformers/models/donut/modeling_donut_swin.py ADDED
@@ -0,0 +1,1011 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch Donut Swin Transformer model.
16
+
17
+ This implementation is identical to a regular Swin Transformer, without final layer norm on top of the final hidden
18
+ states."""
19
+
20
+ import collections.abc
21
+ import math
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
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
+ torch_int,
39
+ )
40
+ from .configuration_donut_swin import DonutSwinConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ # General docstring
46
+ _CONFIG_FOR_DOC = "DonutSwinConfig"
47
+
48
+ # Base docstring
49
+ _CHECKPOINT_FOR_DOC = "https://huggingface.co/naver-clova-ix/donut-base"
50
+ _EXPECTED_OUTPUT_SHAPE = [1, 49, 768]
51
+
52
+
53
+ @dataclass
54
+ # Copied from transformers.models.swin.modeling_swin.SwinEncoderOutput with Swin->DonutSwin
55
+ class DonutSwinEncoderOutput(ModelOutput):
56
+ """
57
+ DonutSwin encoder'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
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
63
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
64
+ shape `(batch_size, sequence_length, hidden_size)`.
65
+
66
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
67
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
68
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
69
+ sequence_length)`.
70
+
71
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
72
+ heads.
73
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
74
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
75
+ shape `(batch_size, hidden_size, height, width)`.
76
+
77
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
78
+ include the spatial dimensions.
79
+ """
80
+
81
+ last_hidden_state: torch.FloatTensor = None
82
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
83
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
84
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
85
+
86
+
87
+ @dataclass
88
+ # Copied from transformers.models.swin.modeling_swin.SwinModelOutput with Swin->DonutSwin
89
+ class DonutSwinModelOutput(ModelOutput):
90
+ """
91
+ DonutSwin model's outputs that also contains a pooling of the last hidden states.
92
+
93
+ Args:
94
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
95
+ Sequence of hidden-states at the output of the last layer of the model.
96
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
97
+ Average pooling of the last layer hidden-state.
98
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
99
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
100
+ shape `(batch_size, sequence_length, hidden_size)`.
101
+
102
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
103
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
104
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
105
+ sequence_length)`.
106
+
107
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
108
+ heads.
109
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
110
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
111
+ shape `(batch_size, hidden_size, height, width)`.
112
+
113
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
114
+ include the spatial dimensions.
115
+ """
116
+
117
+ last_hidden_state: torch.FloatTensor = None
118
+ pooler_output: Optional[torch.FloatTensor] = None
119
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
120
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
121
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
122
+
123
+
124
+ # Copied from transformers.models.swin.modeling_swin.window_partition
125
+ def window_partition(input_feature, window_size):
126
+ """
127
+ Partitions the given input into windows.
128
+ """
129
+ batch_size, height, width, num_channels = input_feature.shape
130
+ input_feature = input_feature.view(
131
+ batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
132
+ )
133
+ windows = input_feature.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
134
+ return windows
135
+
136
+
137
+ # Copied from transformers.models.swin.modeling_swin.window_reverse
138
+ def window_reverse(windows, window_size, height, width):
139
+ """
140
+ Merges windows to produce higher resolution features.
141
+ """
142
+ num_channels = windows.shape[-1]
143
+ windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
144
+ windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, height, width, num_channels)
145
+ return windows
146
+
147
+
148
+ # Copied from transformers.models.swin.modeling_swin.SwinEmbeddings with Swin->DonutSwin
149
+ class DonutSwinEmbeddings(nn.Module):
150
+ """
151
+ Construct the patch and position embeddings. Optionally, also the mask token.
152
+ """
153
+
154
+ def __init__(self, config, use_mask_token=False):
155
+ super().__init__()
156
+
157
+ self.patch_embeddings = DonutSwinPatchEmbeddings(config)
158
+ num_patches = self.patch_embeddings.num_patches
159
+ self.patch_grid = self.patch_embeddings.grid_size
160
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
161
+
162
+ if config.use_absolute_embeddings:
163
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim))
164
+ else:
165
+ self.position_embeddings = None
166
+
167
+ self.norm = nn.LayerNorm(config.embed_dim)
168
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
169
+ self.patch_size = config.patch_size
170
+ self.config = config
171
+
172
+ # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
173
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
174
+ """
175
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
176
+ images. This method is also adapted to support torch.jit tracing.
177
+
178
+ Adapted from:
179
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
180
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
181
+ """
182
+
183
+ num_patches = embeddings.shape[1] - 1
184
+ num_positions = self.position_embeddings.shape[1] - 1
185
+
186
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
187
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
188
+ return self.position_embeddings
189
+
190
+ class_pos_embed = self.position_embeddings[:, :1]
191
+ patch_pos_embed = self.position_embeddings[:, 1:]
192
+
193
+ dim = embeddings.shape[-1]
194
+
195
+ new_height = height // self.patch_size
196
+ new_width = width // self.patch_size
197
+
198
+ sqrt_num_positions = torch_int(num_positions**0.5)
199
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
200
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
201
+
202
+ patch_pos_embed = nn.functional.interpolate(
203
+ patch_pos_embed,
204
+ size=(new_height, new_width),
205
+ mode="bicubic",
206
+ align_corners=False,
207
+ )
208
+
209
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
210
+
211
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
212
+
213
+ def forward(
214
+ self,
215
+ pixel_values: Optional[torch.FloatTensor],
216
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
217
+ interpolate_pos_encoding: bool = False,
218
+ ) -> Tuple[torch.Tensor]:
219
+ _, num_channels, height, width = pixel_values.shape
220
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
221
+ embeddings = self.norm(embeddings)
222
+ batch_size, seq_len, _ = embeddings.size()
223
+
224
+ if bool_masked_pos is not None:
225
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
226
+ # replace the masked visual tokens by mask_tokens
227
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
228
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
229
+
230
+ if self.position_embeddings is not None:
231
+ if interpolate_pos_encoding:
232
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
233
+ else:
234
+ embeddings = embeddings + self.position_embeddings
235
+
236
+ embeddings = self.dropout(embeddings)
237
+
238
+ return embeddings, output_dimensions
239
+
240
+
241
+ # Copied from transformers.models.swin.modeling_swin.SwinPatchEmbeddings with Swin->DonutSwin
242
+ class DonutSwinPatchEmbeddings(nn.Module):
243
+ """
244
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
245
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
246
+ Transformer.
247
+ """
248
+
249
+ def __init__(self, config):
250
+ super().__init__()
251
+ image_size, patch_size = config.image_size, config.patch_size
252
+ num_channels, hidden_size = config.num_channels, config.embed_dim
253
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
254
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
255
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
256
+ self.image_size = image_size
257
+ self.patch_size = patch_size
258
+ self.num_channels = num_channels
259
+ self.num_patches = num_patches
260
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
261
+
262
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
263
+
264
+ def maybe_pad(self, pixel_values, height, width):
265
+ if width % self.patch_size[1] != 0:
266
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
267
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
268
+ if height % self.patch_size[0] != 0:
269
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
270
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
271
+ return pixel_values
272
+
273
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor, Tuple[int]]:
274
+ _, num_channels, height, width = pixel_values.shape
275
+ # pad the input to be divisible by self.patch_size, if needed
276
+ pixel_values = self.maybe_pad(pixel_values, height, width)
277
+ embeddings = self.projection(pixel_values)
278
+ _, _, height, width = embeddings.shape
279
+ output_dimensions = (height, width)
280
+ embeddings = embeddings.flatten(2).transpose(1, 2)
281
+
282
+ return embeddings, output_dimensions
283
+
284
+
285
+ # Copied from transformers.models.swin.modeling_swin.SwinPatchMerging
286
+ class DonutSwinPatchMerging(nn.Module):
287
+ """
288
+ Patch Merging Layer.
289
+
290
+ Args:
291
+ input_resolution (`Tuple[int]`):
292
+ Resolution of input feature.
293
+ dim (`int`):
294
+ Number of input channels.
295
+ norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
296
+ Normalization layer class.
297
+ """
298
+
299
+ def __init__(self, input_resolution: Tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
300
+ super().__init__()
301
+ self.input_resolution = input_resolution
302
+ self.dim = dim
303
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
304
+ self.norm = norm_layer(4 * dim)
305
+
306
+ def maybe_pad(self, input_feature, height, width):
307
+ should_pad = (height % 2 == 1) or (width % 2 == 1)
308
+ if should_pad:
309
+ pad_values = (0, 0, 0, width % 2, 0, height % 2)
310
+ input_feature = nn.functional.pad(input_feature, pad_values)
311
+
312
+ return input_feature
313
+
314
+ def forward(self, input_feature: torch.Tensor, input_dimensions: Tuple[int, int]) -> torch.Tensor:
315
+ height, width = input_dimensions
316
+ # `dim` is height * width
317
+ batch_size, dim, num_channels = input_feature.shape
318
+
319
+ input_feature = input_feature.view(batch_size, height, width, num_channels)
320
+ # pad input to be disible by width and height, if needed
321
+ input_feature = self.maybe_pad(input_feature, height, width)
322
+ # [batch_size, height/2, width/2, num_channels]
323
+ input_feature_0 = input_feature[:, 0::2, 0::2, :]
324
+ # [batch_size, height/2, width/2, num_channels]
325
+ input_feature_1 = input_feature[:, 1::2, 0::2, :]
326
+ # [batch_size, height/2, width/2, num_channels]
327
+ input_feature_2 = input_feature[:, 0::2, 1::2, :]
328
+ # [batch_size, height/2, width/2, num_channels]
329
+ input_feature_3 = input_feature[:, 1::2, 1::2, :]
330
+ # batch_size height/2 width/2 4*num_channels
331
+ input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1)
332
+ input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # batch_size height/2*width/2 4*C
333
+
334
+ input_feature = self.norm(input_feature)
335
+ input_feature = self.reduction(input_feature)
336
+
337
+ return input_feature
338
+
339
+
340
+ # Copied from transformers.models.beit.modeling_beit.drop_path
341
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
342
+ """
343
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
344
+
345
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
346
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
347
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
348
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
349
+ argument.
350
+ """
351
+ if drop_prob == 0.0 or not training:
352
+ return input
353
+ keep_prob = 1 - drop_prob
354
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
355
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
356
+ random_tensor.floor_() # binarize
357
+ output = input.div(keep_prob) * random_tensor
358
+ return output
359
+
360
+
361
+ # Copied from transformers.models.swin.modeling_swin.SwinDropPath
362
+ class DonutSwinDropPath(nn.Module):
363
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
364
+
365
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
366
+ super().__init__()
367
+ self.drop_prob = drop_prob
368
+
369
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
370
+ return drop_path(hidden_states, self.drop_prob, self.training)
371
+
372
+ def extra_repr(self) -> str:
373
+ return "p={}".format(self.drop_prob)
374
+
375
+
376
+ # Copied from transformers.models.swin.modeling_swin.SwinSelfAttention with Swin->DonutSwin
377
+ class DonutSwinSelfAttention(nn.Module):
378
+ def __init__(self, config, dim, num_heads, window_size):
379
+ super().__init__()
380
+ if dim % num_heads != 0:
381
+ raise ValueError(
382
+ f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
383
+ )
384
+
385
+ self.num_attention_heads = num_heads
386
+ self.attention_head_size = int(dim / num_heads)
387
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
388
+ self.window_size = (
389
+ window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
390
+ )
391
+
392
+ self.relative_position_bias_table = nn.Parameter(
393
+ torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
394
+ )
395
+
396
+ # get pair-wise relative position index for each token inside the window
397
+ coords_h = torch.arange(self.window_size[0])
398
+ coords_w = torch.arange(self.window_size[1])
399
+ coords = torch.stack(meshgrid([coords_h, coords_w], indexing="ij"))
400
+ coords_flatten = torch.flatten(coords, 1)
401
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
402
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous()
403
+ relative_coords[:, :, 0] += self.window_size[0] - 1
404
+ relative_coords[:, :, 1] += self.window_size[1] - 1
405
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
406
+ relative_position_index = relative_coords.sum(-1)
407
+ self.register_buffer("relative_position_index", relative_position_index)
408
+
409
+ self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
410
+ self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
411
+ self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
412
+
413
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
414
+
415
+ def transpose_for_scores(self, x):
416
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
417
+ x = x.view(new_x_shape)
418
+ return x.permute(0, 2, 1, 3)
419
+
420
+ def forward(
421
+ self,
422
+ hidden_states: torch.Tensor,
423
+ attention_mask: Optional[torch.FloatTensor] = None,
424
+ head_mask: Optional[torch.FloatTensor] = None,
425
+ output_attentions: Optional[bool] = False,
426
+ ) -> Tuple[torch.Tensor]:
427
+ batch_size, dim, num_channels = hidden_states.shape
428
+ mixed_query_layer = self.query(hidden_states)
429
+
430
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
431
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
432
+ query_layer = self.transpose_for_scores(mixed_query_layer)
433
+
434
+ # Take the dot product between "query" and "key" to get the raw attention scores.
435
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
436
+
437
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
438
+
439
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)]
440
+ relative_position_bias = relative_position_bias.view(
441
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
442
+ )
443
+
444
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
445
+ attention_scores = attention_scores + relative_position_bias.unsqueeze(0)
446
+
447
+ if attention_mask is not None:
448
+ # Apply the attention mask is (precomputed for all layers in DonutSwinModel forward() function)
449
+ mask_shape = attention_mask.shape[0]
450
+ attention_scores = attention_scores.view(
451
+ batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim
452
+ )
453
+ attention_scores = attention_scores + attention_mask.unsqueeze(1).unsqueeze(0)
454
+ attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
455
+
456
+ # Normalize the attention scores to probabilities.
457
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
458
+
459
+ # This is actually dropping out entire tokens to attend to, which might
460
+ # seem a bit unusual, but is taken from the original Transformer paper.
461
+ attention_probs = self.dropout(attention_probs)
462
+
463
+ # Mask heads if we want to
464
+ if head_mask is not None:
465
+ attention_probs = attention_probs * head_mask
466
+
467
+ context_layer = torch.matmul(attention_probs, value_layer)
468
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
469
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
470
+ context_layer = context_layer.view(new_context_layer_shape)
471
+
472
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
473
+
474
+ return outputs
475
+
476
+
477
+ # Copied from transformers.models.swin.modeling_swin.SwinSelfOutput
478
+ class DonutSwinSelfOutput(nn.Module):
479
+ def __init__(self, config, dim):
480
+ super().__init__()
481
+ self.dense = nn.Linear(dim, dim)
482
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
483
+
484
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
485
+ hidden_states = self.dense(hidden_states)
486
+ hidden_states = self.dropout(hidden_states)
487
+
488
+ return hidden_states
489
+
490
+
491
+ # Copied from transformers.models.swin.modeling_swin.SwinAttention with Swin->DonutSwin
492
+ class DonutSwinAttention(nn.Module):
493
+ def __init__(self, config, dim, num_heads, window_size):
494
+ super().__init__()
495
+ self.self = DonutSwinSelfAttention(config, dim, num_heads, window_size)
496
+ self.output = DonutSwinSelfOutput(config, dim)
497
+ self.pruned_heads = set()
498
+
499
+ def prune_heads(self, heads):
500
+ if len(heads) == 0:
501
+ return
502
+ heads, index = find_pruneable_heads_and_indices(
503
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
504
+ )
505
+
506
+ # Prune linear layers
507
+ self.self.query = prune_linear_layer(self.self.query, index)
508
+ self.self.key = prune_linear_layer(self.self.key, index)
509
+ self.self.value = prune_linear_layer(self.self.value, index)
510
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
511
+
512
+ # Update hyper params and store pruned heads
513
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
514
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
515
+ self.pruned_heads = self.pruned_heads.union(heads)
516
+
517
+ def forward(
518
+ self,
519
+ hidden_states: torch.Tensor,
520
+ attention_mask: Optional[torch.FloatTensor] = None,
521
+ head_mask: Optional[torch.FloatTensor] = None,
522
+ output_attentions: Optional[bool] = False,
523
+ ) -> Tuple[torch.Tensor]:
524
+ self_outputs = self.self(hidden_states, attention_mask, head_mask, output_attentions)
525
+ attention_output = self.output(self_outputs[0], hidden_states)
526
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
527
+ return outputs
528
+
529
+
530
+ # Copied from transformers.models.swin.modeling_swin.SwinIntermediate
531
+ class DonutSwinIntermediate(nn.Module):
532
+ def __init__(self, config, dim):
533
+ super().__init__()
534
+ self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
535
+ if isinstance(config.hidden_act, str):
536
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
537
+ else:
538
+ self.intermediate_act_fn = config.hidden_act
539
+
540
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
541
+ hidden_states = self.dense(hidden_states)
542
+ hidden_states = self.intermediate_act_fn(hidden_states)
543
+ return hidden_states
544
+
545
+
546
+ # Copied from transformers.models.swin.modeling_swin.SwinOutput
547
+ class DonutSwinOutput(nn.Module):
548
+ def __init__(self, config, dim):
549
+ super().__init__()
550
+ self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
551
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
552
+
553
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
554
+ hidden_states = self.dense(hidden_states)
555
+ hidden_states = self.dropout(hidden_states)
556
+ return hidden_states
557
+
558
+
559
+ # Copied from transformers.models.swin.modeling_swin.SwinLayer with Swin->DonutSwin
560
+ class DonutSwinLayer(nn.Module):
561
+ def __init__(self, config, dim, input_resolution, num_heads, drop_path_rate=0.0, shift_size=0):
562
+ super().__init__()
563
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
564
+ self.shift_size = shift_size
565
+ self.window_size = config.window_size
566
+ self.input_resolution = input_resolution
567
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
568
+ self.attention = DonutSwinAttention(config, dim, num_heads, window_size=self.window_size)
569
+ self.drop_path = DonutSwinDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
570
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
571
+ self.intermediate = DonutSwinIntermediate(config, dim)
572
+ self.output = DonutSwinOutput(config, dim)
573
+
574
+ def set_shift_and_window_size(self, input_resolution):
575
+ if min(input_resolution) <= self.window_size:
576
+ # if window size is larger than input resolution, we don't partition windows
577
+ self.shift_size = torch_int(0)
578
+ self.window_size = (
579
+ torch.min(torch.tensor(input_resolution)) if torch.jit.is_tracing() else min(input_resolution)
580
+ )
581
+
582
+ def get_attn_mask(self, height, width, dtype, device):
583
+ if self.shift_size > 0:
584
+ # calculate attention mask for SW-MSA
585
+ img_mask = torch.zeros((1, height, width, 1), dtype=dtype, device=device)
586
+ height_slices = (
587
+ slice(0, -self.window_size),
588
+ slice(-self.window_size, -self.shift_size),
589
+ slice(-self.shift_size, None),
590
+ )
591
+ width_slices = (
592
+ slice(0, -self.window_size),
593
+ slice(-self.window_size, -self.shift_size),
594
+ slice(-self.shift_size, None),
595
+ )
596
+ count = 0
597
+ for height_slice in height_slices:
598
+ for width_slice in width_slices:
599
+ img_mask[:, height_slice, width_slice, :] = count
600
+ count += 1
601
+
602
+ mask_windows = window_partition(img_mask, self.window_size)
603
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
604
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
605
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
606
+ else:
607
+ attn_mask = None
608
+ return attn_mask
609
+
610
+ def maybe_pad(self, hidden_states, height, width):
611
+ pad_right = (self.window_size - width % self.window_size) % self.window_size
612
+ pad_bottom = (self.window_size - height % self.window_size) % self.window_size
613
+ pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
614
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
615
+ return hidden_states, pad_values
616
+
617
+ def forward(
618
+ self,
619
+ hidden_states: torch.Tensor,
620
+ input_dimensions: Tuple[int, int],
621
+ head_mask: Optional[torch.FloatTensor] = None,
622
+ output_attentions: Optional[bool] = False,
623
+ always_partition: Optional[bool] = False,
624
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
625
+ if not always_partition:
626
+ self.set_shift_and_window_size(input_dimensions)
627
+ else:
628
+ pass
629
+ height, width = input_dimensions
630
+ batch_size, _, channels = hidden_states.size()
631
+ shortcut = hidden_states
632
+
633
+ hidden_states = self.layernorm_before(hidden_states)
634
+
635
+ hidden_states = hidden_states.view(batch_size, height, width, channels)
636
+
637
+ # pad hidden_states to multiples of window size
638
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
639
+
640
+ _, height_pad, width_pad, _ = hidden_states.shape
641
+ # cyclic shift
642
+ if self.shift_size > 0:
643
+ shifted_hidden_states = torch.roll(hidden_states, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
644
+ else:
645
+ shifted_hidden_states = hidden_states
646
+
647
+ # partition windows
648
+ hidden_states_windows = window_partition(shifted_hidden_states, self.window_size)
649
+ hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
650
+ attn_mask = self.get_attn_mask(
651
+ height_pad, width_pad, dtype=hidden_states.dtype, device=hidden_states_windows.device
652
+ )
653
+
654
+ attention_outputs = self.attention(
655
+ hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions
656
+ )
657
+
658
+ attention_output = attention_outputs[0]
659
+
660
+ attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
661
+ shifted_windows = window_reverse(attention_windows, self.window_size, height_pad, width_pad)
662
+
663
+ # reverse cyclic shift
664
+ if self.shift_size > 0:
665
+ attention_windows = torch.roll(shifted_windows, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
666
+ else:
667
+ attention_windows = shifted_windows
668
+
669
+ was_padded = pad_values[3] > 0 or pad_values[5] > 0
670
+ if was_padded:
671
+ attention_windows = attention_windows[:, :height, :width, :].contiguous()
672
+
673
+ attention_windows = attention_windows.view(batch_size, height * width, channels)
674
+
675
+ hidden_states = shortcut + self.drop_path(attention_windows)
676
+
677
+ layer_output = self.layernorm_after(hidden_states)
678
+ layer_output = self.intermediate(layer_output)
679
+ layer_output = hidden_states + self.output(layer_output)
680
+
681
+ layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
682
+ return layer_outputs
683
+
684
+
685
+ # Copied from transformers.models.swin.modeling_swin.SwinStage with Swin->DonutSwin
686
+ class DonutSwinStage(nn.Module):
687
+ def __init__(self, config, dim, input_resolution, depth, num_heads, drop_path, downsample):
688
+ super().__init__()
689
+ self.config = config
690
+ self.dim = dim
691
+ self.blocks = nn.ModuleList(
692
+ [
693
+ DonutSwinLayer(
694
+ config=config,
695
+ dim=dim,
696
+ input_resolution=input_resolution,
697
+ num_heads=num_heads,
698
+ drop_path_rate=drop_path[i],
699
+ shift_size=0 if (i % 2 == 0) else config.window_size // 2,
700
+ )
701
+ for i in range(depth)
702
+ ]
703
+ )
704
+
705
+ # patch merging layer
706
+ if downsample is not None:
707
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=nn.LayerNorm)
708
+ else:
709
+ self.downsample = None
710
+
711
+ self.pointing = False
712
+
713
+ def forward(
714
+ self,
715
+ hidden_states: torch.Tensor,
716
+ input_dimensions: Tuple[int, int],
717
+ head_mask: Optional[torch.FloatTensor] = None,
718
+ output_attentions: Optional[bool] = False,
719
+ always_partition: Optional[bool] = False,
720
+ ) -> Tuple[torch.Tensor]:
721
+ height, width = input_dimensions
722
+ for i, layer_module in enumerate(self.blocks):
723
+ layer_head_mask = head_mask[i] if head_mask is not None else None
724
+
725
+ layer_outputs = layer_module(
726
+ hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
727
+ )
728
+
729
+ hidden_states = layer_outputs[0]
730
+
731
+ hidden_states_before_downsampling = hidden_states
732
+ if self.downsample is not None:
733
+ height_downsampled, width_downsampled = (height + 1) // 2, (width + 1) // 2
734
+ output_dimensions = (height, width, height_downsampled, width_downsampled)
735
+ hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
736
+ else:
737
+ output_dimensions = (height, width, height, width)
738
+
739
+ stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
740
+
741
+ if output_attentions:
742
+ stage_outputs += layer_outputs[1:]
743
+ return stage_outputs
744
+
745
+
746
+ # Copied from transformers.models.swin.modeling_swin.SwinEncoder with Swin->DonutSwin
747
+ class DonutSwinEncoder(nn.Module):
748
+ def __init__(self, config, grid_size):
749
+ super().__init__()
750
+ self.num_layers = len(config.depths)
751
+ self.config = config
752
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
753
+ self.layers = nn.ModuleList(
754
+ [
755
+ DonutSwinStage(
756
+ config=config,
757
+ dim=int(config.embed_dim * 2**i_layer),
758
+ input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
759
+ depth=config.depths[i_layer],
760
+ num_heads=config.num_heads[i_layer],
761
+ drop_path=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
762
+ downsample=DonutSwinPatchMerging if (i_layer < self.num_layers - 1) else None,
763
+ )
764
+ for i_layer in range(self.num_layers)
765
+ ]
766
+ )
767
+
768
+ self.gradient_checkpointing = False
769
+
770
+ def forward(
771
+ self,
772
+ hidden_states: torch.Tensor,
773
+ input_dimensions: Tuple[int, int],
774
+ head_mask: Optional[torch.FloatTensor] = None,
775
+ output_attentions: Optional[bool] = False,
776
+ output_hidden_states: Optional[bool] = False,
777
+ output_hidden_states_before_downsampling: Optional[bool] = False,
778
+ always_partition: Optional[bool] = False,
779
+ return_dict: Optional[bool] = True,
780
+ ) -> Union[Tuple, DonutSwinEncoderOutput]:
781
+ all_hidden_states = () if output_hidden_states else None
782
+ all_reshaped_hidden_states = () if output_hidden_states else None
783
+ all_self_attentions = () if output_attentions else None
784
+
785
+ if output_hidden_states:
786
+ batch_size, _, hidden_size = hidden_states.shape
787
+ # rearrange b (h w) c -> b c h w
788
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
789
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
790
+ all_hidden_states += (hidden_states,)
791
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
792
+
793
+ for i, layer_module in enumerate(self.layers):
794
+ layer_head_mask = head_mask[i] if head_mask is not None else None
795
+
796
+ if self.gradient_checkpointing and self.training:
797
+ layer_outputs = self._gradient_checkpointing_func(
798
+ layer_module.__call__,
799
+ hidden_states,
800
+ input_dimensions,
801
+ layer_head_mask,
802
+ output_attentions,
803
+ always_partition,
804
+ )
805
+ else:
806
+ layer_outputs = layer_module(
807
+ hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
808
+ )
809
+
810
+ hidden_states = layer_outputs[0]
811
+ hidden_states_before_downsampling = layer_outputs[1]
812
+ output_dimensions = layer_outputs[2]
813
+
814
+ input_dimensions = (output_dimensions[-2], output_dimensions[-1])
815
+
816
+ if output_hidden_states and output_hidden_states_before_downsampling:
817
+ batch_size, _, hidden_size = hidden_states_before_downsampling.shape
818
+ # rearrange b (h w) c -> b c h w
819
+ # here we use the original (not downsampled) height and width
820
+ reshaped_hidden_state = hidden_states_before_downsampling.view(
821
+ batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
822
+ )
823
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
824
+ all_hidden_states += (hidden_states_before_downsampling,)
825
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
826
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
827
+ batch_size, _, hidden_size = hidden_states.shape
828
+ # rearrange b (h w) c -> b c h w
829
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
830
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
831
+ all_hidden_states += (hidden_states,)
832
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
833
+
834
+ if output_attentions:
835
+ all_self_attentions += layer_outputs[3:]
836
+
837
+ if not return_dict:
838
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
839
+
840
+ return DonutSwinEncoderOutput(
841
+ last_hidden_state=hidden_states,
842
+ hidden_states=all_hidden_states,
843
+ attentions=all_self_attentions,
844
+ reshaped_hidden_states=all_reshaped_hidden_states,
845
+ )
846
+
847
+
848
+ # Copied from transformers.models.swin.modeling_swin.SwinPreTrainedModel with Swin->DonutSwin
849
+ class DonutSwinPreTrainedModel(PreTrainedModel):
850
+ """
851
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
852
+ models.
853
+ """
854
+
855
+ config_class = DonutSwinConfig
856
+ base_model_prefix = "swin"
857
+ main_input_name = "pixel_values"
858
+ supports_gradient_checkpointing = True
859
+ _no_split_modules = ["DonutSwinStage"]
860
+
861
+ def _init_weights(self, module):
862
+ """Initialize the weights"""
863
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
864
+ # Slightly different from the TF version which uses truncated_normal for initialization
865
+ # cf https://github.com/pytorch/pytorch/pull/5617
866
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
867
+ if module.bias is not None:
868
+ module.bias.data.zero_()
869
+ elif isinstance(module, nn.LayerNorm):
870
+ module.bias.data.zero_()
871
+ module.weight.data.fill_(1.0)
872
+
873
+
874
+ SWIN_START_DOCSTRING = r"""
875
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
876
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
877
+ behavior.
878
+
879
+ Parameters:
880
+ config ([`DonutSwinConfig`]): Model configuration class with all the parameters of the model.
881
+ Initializing with a config file does not load the weights associated with the model, only the
882
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
883
+ """
884
+
885
+ SWIN_INPUTS_DOCSTRING = r"""
886
+ Args:
887
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
888
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
889
+ [`DonutImageProcessor.__call__`] for details.
890
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
891
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
892
+
893
+ - 1 indicates the head is **not masked**,
894
+ - 0 indicates the head is **masked**.
895
+
896
+ output_attentions (`bool`, *optional*):
897
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
898
+ tensors for more detail.
899
+ output_hidden_states (`bool`, *optional*):
900
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
901
+ more detail.
902
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
903
+ Whether to interpolate the pre-trained position encodings.
904
+ return_dict (`bool`, *optional*):
905
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
906
+ """
907
+
908
+
909
+ @add_start_docstrings(
910
+ "The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.",
911
+ SWIN_START_DOCSTRING,
912
+ )
913
+ class DonutSwinModel(DonutSwinPreTrainedModel):
914
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
915
+ super().__init__(config)
916
+ self.config = config
917
+ self.num_layers = len(config.depths)
918
+ self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
919
+
920
+ self.embeddings = DonutSwinEmbeddings(config, use_mask_token=use_mask_token)
921
+ self.encoder = DonutSwinEncoder(config, self.embeddings.patch_grid)
922
+
923
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
924
+
925
+ # Initialize weights and apply final processing
926
+ self.post_init()
927
+
928
+ def get_input_embeddings(self):
929
+ return self.embeddings.patch_embeddings
930
+
931
+ def _prune_heads(self, heads_to_prune):
932
+ """
933
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
934
+ class PreTrainedModel
935
+ """
936
+ for layer, heads in heads_to_prune.items():
937
+ self.encoder.layer[layer].attention.prune_heads(heads)
938
+
939
+ @add_start_docstrings_to_model_forward(SWIN_INPUTS_DOCSTRING)
940
+ @add_code_sample_docstrings(
941
+ checkpoint=_CHECKPOINT_FOR_DOC,
942
+ output_type=DonutSwinModelOutput,
943
+ config_class=_CONFIG_FOR_DOC,
944
+ modality="vision",
945
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
946
+ )
947
+ def forward(
948
+ self,
949
+ pixel_values: Optional[torch.FloatTensor] = None,
950
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
951
+ head_mask: Optional[torch.FloatTensor] = None,
952
+ output_attentions: Optional[bool] = None,
953
+ output_hidden_states: Optional[bool] = None,
954
+ interpolate_pos_encoding: bool = False,
955
+ return_dict: Optional[bool] = None,
956
+ ) -> Union[Tuple, DonutSwinModelOutput]:
957
+ r"""
958
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
959
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
960
+ """
961
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
962
+ output_hidden_states = (
963
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
964
+ )
965
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
966
+
967
+ if pixel_values is None:
968
+ raise ValueError("You have to specify pixel_values")
969
+
970
+ # Prepare head mask if needed
971
+ # 1.0 in head_mask indicate we keep the head
972
+ # attention_probs has shape bsz x n_heads x N x N
973
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
974
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
975
+ head_mask = self.get_head_mask(head_mask, len(self.config.depths))
976
+
977
+ embedding_output, input_dimensions = self.embeddings(
978
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
979
+ )
980
+
981
+ encoder_outputs = self.encoder(
982
+ embedding_output,
983
+ input_dimensions,
984
+ head_mask=head_mask,
985
+ output_attentions=output_attentions,
986
+ output_hidden_states=output_hidden_states,
987
+ return_dict=return_dict,
988
+ )
989
+
990
+ sequence_output = encoder_outputs[0]
991
+
992
+ pooled_output = None
993
+ if self.pooler is not None:
994
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
995
+ pooled_output = torch.flatten(pooled_output, 1)
996
+
997
+ if not return_dict:
998
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
999
+
1000
+ return output
1001
+
1002
+ return DonutSwinModelOutput(
1003
+ last_hidden_state=sequence_output,
1004
+ pooler_output=pooled_output,
1005
+ hidden_states=encoder_outputs.hidden_states,
1006
+ attentions=encoder_outputs.attentions,
1007
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
1008
+ )
1009
+
1010
+
1011
+ __all__ = ["DonutSwinModel", "DonutSwinPreTrainedModel"]
janus/lib/python3.10/site-packages/transformers/models/donut/processing_donut.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Processor class for Donut.
17
+ """
18
+
19
+ import re
20
+ import warnings
21
+ from contextlib import contextmanager
22
+ from typing import List, Optional, Union
23
+
24
+ from ...image_utils import ImageInput
25
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
26
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
27
+ from ...utils import logging
28
+
29
+
30
+ class DonutProcessorKwargs(ProcessingKwargs, total=False):
31
+ _defaults = {}
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ class DonutProcessor(ProcessorMixin):
38
+ r"""
39
+ Constructs a Donut processor which wraps a Donut image processor and an XLMRoBERTa tokenizer into a single
40
+ processor.
41
+
42
+ [`DonutProcessor`] offers all the functionalities of [`DonutImageProcessor`] and
43
+ [`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`]. See the [`~DonutProcessor.__call__`] and
44
+ [`~DonutProcessor.decode`] for more information.
45
+
46
+ Args:
47
+ image_processor ([`DonutImageProcessor`], *optional*):
48
+ An instance of [`DonutImageProcessor`]. The image processor is a required input.
49
+ tokenizer ([`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`], *optional*):
50
+ An instance of [`XLMRobertaTokenizer`/`XLMRobertaTokenizerFast`]. The tokenizer is a required input.
51
+ """
52
+
53
+ attributes = ["image_processor", "tokenizer"]
54
+ image_processor_class = "AutoImageProcessor"
55
+ tokenizer_class = "AutoTokenizer"
56
+
57
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
58
+ feature_extractor = None
59
+ if "feature_extractor" in kwargs:
60
+ warnings.warn(
61
+ "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
62
+ " instead.",
63
+ FutureWarning,
64
+ )
65
+ feature_extractor = kwargs.pop("feature_extractor")
66
+
67
+ image_processor = image_processor if image_processor is not None else feature_extractor
68
+ if image_processor is None:
69
+ raise ValueError("You need to specify an `image_processor`.")
70
+ if tokenizer is None:
71
+ raise ValueError("You need to specify a `tokenizer`.")
72
+
73
+ super().__init__(image_processor, tokenizer)
74
+ self.current_processor = self.image_processor
75
+ self._in_target_context_manager = False
76
+
77
+ def __call__(
78
+ self,
79
+ images: ImageInput = None,
80
+ text: Optional[Union[str, List[str], TextInput, PreTokenizedInput]] = None,
81
+ audio=None,
82
+ videos=None,
83
+ **kwargs: Unpack[DonutProcessorKwargs],
84
+ ):
85
+ """
86
+ When used in normal mode, this method forwards all its arguments to AutoImageProcessor's
87
+ [`~AutoImageProcessor.__call__`] and returns its output. If used in the context
88
+ [`~DonutProcessor.as_target_processor`] this method forwards all its arguments to DonutTokenizer's
89
+ [`~DonutTokenizer.__call__`]. Please refer to the doctsring of the above two methods for more information.
90
+ """
91
+ # For backward compatibility
92
+ legacy = kwargs.pop("legacy", True)
93
+ if legacy:
94
+ # With `add_special_tokens=True`, the performance of donut are degraded when working with both images and text.
95
+ logger.warning_once(
96
+ "Legacy behavior is being used. The current behavior will be deprecated in version 5.0.0. "
97
+ "In the new behavior, if both images and text are provided, the default value of `add_special_tokens` "
98
+ "will be changed to `False` when calling the tokenizer if `add_special_tokens` is unset. "
99
+ "To test the new behavior, set `legacy=False`as a processor call argument."
100
+ )
101
+
102
+ if self._in_target_context_manager:
103
+ return self.current_processor(images, text, **kwargs)
104
+
105
+ if images is None and text is None:
106
+ raise ValueError("You need to specify either an `images` or `text` input to process.")
107
+
108
+ output_kwargs = self._merge_kwargs(
109
+ DonutProcessorKwargs,
110
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
111
+ **kwargs,
112
+ )
113
+
114
+ if images is not None:
115
+ inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
116
+ if text is not None:
117
+ if not legacy and images is not None:
118
+ output_kwargs["text_kwargs"].setdefault("add_special_tokens", False)
119
+ encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
120
+
121
+ if text is None:
122
+ return inputs
123
+ elif images is None:
124
+ return encodings
125
+ else:
126
+ inputs["labels"] = encodings["input_ids"] # for BC
127
+ inputs["input_ids"] = encodings["input_ids"]
128
+ return inputs
129
+
130
+ def batch_decode(self, *args, **kwargs):
131
+ """
132
+ This method forwards all its arguments to DonutTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please refer
133
+ to the docstring of this method for more information.
134
+ """
135
+ return self.tokenizer.batch_decode(*args, **kwargs)
136
+
137
+ def decode(self, *args, **kwargs):
138
+ """
139
+ This method forwards all its arguments to DonutTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
140
+ docstring of this method for more information.
141
+ """
142
+ return self.tokenizer.decode(*args, **kwargs)
143
+
144
+ @contextmanager
145
+ def as_target_processor(self):
146
+ """
147
+ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning TrOCR.
148
+ """
149
+ warnings.warn(
150
+ "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
151
+ "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
152
+ "your images inputs, or in a separate call."
153
+ )
154
+ self._in_target_context_manager = True
155
+ self.current_processor = self.tokenizer
156
+ yield
157
+ self.current_processor = self.image_processor
158
+ self._in_target_context_manager = False
159
+
160
+ def token2json(self, tokens, is_inner_value=False, added_vocab=None):
161
+ """
162
+ Convert a (generated) token sequence into an ordered JSON format.
163
+ """
164
+ if added_vocab is None:
165
+ added_vocab = self.tokenizer.get_added_vocab()
166
+
167
+ output = {}
168
+
169
+ while tokens:
170
+ start_token = re.search(r"<s_(.*?)>", tokens, re.IGNORECASE)
171
+ if start_token is None:
172
+ break
173
+ key = start_token.group(1)
174
+ key_escaped = re.escape(key)
175
+
176
+ end_token = re.search(rf"</s_{key_escaped}>", tokens, re.IGNORECASE)
177
+ start_token = start_token.group()
178
+ if end_token is None:
179
+ tokens = tokens.replace(start_token, "")
180
+ else:
181
+ end_token = end_token.group()
182
+ start_token_escaped = re.escape(start_token)
183
+ end_token_escaped = re.escape(end_token)
184
+ content = re.search(
185
+ f"{start_token_escaped}(.*?){end_token_escaped}", tokens, re.IGNORECASE | re.DOTALL
186
+ )
187
+ if content is not None:
188
+ content = content.group(1).strip()
189
+ if r"<s_" in content and r"</s_" in content: # non-leaf node
190
+ value = self.token2json(content, is_inner_value=True, added_vocab=added_vocab)
191
+ if value:
192
+ if len(value) == 1:
193
+ value = value[0]
194
+ output[key] = value
195
+ else: # leaf nodes
196
+ output[key] = []
197
+ for leaf in content.split(r"<sep/>"):
198
+ leaf = leaf.strip()
199
+ if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
200
+ leaf = leaf[1:-2] # for categorical special tokens
201
+ output[key].append(leaf)
202
+ if len(output[key]) == 1:
203
+ output[key] = output[key][0]
204
+
205
+ tokens = tokens[tokens.find(end_token) + len(end_token) :].strip()
206
+ if tokens[:6] == r"<sep/>": # non-leaf nodes
207
+ return [output] + self.token2json(tokens[6:], is_inner_value=True, added_vocab=added_vocab)
208
+
209
+ if len(output):
210
+ return [output] if is_inner_value else output
211
+ else:
212
+ return [] if is_inner_value else {"text_sequence": tokens}
213
+
214
+ @property
215
+ def feature_extractor_class(self):
216
+ warnings.warn(
217
+ "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
218
+ FutureWarning,
219
+ )
220
+ return self.image_processor_class
221
+
222
+ @property
223
+ def feature_extractor(self):
224
+ warnings.warn(
225
+ "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
226
+ FutureWarning,
227
+ )
228
+ return self.image_processor
229
+
230
+
231
+ __all__ = ["DonutProcessor"]
janus/lib/python3.10/site-packages/transformers/models/efficientnet/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_efficientnet import *
22
+ from .image_processing_efficientnet import *
23
+ from .modeling_efficientnet import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (596 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-310.pyc ADDED
Binary file (7.21 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/efficientnet/configuration_efficientnet.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Google Research, Inc. 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
+ """EfficientNet model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import List, Mapping
19
+
20
+ from packaging import version
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...onnx import OnnxConfig
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class EfficientNetConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`EfficientNetModel`]. It is used to instantiate an
33
+ EfficientNet model according to the specified arguments, defining the model architecture. Instantiating a
34
+ configuration with the defaults will yield a similar configuration to that of the EfficientNet
35
+ [google/efficientnet-b7](https://huggingface.co/google/efficientnet-b7) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ num_channels (`int`, *optional*, defaults to 3):
42
+ The number of input channels.
43
+ image_size (`int`, *optional*, defaults to 600):
44
+ The input image size.
45
+ width_coefficient (`float`, *optional*, defaults to 2.0):
46
+ Scaling coefficient for network width at each stage.
47
+ depth_coefficient (`float`, *optional*, defaults to 3.1):
48
+ Scaling coefficient for network depth at each stage.
49
+ depth_divisor `int`, *optional*, defaults to 8):
50
+ A unit of network width.
51
+ kernel_sizes (`List[int]`, *optional*, defaults to `[3, 3, 5, 3, 5, 5, 3]`):
52
+ List of kernel sizes to be used in each block.
53
+ in_channels (`List[int]`, *optional*, defaults to `[32, 16, 24, 40, 80, 112, 192]`):
54
+ List of input channel sizes to be used in each block for convolutional layers.
55
+ out_channels (`List[int]`, *optional*, defaults to `[16, 24, 40, 80, 112, 192, 320]`):
56
+ List of output channel sizes to be used in each block for convolutional layers.
57
+ depthwise_padding (`List[int]`, *optional*, defaults to `[]`):
58
+ List of block indices with square padding.
59
+ strides (`List[int]`, *optional*, defaults to `[1, 2, 2, 2, 1, 2, 1]`):
60
+ List of stride sizes to be used in each block for convolutional layers.
61
+ num_block_repeats (`List[int]`, *optional*, defaults to `[1, 2, 2, 3, 3, 4, 1]`):
62
+ List of the number of times each block is to repeated.
63
+ expand_ratios (`List[int]`, *optional*, defaults to `[1, 6, 6, 6, 6, 6, 6]`):
64
+ List of scaling coefficient of each block.
65
+ squeeze_expansion_ratio (`float`, *optional*, defaults to 0.25):
66
+ Squeeze expansion ratio.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
69
+ `"selu", `"gelu_new"`, `"silu"` and `"mish"` are supported.
70
+ hiddem_dim (`int`, *optional*, defaults to 1280):
71
+ The hidden dimension of the layer before the classification head.
72
+ pooling_type (`str` or `function`, *optional*, defaults to `"mean"`):
73
+ Type of final pooling to be applied before the dense classification head. Available options are [`"mean"`,
74
+ `"max"`]
75
+ initializer_range (`float`, *optional*, defaults to 0.02):
76
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
77
+ batch_norm_eps (`float`, *optional*, defaults to 1e-3):
78
+ The epsilon used by the batch normalization layers.
79
+ batch_norm_momentum (`float`, *optional*, defaults to 0.99):
80
+ The momentum used by the batch normalization layers.
81
+ dropout_rate (`float`, *optional*, defaults to 0.5):
82
+ The dropout rate to be applied before final classifier layer.
83
+ drop_connect_rate (`float`, *optional*, defaults to 0.2):
84
+ The drop rate for skip connections.
85
+
86
+ Example:
87
+ ```python
88
+ >>> from transformers import EfficientNetConfig, EfficientNetModel
89
+
90
+ >>> # Initializing a EfficientNet efficientnet-b7 style configuration
91
+ >>> configuration = EfficientNetConfig()
92
+
93
+ >>> # Initializing a model (with random weights) from the efficientnet-b7 style configuration
94
+ >>> model = EfficientNetModel(configuration)
95
+
96
+ >>> # Accessing the model configuration
97
+ >>> configuration = model.config
98
+ ```"""
99
+
100
+ model_type = "efficientnet"
101
+
102
+ def __init__(
103
+ self,
104
+ num_channels: int = 3,
105
+ image_size: int = 600,
106
+ width_coefficient: float = 2.0,
107
+ depth_coefficient: float = 3.1,
108
+ depth_divisor: int = 8,
109
+ kernel_sizes: List[int] = [3, 3, 5, 3, 5, 5, 3],
110
+ in_channels: List[int] = [32, 16, 24, 40, 80, 112, 192],
111
+ out_channels: List[int] = [16, 24, 40, 80, 112, 192, 320],
112
+ depthwise_padding: List[int] = [],
113
+ strides: List[int] = [1, 2, 2, 2, 1, 2, 1],
114
+ num_block_repeats: List[int] = [1, 2, 2, 3, 3, 4, 1],
115
+ expand_ratios: List[int] = [1, 6, 6, 6, 6, 6, 6],
116
+ squeeze_expansion_ratio: float = 0.25,
117
+ hidden_act: str = "swish",
118
+ hidden_dim: int = 2560,
119
+ pooling_type: str = "mean",
120
+ initializer_range: float = 0.02,
121
+ batch_norm_eps: float = 0.001,
122
+ batch_norm_momentum: float = 0.99,
123
+ dropout_rate: float = 0.5,
124
+ drop_connect_rate: float = 0.2,
125
+ **kwargs,
126
+ ):
127
+ super().__init__(**kwargs)
128
+
129
+ self.num_channels = num_channels
130
+ self.image_size = image_size
131
+ self.width_coefficient = width_coefficient
132
+ self.depth_coefficient = depth_coefficient
133
+ self.depth_divisor = depth_divisor
134
+ self.kernel_sizes = kernel_sizes
135
+ self.in_channels = in_channels
136
+ self.out_channels = out_channels
137
+ self.depthwise_padding = depthwise_padding
138
+ self.strides = strides
139
+ self.num_block_repeats = num_block_repeats
140
+ self.expand_ratios = expand_ratios
141
+ self.squeeze_expansion_ratio = squeeze_expansion_ratio
142
+ self.hidden_act = hidden_act
143
+ self.hidden_dim = hidden_dim
144
+ self.pooling_type = pooling_type
145
+ self.initializer_range = initializer_range
146
+ self.batch_norm_eps = batch_norm_eps
147
+ self.batch_norm_momentum = batch_norm_momentum
148
+ self.dropout_rate = dropout_rate
149
+ self.drop_connect_rate = drop_connect_rate
150
+ self.num_hidden_layers = sum(num_block_repeats) * 4
151
+
152
+
153
+ class EfficientNetOnnxConfig(OnnxConfig):
154
+ torch_onnx_minimum_version = version.parse("1.11")
155
+
156
+ @property
157
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
158
+ return OrderedDict(
159
+ [
160
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
161
+ ]
162
+ )
163
+
164
+ @property
165
+ def atol_for_validation(self) -> float:
166
+ return 1e-5
167
+
168
+
169
+ __all__ = ["EfficientNetConfig", "EfficientNetOnnxConfig"]
janus/lib/python3.10/site-packages/transformers/models/efficientnet/image_processing_efficientnet.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 EfficientNet."""
16
+
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import rescale, resize, to_channel_dimension_format
23
+ from ...image_utils import (
24
+ IMAGENET_STANDARD_MEAN,
25
+ IMAGENET_STANDARD_STD,
26
+ ChannelDimension,
27
+ ImageInput,
28
+ PILImageResampling,
29
+ infer_channel_dimension_format,
30
+ is_scaled_image,
31
+ make_list_of_images,
32
+ to_numpy_array,
33
+ valid_images,
34
+ validate_preprocess_arguments,
35
+ )
36
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
37
+
38
+
39
+ if is_vision_available():
40
+ import PIL
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class EfficientNetImageProcessor(BaseImageProcessor):
47
+ r"""
48
+ Constructs a EfficientNet image processor.
49
+
50
+ Args:
51
+ do_resize (`bool`, *optional*, defaults to `True`):
52
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
53
+ `do_resize` in `preprocess`.
54
+ size (`Dict[str, int]` *optional*, defaults to `{"height": 346, "width": 346}`):
55
+ Size of the image after `resize`. Can be overridden by `size` in `preprocess`.
56
+ resample (`PILImageResampling` filter, *optional*, defaults to 0):
57
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`.
58
+ do_center_crop (`bool`, *optional*, defaults to `False`):
59
+ Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the image
60
+ is padded with 0's and then center cropped. Can be overridden by `do_center_crop` in `preprocess`.
61
+ crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 289, "width": 289}`):
62
+ Desired output size when applying center-cropping. Can be overridden by `crop_size` in `preprocess`.
63
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
64
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
65
+ `preprocess` method.
66
+ rescale_offset (`bool`, *optional*, defaults to `False`):
67
+ Whether to rescale the image between [-scale_range, scale_range] instead of [0, scale_range]. Can be
68
+ overridden by the `rescale_factor` parameter in the `preprocess` method.
69
+ do_rescale (`bool`, *optional*, defaults to `True`):
70
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
71
+ parameter in the `preprocess` method.
72
+ do_normalize (`bool`, *optional*, defaults to `True`):
73
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
74
+ method.
75
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
76
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
77
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
78
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
79
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
80
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
81
+ include_top (`bool`, *optional*, defaults to `True`):
82
+ Whether to rescale the image again. Should be set to True if the inputs are used for image classification.
83
+ """
84
+
85
+ model_input_names = ["pixel_values"]
86
+
87
+ def __init__(
88
+ self,
89
+ do_resize: bool = True,
90
+ size: Dict[str, int] = None,
91
+ resample: PILImageResampling = PIL.Image.NEAREST,
92
+ do_center_crop: bool = False,
93
+ crop_size: Dict[str, int] = None,
94
+ rescale_factor: Union[int, float] = 1 / 255,
95
+ rescale_offset: bool = False,
96
+ do_rescale: bool = True,
97
+ do_normalize: bool = True,
98
+ image_mean: Optional[Union[float, List[float]]] = None,
99
+ image_std: Optional[Union[float, List[float]]] = None,
100
+ include_top: bool = True,
101
+ **kwargs,
102
+ ) -> None:
103
+ super().__init__(**kwargs)
104
+ size = size if size is not None else {"height": 346, "width": 346}
105
+ size = get_size_dict(size)
106
+ crop_size = crop_size if crop_size is not None else {"height": 289, "width": 289}
107
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
108
+
109
+ self.do_resize = do_resize
110
+ self.size = size
111
+ self.resample = resample
112
+ self.do_center_crop = do_center_crop
113
+ self.crop_size = crop_size
114
+ self.do_rescale = do_rescale
115
+ self.rescale_factor = rescale_factor
116
+ self.rescale_offset = rescale_offset
117
+ self.do_normalize = do_normalize
118
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
119
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
120
+ self.include_top = include_top
121
+
122
+ # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.NEAREST
123
+ def resize(
124
+ self,
125
+ image: np.ndarray,
126
+ size: Dict[str, int],
127
+ resample: PILImageResampling = PILImageResampling.NEAREST,
128
+ data_format: Optional[Union[str, ChannelDimension]] = None,
129
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
130
+ **kwargs,
131
+ ) -> np.ndarray:
132
+ """
133
+ Resize an image to `(size["height"], size["width"])`.
134
+
135
+ Args:
136
+ image (`np.ndarray`):
137
+ Image to resize.
138
+ size (`Dict[str, int]`):
139
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
140
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.NEAREST`):
141
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.NEAREST`.
142
+ data_format (`ChannelDimension` or `str`, *optional*):
143
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
144
+ image is used. Can be one of:
145
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
146
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
147
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
148
+ input_data_format (`ChannelDimension` or `str`, *optional*):
149
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
150
+ from the input image. Can be one of:
151
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
152
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
153
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
154
+
155
+ Returns:
156
+ `np.ndarray`: The resized image.
157
+ """
158
+ size = get_size_dict(size)
159
+ if "height" not in size or "width" not in size:
160
+ raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
161
+ output_size = (size["height"], size["width"])
162
+ return resize(
163
+ image,
164
+ size=output_size,
165
+ resample=resample,
166
+ data_format=data_format,
167
+ input_data_format=input_data_format,
168
+ **kwargs,
169
+ )
170
+
171
+ def rescale(
172
+ self,
173
+ image: np.ndarray,
174
+ scale: Union[int, float],
175
+ offset: bool = True,
176
+ data_format: Optional[Union[str, ChannelDimension]] = None,
177
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
178
+ **kwargs,
179
+ ):
180
+ """
181
+ Rescale an image by a scale factor.
182
+
183
+ If `offset` is `True`, the image has its values rescaled by `scale` and then offset by 1. If `scale` is
184
+ 1/127.5, the image is rescaled between [-1, 1].
185
+ image = image * scale - 1
186
+
187
+ If `offset` is `False`, and `scale` is 1/255, the image is rescaled between [0, 1].
188
+ image = image * scale
189
+
190
+ Args:
191
+ image (`np.ndarray`):
192
+ Image to rescale.
193
+ scale (`int` or `float`):
194
+ Scale to apply to the image.
195
+ offset (`bool`, *optional*):
196
+ Whether to scale the image in both negative and positive directions.
197
+ data_format (`str` or `ChannelDimension`, *optional*):
198
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
199
+ input_data_format (`ChannelDimension` or `str`, *optional*):
200
+ The channel dimension format of the input image. If not provided, it will be inferred.
201
+ """
202
+ rescaled_image = rescale(
203
+ image, scale=scale, data_format=data_format, input_data_format=input_data_format, **kwargs
204
+ )
205
+
206
+ if offset:
207
+ rescaled_image = rescaled_image - 1
208
+
209
+ return rescaled_image
210
+
211
+ @filter_out_non_signature_kwargs()
212
+ def preprocess(
213
+ self,
214
+ images: ImageInput,
215
+ do_resize: bool = None,
216
+ size: Dict[str, int] = None,
217
+ resample=None,
218
+ do_center_crop: bool = None,
219
+ crop_size: Dict[str, int] = None,
220
+ do_rescale: bool = None,
221
+ rescale_factor: float = None,
222
+ rescale_offset: bool = None,
223
+ do_normalize: bool = None,
224
+ image_mean: Optional[Union[float, List[float]]] = None,
225
+ image_std: Optional[Union[float, List[float]]] = None,
226
+ include_top: bool = None,
227
+ return_tensors: Optional[Union[str, TensorType]] = None,
228
+ data_format: ChannelDimension = ChannelDimension.FIRST,
229
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
230
+ ) -> PIL.Image.Image:
231
+ """
232
+ Preprocess an image or batch of images.
233
+
234
+ Args:
235
+ images (`ImageInput`):
236
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
237
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
238
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
239
+ Whether to resize the image.
240
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
241
+ Size of the image after `resize`.
242
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
243
+ PILImageResampling filter to use if resizing the image Only has an effect if `do_resize` is set to
244
+ `True`.
245
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
246
+ Whether to center crop the image.
247
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
248
+ Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be
249
+ padded with zeros and then cropped
250
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
251
+ Whether to rescale the image values between [0 - 1].
252
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
253
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
254
+ rescale_offset (`bool`, *optional*, defaults to `self.rescale_offset`):
255
+ Whether to rescale the image between [-scale_range, scale_range] instead of [0, scale_range].
256
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
257
+ Whether to normalize the image.
258
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
259
+ Image mean.
260
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
261
+ Image standard deviation.
262
+ include_top (`bool`, *optional*, defaults to `self.include_top`):
263
+ Rescales the image again for image classification if set to True.
264
+ return_tensors (`str` or `TensorType`, *optional*):
265
+ The type of tensors to return. Can be one of:
266
+ - `None`: Return a list of `np.ndarray`.
267
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
268
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
269
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
270
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
271
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
272
+ The channel dimension format for the output image. Can be one of:
273
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
274
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
275
+ input_data_format (`ChannelDimension` or `str`, *optional*):
276
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
277
+ from the input image. Can be one of:
278
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
279
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
280
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
281
+ """
282
+ do_resize = do_resize if do_resize is not None else self.do_resize
283
+ resample = resample if resample is not None else self.resample
284
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
285
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
286
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
287
+ rescale_offset = rescale_offset if rescale_offset is not None else self.rescale_offset
288
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
289
+ image_mean = image_mean if image_mean is not None else self.image_mean
290
+ image_std = image_std if image_std is not None else self.image_std
291
+ include_top = include_top if include_top is not None else self.include_top
292
+
293
+ size = size if size is not None else self.size
294
+ size = get_size_dict(size)
295
+ crop_size = crop_size if crop_size is not None else self.crop_size
296
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
297
+
298
+ images = make_list_of_images(images)
299
+
300
+ if not valid_images(images):
301
+ raise ValueError(
302
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
303
+ "torch.Tensor, tf.Tensor or jax.ndarray."
304
+ )
305
+ validate_preprocess_arguments(
306
+ do_rescale=do_rescale,
307
+ rescale_factor=rescale_factor,
308
+ do_normalize=do_normalize,
309
+ image_mean=image_mean,
310
+ image_std=image_std,
311
+ do_center_crop=do_center_crop,
312
+ crop_size=crop_size,
313
+ do_resize=do_resize,
314
+ size=size,
315
+ resample=resample,
316
+ )
317
+ # All transformations expect numpy arrays.
318
+ images = [to_numpy_array(image) for image in images]
319
+
320
+ if do_rescale and is_scaled_image(images[0]):
321
+ logger.warning_once(
322
+ "It looks like you are trying to rescale already rescaled images. If the input"
323
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
324
+ )
325
+
326
+ if input_data_format is None:
327
+ # We assume that all images have the same channel dimension format.
328
+ input_data_format = infer_channel_dimension_format(images[0])
329
+
330
+ if do_resize:
331
+ images = [
332
+ self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
333
+ for image in images
334
+ ]
335
+
336
+ if do_center_crop:
337
+ images = [
338
+ self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
339
+ ]
340
+
341
+ if do_rescale:
342
+ images = [
343
+ self.rescale(
344
+ image=image, scale=rescale_factor, offset=rescale_offset, input_data_format=input_data_format
345
+ )
346
+ for image in images
347
+ ]
348
+
349
+ if do_normalize:
350
+ images = [
351
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
352
+ for image in images
353
+ ]
354
+
355
+ if include_top:
356
+ images = [
357
+ self.normalize(image=image, mean=0, std=image_std, input_data_format=input_data_format)
358
+ for image in images
359
+ ]
360
+
361
+ images = [
362
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
363
+ ]
364
+
365
+ data = {"pixel_values": images}
366
+ return BatchFeature(data=data, tensor_type=return_tensors)
367
+
368
+
369
+ __all__ = ["EfficientNetImageProcessor"]
janus/lib/python3.10/site-packages/transformers/models/efficientnet/modeling_efficientnet.py ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Google Research, Inc. 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 EfficientNet model."""
16
+
17
+ import math
18
+ from typing import Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...modeling_outputs import (
27
+ BaseModelOutputWithNoAttention,
28
+ BaseModelOutputWithPoolingAndNoAttention,
29
+ ImageClassifierOutputWithNoAttention,
30
+ )
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...utils import (
33
+ add_code_sample_docstrings,
34
+ add_start_docstrings,
35
+ add_start_docstrings_to_model_forward,
36
+ logging,
37
+ )
38
+ from .configuration_efficientnet import EfficientNetConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ # General docstring
44
+ _CONFIG_FOR_DOC = "EfficientNetConfig"
45
+
46
+ # Base docstring
47
+ _CHECKPOINT_FOR_DOC = "google/efficientnet-b7"
48
+ _EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7]
49
+
50
+ # Image classification docstring
51
+ _IMAGE_CLASS_CHECKPOINT = "google/efficientnet-b7"
52
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
53
+
54
+
55
+ EFFICIENTNET_START_DOCSTRING = r"""
56
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
57
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
58
+ behavior.
59
+
60
+ Parameters:
61
+ config ([`EfficientNetConfig`]): Model configuration class with all the parameters of the model.
62
+ Initializing with a config file does not load the weights associated with the model, only the
63
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
64
+ """
65
+
66
+ EFFICIENTNET_INPUTS_DOCSTRING = r"""
67
+ Args:
68
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
69
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
70
+ [`AutoImageProcessor.__call__`] for details.
71
+
72
+ output_hidden_states (`bool`, *optional*):
73
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
74
+ more detail.
75
+ return_dict (`bool`, *optional*):
76
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
77
+ """
78
+
79
+
80
+ def round_filters(config: EfficientNetConfig, num_channels: int):
81
+ r"""
82
+ Round number of filters based on depth multiplier.
83
+ """
84
+ divisor = config.depth_divisor
85
+ num_channels *= config.width_coefficient
86
+ new_dim = max(divisor, int(num_channels + divisor / 2) // divisor * divisor)
87
+
88
+ # Make sure that round down does not go down by more than 10%.
89
+ if new_dim < 0.9 * num_channels:
90
+ new_dim += divisor
91
+
92
+ return int(new_dim)
93
+
94
+
95
+ def correct_pad(kernel_size: Union[int, Tuple], adjust: bool = True):
96
+ r"""
97
+ Utility function to get the tuple padding value for the depthwise convolution.
98
+
99
+ Args:
100
+ kernel_size (`int` or `tuple`):
101
+ Kernel size of the convolution layers.
102
+ adjust (`bool`, *optional*, defaults to `True`):
103
+ Adjusts padding value to apply to right and bottom sides of the input.
104
+ """
105
+ if isinstance(kernel_size, int):
106
+ kernel_size = (kernel_size, kernel_size)
107
+
108
+ correct = (kernel_size[0] // 2, kernel_size[1] // 2)
109
+ if adjust:
110
+ return (correct[1] - 1, correct[1], correct[0] - 1, correct[0])
111
+ else:
112
+ return (correct[1], correct[1], correct[0], correct[0])
113
+
114
+
115
+ class EfficientNetEmbeddings(nn.Module):
116
+ r"""
117
+ A module that corresponds to the stem module of the original work.
118
+ """
119
+
120
+ def __init__(self, config: EfficientNetConfig):
121
+ super().__init__()
122
+
123
+ self.out_dim = round_filters(config, 32)
124
+ self.padding = nn.ZeroPad2d(padding=(0, 1, 0, 1))
125
+ self.convolution = nn.Conv2d(
126
+ config.num_channels, self.out_dim, kernel_size=3, stride=2, padding="valid", bias=False
127
+ )
128
+ self.batchnorm = nn.BatchNorm2d(self.out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum)
129
+ self.activation = ACT2FN[config.hidden_act]
130
+
131
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
132
+ features = self.padding(pixel_values)
133
+ features = self.convolution(features)
134
+ features = self.batchnorm(features)
135
+ features = self.activation(features)
136
+
137
+ return features
138
+
139
+
140
+ class EfficientNetDepthwiseConv2d(nn.Conv2d):
141
+ def __init__(
142
+ self,
143
+ in_channels,
144
+ depth_multiplier=1,
145
+ kernel_size=3,
146
+ stride=1,
147
+ padding=0,
148
+ dilation=1,
149
+ bias=True,
150
+ padding_mode="zeros",
151
+ ):
152
+ out_channels = in_channels * depth_multiplier
153
+ super().__init__(
154
+ in_channels=in_channels,
155
+ out_channels=out_channels,
156
+ kernel_size=kernel_size,
157
+ stride=stride,
158
+ padding=padding,
159
+ dilation=dilation,
160
+ groups=in_channels,
161
+ bias=bias,
162
+ padding_mode=padding_mode,
163
+ )
164
+
165
+
166
+ class EfficientNetExpansionLayer(nn.Module):
167
+ r"""
168
+ This corresponds to the expansion phase of each block in the original implementation.
169
+ """
170
+
171
+ def __init__(self, config: EfficientNetConfig, in_dim: int, out_dim: int, stride: int):
172
+ super().__init__()
173
+ self.expand_conv = nn.Conv2d(
174
+ in_channels=in_dim,
175
+ out_channels=out_dim,
176
+ kernel_size=1,
177
+ padding="same",
178
+ bias=False,
179
+ )
180
+ self.expand_bn = nn.BatchNorm2d(num_features=out_dim, eps=config.batch_norm_eps)
181
+ self.expand_act = ACT2FN[config.hidden_act]
182
+
183
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
184
+ # Expand phase
185
+ hidden_states = self.expand_conv(hidden_states)
186
+ hidden_states = self.expand_bn(hidden_states)
187
+ hidden_states = self.expand_act(hidden_states)
188
+
189
+ return hidden_states
190
+
191
+
192
+ class EfficientNetDepthwiseLayer(nn.Module):
193
+ r"""
194
+ This corresponds to the depthwise convolution phase of each block in the original implementation.
195
+ """
196
+
197
+ def __init__(
198
+ self,
199
+ config: EfficientNetConfig,
200
+ in_dim: int,
201
+ stride: int,
202
+ kernel_size: int,
203
+ adjust_padding: bool,
204
+ ):
205
+ super().__init__()
206
+ self.stride = stride
207
+ conv_pad = "valid" if self.stride == 2 else "same"
208
+ padding = correct_pad(kernel_size, adjust=adjust_padding)
209
+
210
+ self.depthwise_conv_pad = nn.ZeroPad2d(padding=padding)
211
+ self.depthwise_conv = EfficientNetDepthwiseConv2d(
212
+ in_dim, kernel_size=kernel_size, stride=stride, padding=conv_pad, bias=False
213
+ )
214
+ self.depthwise_norm = nn.BatchNorm2d(
215
+ num_features=in_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum
216
+ )
217
+ self.depthwise_act = ACT2FN[config.hidden_act]
218
+
219
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
220
+ # Depthwise convolution
221
+ if self.stride == 2:
222
+ hidden_states = self.depthwise_conv_pad(hidden_states)
223
+
224
+ hidden_states = self.depthwise_conv(hidden_states)
225
+ hidden_states = self.depthwise_norm(hidden_states)
226
+ hidden_states = self.depthwise_act(hidden_states)
227
+
228
+ return hidden_states
229
+
230
+
231
+ class EfficientNetSqueezeExciteLayer(nn.Module):
232
+ r"""
233
+ This corresponds to the Squeeze and Excitement phase of each block in the original implementation.
234
+ """
235
+
236
+ def __init__(self, config: EfficientNetConfig, in_dim: int, expand_dim: int, expand: bool = False):
237
+ super().__init__()
238
+ self.dim = expand_dim if expand else in_dim
239
+ self.dim_se = max(1, int(in_dim * config.squeeze_expansion_ratio))
240
+
241
+ self.squeeze = nn.AdaptiveAvgPool2d(output_size=1)
242
+ self.reduce = nn.Conv2d(
243
+ in_channels=self.dim,
244
+ out_channels=self.dim_se,
245
+ kernel_size=1,
246
+ padding="same",
247
+ )
248
+ self.expand = nn.Conv2d(
249
+ in_channels=self.dim_se,
250
+ out_channels=self.dim,
251
+ kernel_size=1,
252
+ padding="same",
253
+ )
254
+ self.act_reduce = ACT2FN[config.hidden_act]
255
+ self.act_expand = nn.Sigmoid()
256
+
257
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
258
+ inputs = hidden_states
259
+ hidden_states = self.squeeze(hidden_states)
260
+ hidden_states = self.reduce(hidden_states)
261
+ hidden_states = self.act_reduce(hidden_states)
262
+
263
+ hidden_states = self.expand(hidden_states)
264
+ hidden_states = self.act_expand(hidden_states)
265
+ hidden_states = torch.mul(inputs, hidden_states)
266
+
267
+ return hidden_states
268
+
269
+
270
+ class EfficientNetFinalBlockLayer(nn.Module):
271
+ r"""
272
+ This corresponds to the final phase of each block in the original implementation.
273
+ """
274
+
275
+ def __init__(
276
+ self, config: EfficientNetConfig, in_dim: int, out_dim: int, stride: int, drop_rate: float, id_skip: bool
277
+ ):
278
+ super().__init__()
279
+ self.apply_dropout = stride == 1 and not id_skip
280
+ self.project_conv = nn.Conv2d(
281
+ in_channels=in_dim,
282
+ out_channels=out_dim,
283
+ kernel_size=1,
284
+ padding="same",
285
+ bias=False,
286
+ )
287
+ self.project_bn = nn.BatchNorm2d(
288
+ num_features=out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum
289
+ )
290
+ self.dropout = nn.Dropout(p=drop_rate)
291
+
292
+ def forward(self, embeddings: torch.FloatTensor, hidden_states: torch.FloatTensor) -> torch.Tensor:
293
+ hidden_states = self.project_conv(hidden_states)
294
+ hidden_states = self.project_bn(hidden_states)
295
+
296
+ if self.apply_dropout:
297
+ hidden_states = self.dropout(hidden_states)
298
+ hidden_states = hidden_states + embeddings
299
+
300
+ return hidden_states
301
+
302
+
303
+ class EfficientNetBlock(nn.Module):
304
+ r"""
305
+ This corresponds to the expansion and depthwise convolution phase of each block in the original implementation.
306
+
307
+ Args:
308
+ config ([`EfficientNetConfig`]):
309
+ Model configuration class.
310
+ in_dim (`int`):
311
+ Number of input channels.
312
+ out_dim (`int`):
313
+ Number of output channels.
314
+ stride (`int`):
315
+ Stride size to be used in convolution layers.
316
+ expand_ratio (`int`):
317
+ Expand ratio to set the output dimensions for the expansion and squeeze-excite layers.
318
+ kernel_size (`int`):
319
+ Kernel size for the depthwise convolution layer.
320
+ drop_rate (`float`):
321
+ Dropout rate to be used in the final phase of each block.
322
+ id_skip (`bool`):
323
+ Whether to apply dropout and sum the final hidden states with the input embeddings during the final phase
324
+ of each block. Set to `True` for the first block of each stage.
325
+ adjust_padding (`bool`):
326
+ Whether to apply padding to only right and bottom side of the input kernel before the depthwise convolution
327
+ operation, set to `True` for inputs with odd input sizes.
328
+ """
329
+
330
+ def __init__(
331
+ self,
332
+ config: EfficientNetConfig,
333
+ in_dim: int,
334
+ out_dim: int,
335
+ stride: int,
336
+ expand_ratio: int,
337
+ kernel_size: int,
338
+ drop_rate: float,
339
+ id_skip: bool,
340
+ adjust_padding: bool,
341
+ ):
342
+ super().__init__()
343
+ self.expand_ratio = expand_ratio
344
+ self.expand = True if self.expand_ratio != 1 else False
345
+ expand_in_dim = in_dim * expand_ratio
346
+
347
+ if self.expand:
348
+ self.expansion = EfficientNetExpansionLayer(
349
+ config=config, in_dim=in_dim, out_dim=expand_in_dim, stride=stride
350
+ )
351
+
352
+ self.depthwise_conv = EfficientNetDepthwiseLayer(
353
+ config=config,
354
+ in_dim=expand_in_dim if self.expand else in_dim,
355
+ stride=stride,
356
+ kernel_size=kernel_size,
357
+ adjust_padding=adjust_padding,
358
+ )
359
+ self.squeeze_excite = EfficientNetSqueezeExciteLayer(
360
+ config=config, in_dim=in_dim, expand_dim=expand_in_dim, expand=self.expand
361
+ )
362
+ self.projection = EfficientNetFinalBlockLayer(
363
+ config=config,
364
+ in_dim=expand_in_dim if self.expand else in_dim,
365
+ out_dim=out_dim,
366
+ stride=stride,
367
+ drop_rate=drop_rate,
368
+ id_skip=id_skip,
369
+ )
370
+
371
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
372
+ embeddings = hidden_states
373
+ # Expansion and depthwise convolution phase
374
+ if self.expand_ratio != 1:
375
+ hidden_states = self.expansion(hidden_states)
376
+ hidden_states = self.depthwise_conv(hidden_states)
377
+
378
+ # Squeeze and excite phase
379
+ hidden_states = self.squeeze_excite(hidden_states)
380
+ hidden_states = self.projection(embeddings, hidden_states)
381
+ return hidden_states
382
+
383
+
384
+ class EfficientNetEncoder(nn.Module):
385
+ r"""
386
+ Forward propogates the embeddings through each EfficientNet block.
387
+
388
+ Args:
389
+ config ([`EfficientNetConfig`]):
390
+ Model configuration class.
391
+ """
392
+
393
+ def __init__(self, config: EfficientNetConfig):
394
+ super().__init__()
395
+ self.config = config
396
+ self.depth_coefficient = config.depth_coefficient
397
+
398
+ def round_repeats(repeats):
399
+ # Round number of block repeats based on depth multiplier.
400
+ return int(math.ceil(self.depth_coefficient * repeats))
401
+
402
+ num_base_blocks = len(config.in_channels)
403
+ num_blocks = sum(round_repeats(n) for n in config.num_block_repeats)
404
+
405
+ curr_block_num = 0
406
+ blocks = []
407
+ for i in range(num_base_blocks):
408
+ in_dim = round_filters(config, config.in_channels[i])
409
+ out_dim = round_filters(config, config.out_channels[i])
410
+ stride = config.strides[i]
411
+ kernel_size = config.kernel_sizes[i]
412
+ expand_ratio = config.expand_ratios[i]
413
+
414
+ for j in range(round_repeats(config.num_block_repeats[i])):
415
+ id_skip = True if j == 0 else False
416
+ stride = 1 if j > 0 else stride
417
+ in_dim = out_dim if j > 0 else in_dim
418
+ adjust_padding = False if curr_block_num in config.depthwise_padding else True
419
+ drop_rate = config.drop_connect_rate * curr_block_num / num_blocks
420
+
421
+ block = EfficientNetBlock(
422
+ config=config,
423
+ in_dim=in_dim,
424
+ out_dim=out_dim,
425
+ stride=stride,
426
+ kernel_size=kernel_size,
427
+ expand_ratio=expand_ratio,
428
+ drop_rate=drop_rate,
429
+ id_skip=id_skip,
430
+ adjust_padding=adjust_padding,
431
+ )
432
+ blocks.append(block)
433
+ curr_block_num += 1
434
+
435
+ self.blocks = nn.ModuleList(blocks)
436
+ self.top_conv = nn.Conv2d(
437
+ in_channels=out_dim,
438
+ out_channels=round_filters(config, 1280),
439
+ kernel_size=1,
440
+ padding="same",
441
+ bias=False,
442
+ )
443
+ self.top_bn = nn.BatchNorm2d(
444
+ num_features=config.hidden_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum
445
+ )
446
+ self.top_activation = ACT2FN[config.hidden_act]
447
+
448
+ def forward(
449
+ self,
450
+ hidden_states: torch.FloatTensor,
451
+ output_hidden_states: Optional[bool] = False,
452
+ return_dict: Optional[bool] = True,
453
+ ) -> BaseModelOutputWithNoAttention:
454
+ all_hidden_states = (hidden_states,) if output_hidden_states else None
455
+
456
+ for block in self.blocks:
457
+ hidden_states = block(hidden_states)
458
+ if output_hidden_states:
459
+ all_hidden_states += (hidden_states,)
460
+
461
+ hidden_states = self.top_conv(hidden_states)
462
+ hidden_states = self.top_bn(hidden_states)
463
+ hidden_states = self.top_activation(hidden_states)
464
+
465
+ if not return_dict:
466
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
467
+
468
+ return BaseModelOutputWithNoAttention(
469
+ last_hidden_state=hidden_states,
470
+ hidden_states=all_hidden_states,
471
+ )
472
+
473
+
474
+ class EfficientNetPreTrainedModel(PreTrainedModel):
475
+ """
476
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
477
+ models.
478
+ """
479
+
480
+ config_class = EfficientNetConfig
481
+ base_model_prefix = "efficientnet"
482
+ main_input_name = "pixel_values"
483
+ _no_split_modules = []
484
+
485
+ def _init_weights(self, module):
486
+ """Initialize the weights"""
487
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
488
+ # Slightly different from the TF version which uses truncated_normal for initialization
489
+ # cf https://github.com/pytorch/pytorch/pull/5617
490
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
491
+ if module.bias is not None:
492
+ module.bias.data.zero_()
493
+ elif isinstance(module, nn.LayerNorm):
494
+ module.bias.data.zero_()
495
+ module.weight.data.fill_(1.0)
496
+
497
+
498
+ @add_start_docstrings(
499
+ "The bare EfficientNet model outputting raw features without any specific head on top.",
500
+ EFFICIENTNET_START_DOCSTRING,
501
+ )
502
+ class EfficientNetModel(EfficientNetPreTrainedModel):
503
+ def __init__(self, config: EfficientNetConfig):
504
+ super().__init__(config)
505
+ self.config = config
506
+ self.embeddings = EfficientNetEmbeddings(config)
507
+ self.encoder = EfficientNetEncoder(config)
508
+
509
+ # Final pooling layer
510
+ if config.pooling_type == "mean":
511
+ self.pooler = nn.AvgPool2d(config.hidden_dim, ceil_mode=True)
512
+ elif config.pooling_type == "max":
513
+ self.pooler = nn.MaxPool2d(config.hidden_dim, ceil_mode=True)
514
+ else:
515
+ raise ValueError(f"config.pooling must be one of ['mean', 'max'] got {config.pooling}")
516
+
517
+ # Initialize weights and apply final processing
518
+ self.post_init()
519
+
520
+ @add_start_docstrings_to_model_forward(EFFICIENTNET_INPUTS_DOCSTRING)
521
+ @add_code_sample_docstrings(
522
+ checkpoint=_CHECKPOINT_FOR_DOC,
523
+ output_type=BaseModelOutputWithPoolingAndNoAttention,
524
+ config_class=_CONFIG_FOR_DOC,
525
+ modality="vision",
526
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
527
+ )
528
+ def forward(
529
+ self,
530
+ pixel_values: torch.FloatTensor = None,
531
+ output_hidden_states: Optional[bool] = None,
532
+ return_dict: Optional[bool] = None,
533
+ ) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:
534
+ output_hidden_states = (
535
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
536
+ )
537
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
538
+
539
+ if pixel_values is None:
540
+ raise ValueError("You have to specify pixel_values")
541
+
542
+ embedding_output = self.embeddings(pixel_values)
543
+
544
+ encoder_outputs = self.encoder(
545
+ embedding_output,
546
+ output_hidden_states=output_hidden_states,
547
+ return_dict=return_dict,
548
+ )
549
+ # Apply pooling
550
+ last_hidden_state = encoder_outputs[0]
551
+ pooled_output = self.pooler(last_hidden_state)
552
+ # Reshape (batch_size, 1280, 1 , 1) -> (batch_size, 1280)
553
+ pooled_output = pooled_output.reshape(pooled_output.shape[:2])
554
+
555
+ if not return_dict:
556
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
557
+
558
+ return BaseModelOutputWithPoolingAndNoAttention(
559
+ last_hidden_state=last_hidden_state,
560
+ pooler_output=pooled_output,
561
+ hidden_states=encoder_outputs.hidden_states,
562
+ )
563
+
564
+
565
+ @add_start_docstrings(
566
+ """
567
+ EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g.
568
+ for ImageNet.
569
+ """,
570
+ EFFICIENTNET_START_DOCSTRING,
571
+ )
572
+ class EfficientNetForImageClassification(EfficientNetPreTrainedModel):
573
+ def __init__(self, config):
574
+ super().__init__(config)
575
+ self.num_labels = config.num_labels
576
+ self.config = config
577
+ self.efficientnet = EfficientNetModel(config)
578
+ # Classifier head
579
+ self.dropout = nn.Dropout(p=config.dropout_rate)
580
+ self.classifier = nn.Linear(config.hidden_dim, self.num_labels) if self.num_labels > 0 else nn.Identity()
581
+
582
+ # Initialize weights and apply final processing
583
+ self.post_init()
584
+
585
+ @add_start_docstrings_to_model_forward(EFFICIENTNET_INPUTS_DOCSTRING)
586
+ @add_code_sample_docstrings(
587
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
588
+ output_type=ImageClassifierOutputWithNoAttention,
589
+ config_class=_CONFIG_FOR_DOC,
590
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
591
+ )
592
+ def forward(
593
+ self,
594
+ pixel_values: torch.FloatTensor = None,
595
+ labels: Optional[torch.LongTensor] = None,
596
+ output_hidden_states: Optional[bool] = None,
597
+ return_dict: Optional[bool] = None,
598
+ ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
599
+ r"""
600
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
601
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
602
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
603
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
604
+ """
605
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
606
+
607
+ outputs = self.efficientnet(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
608
+
609
+ pooled_output = outputs.pooler_output if return_dict else outputs[1]
610
+ pooled_output = self.dropout(pooled_output)
611
+ logits = self.classifier(pooled_output)
612
+
613
+ loss = None
614
+ if labels is not None:
615
+ if self.config.problem_type is None:
616
+ if self.num_labels == 1:
617
+ self.config.problem_type = "regression"
618
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
619
+ self.config.problem_type = "single_label_classification"
620
+ else:
621
+ self.config.problem_type = "multi_label_classification"
622
+
623
+ if self.config.problem_type == "regression":
624
+ loss_fct = MSELoss()
625
+ if self.num_labels == 1:
626
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
627
+ else:
628
+ loss = loss_fct(logits, labels)
629
+ elif self.config.problem_type == "single_label_classification":
630
+ loss_fct = CrossEntropyLoss()
631
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
632
+ elif self.config.problem_type == "multi_label_classification":
633
+ loss_fct = BCEWithLogitsLoss()
634
+ loss = loss_fct(logits, labels)
635
+
636
+ if not return_dict:
637
+ output = (logits,) + outputs[2:]
638
+ return ((loss,) + output) if loss is not None else output
639
+
640
+ return ImageClassifierOutputWithNoAttention(
641
+ loss=loss,
642
+ logits=logits,
643
+ hidden_states=outputs.hidden_states,
644
+ )
645
+
646
+
647
+ __all__ = ["EfficientNetForImageClassification", "EfficientNetModel", "EfficientNetPreTrainedModel"]
janus/lib/python3.10/site-packages/transformers/models/mpnet/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mpnet import *
22
+ from .modeling_mpnet import *
23
+ from .modeling_tf_mpnet import *
24
+ from .tokenization_mpnet import *
25
+ from .tokenization_mpnet_fast import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (628 Bytes). View file
 
janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/configuration_mpnet.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/modeling_mpnet.cpython-310.pyc ADDED
Binary file (30.3 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/mpnet/__pycache__/tokenization_mpnet_fast.cpython-310.pyc ADDED
Binary file (7.57 kB). View file
 
janus/lib/python3.10/site-packages/transformers/models/mpnet/configuration_mpnet.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
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
+ """MPNet model configuration"""
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class MPNetConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`MPNetModel`] or a [`TFMPNetModel`]. It is used to
28
+ instantiate a MPNet model according to the specified arguments, defining the model architecture. Instantiating a
29
+ configuration with the defaults will yield a similar configuration to that of the MPNet
30
+ [microsoft/mpnet-base](https://huggingface.co/microsoft/mpnet-base) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 30527):
37
+ Vocabulary size of the MPNet model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`MPNetModel`] or [`TFMPNetModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 12):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_size (`int`, *optional*, defaults to 3072):
46
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
47
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
49
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
50
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
51
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
52
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
53
+ The dropout ratio for the attention probabilities.
54
+ max_position_embeddings (`int`, *optional*, defaults to 512):
55
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
56
+ just in case (e.g., 512 or 1024 or 2048).
57
+ initializer_range (`float`, *optional*, defaults to 0.02):
58
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
59
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
60
+ The epsilon used by the layer normalization layers.
61
+ relative_attention_num_buckets (`int`, *optional*, defaults to 32):
62
+ The number of buckets to use for each attention layer.
63
+
64
+ Examples:
65
+
66
+ ```python
67
+ >>> from transformers import MPNetModel, MPNetConfig
68
+
69
+ >>> # Initializing a MPNet mpnet-base style configuration
70
+ >>> configuration = MPNetConfig()
71
+
72
+ >>> # Initializing a model from the mpnet-base style configuration
73
+ >>> model = MPNetModel(configuration)
74
+
75
+ >>> # Accessing the model configuration
76
+ >>> configuration = model.config
77
+ ```"""
78
+
79
+ model_type = "mpnet"
80
+
81
+ def __init__(
82
+ self,
83
+ vocab_size=30527,
84
+ hidden_size=768,
85
+ num_hidden_layers=12,
86
+ num_attention_heads=12,
87
+ intermediate_size=3072,
88
+ hidden_act="gelu",
89
+ hidden_dropout_prob=0.1,
90
+ attention_probs_dropout_prob=0.1,
91
+ max_position_embeddings=512,
92
+ initializer_range=0.02,
93
+ layer_norm_eps=1e-12,
94
+ relative_attention_num_buckets=32,
95
+ pad_token_id=1,
96
+ bos_token_id=0,
97
+ eos_token_id=2,
98
+ **kwargs,
99
+ ):
100
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
101
+
102
+ self.vocab_size = vocab_size
103
+ self.hidden_size = hidden_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.hidden_act = hidden_act
107
+ self.intermediate_size = intermediate_size
108
+ self.hidden_dropout_prob = hidden_dropout_prob
109
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
110
+ self.max_position_embeddings = max_position_embeddings
111
+ self.initializer_range = initializer_range
112
+ self.layer_norm_eps = layer_norm_eps
113
+ self.relative_attention_num_buckets = relative_attention_num_buckets
114
+
115
+
116
+ __all__ = ["MPNetConfig"]
janus/lib/python3.10/site-packages/transformers/models/mpnet/modeling_mpnet.py ADDED
@@ -0,0 +1,1064 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
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
+ """PyTorch MPNet model."""
17
+
18
+ import math
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ...activations import ACT2FN, gelu
26
+ from ...modeling_outputs import (
27
+ BaseModelOutput,
28
+ BaseModelOutputWithPooling,
29
+ MaskedLMOutput,
30
+ MultipleChoiceModelOutput,
31
+ QuestionAnsweringModelOutput,
32
+ SequenceClassifierOutput,
33
+ TokenClassifierOutput,
34
+ )
35
+ from ...modeling_utils import PreTrainedModel
36
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
37
+ from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
38
+ from .configuration_mpnet import MPNetConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CHECKPOINT_FOR_DOC = "microsoft/mpnet-base"
44
+ _CONFIG_FOR_DOC = "MPNetConfig"
45
+
46
+
47
+ class MPNetPreTrainedModel(PreTrainedModel):
48
+ config_class = MPNetConfig
49
+ base_model_prefix = "mpnet"
50
+
51
+ def _init_weights(self, module):
52
+ """Initialize the weights"""
53
+ if isinstance(module, nn.Linear):
54
+ # Slightly different from the TF version which uses truncated_normal for initialization
55
+ # cf https://github.com/pytorch/pytorch/pull/5617
56
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
57
+ if module.bias is not None:
58
+ module.bias.data.zero_()
59
+ elif isinstance(module, nn.Embedding):
60
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
61
+ if module.padding_idx is not None:
62
+ module.weight.data[module.padding_idx].zero_()
63
+ elif isinstance(module, nn.LayerNorm):
64
+ module.bias.data.zero_()
65
+ module.weight.data.fill_(1.0)
66
+
67
+
68
+ class MPNetEmbeddings(nn.Module):
69
+ def __init__(self, config):
70
+ super().__init__()
71
+ self.padding_idx = 1
72
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=self.padding_idx)
73
+ self.position_embeddings = nn.Embedding(
74
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
75
+ )
76
+
77
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
78
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
79
+ self.register_buffer(
80
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
81
+ )
82
+
83
+ def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, **kwargs):
84
+ if position_ids is None:
85
+ if input_ids is not None:
86
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx)
87
+ else:
88
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
89
+
90
+ if input_ids is not None:
91
+ input_shape = input_ids.size()
92
+ else:
93
+ input_shape = inputs_embeds.size()[:-1]
94
+
95
+ seq_length = input_shape[1]
96
+
97
+ if position_ids is None:
98
+ position_ids = self.position_ids[:, :seq_length]
99
+
100
+ if inputs_embeds is None:
101
+ inputs_embeds = self.word_embeddings(input_ids)
102
+ position_embeddings = self.position_embeddings(position_ids)
103
+
104
+ embeddings = inputs_embeds + position_embeddings
105
+ embeddings = self.LayerNorm(embeddings)
106
+ embeddings = self.dropout(embeddings)
107
+ return embeddings
108
+
109
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
110
+ """
111
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
112
+
113
+ Args:
114
+ inputs_embeds: torch.Tensor
115
+
116
+ Returns: torch.Tensor
117
+ """
118
+ input_shape = inputs_embeds.size()[:-1]
119
+ sequence_length = input_shape[1]
120
+
121
+ position_ids = torch.arange(
122
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
123
+ )
124
+ return position_ids.unsqueeze(0).expand(input_shape)
125
+
126
+
127
+ class MPNetSelfAttention(nn.Module):
128
+ def __init__(self, config):
129
+ super().__init__()
130
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
131
+ raise ValueError(
132
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
133
+ f"heads ({config.num_attention_heads})"
134
+ )
135
+
136
+ self.num_attention_heads = config.num_attention_heads
137
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
138
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
139
+
140
+ self.q = nn.Linear(config.hidden_size, self.all_head_size)
141
+ self.k = nn.Linear(config.hidden_size, self.all_head_size)
142
+ self.v = nn.Linear(config.hidden_size, self.all_head_size)
143
+ self.o = nn.Linear(config.hidden_size, config.hidden_size)
144
+
145
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
146
+
147
+ def transpose_for_scores(self, x):
148
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
149
+ x = x.view(*new_x_shape)
150
+ return x.permute(0, 2, 1, 3)
151
+
152
+ def forward(
153
+ self,
154
+ hidden_states,
155
+ attention_mask=None,
156
+ head_mask=None,
157
+ position_bias=None,
158
+ output_attentions=False,
159
+ **kwargs,
160
+ ):
161
+ q = self.q(hidden_states)
162
+ k = self.k(hidden_states)
163
+ v = self.v(hidden_states)
164
+
165
+ q = self.transpose_for_scores(q)
166
+ k = self.transpose_for_scores(k)
167
+ v = self.transpose_for_scores(v)
168
+
169
+ # Take the dot product between "query" and "key" to get the raw attention scores.
170
+ attention_scores = torch.matmul(q, k.transpose(-1, -2))
171
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
172
+
173
+ # Apply relative position embedding (precomputed in MPNetEncoder) if provided.
174
+ if position_bias is not None:
175
+ attention_scores += position_bias
176
+
177
+ if attention_mask is not None:
178
+ attention_scores = attention_scores + attention_mask
179
+
180
+ # Normalize the attention scores to probabilities.
181
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
182
+
183
+ attention_probs = self.dropout(attention_probs)
184
+
185
+ if head_mask is not None:
186
+ attention_probs = attention_probs * head_mask
187
+
188
+ c = torch.matmul(attention_probs, v)
189
+
190
+ c = c.permute(0, 2, 1, 3).contiguous()
191
+ new_c_shape = c.size()[:-2] + (self.all_head_size,)
192
+ c = c.view(*new_c_shape)
193
+
194
+ o = self.o(c)
195
+
196
+ outputs = (o, attention_probs) if output_attentions else (o,)
197
+ return outputs
198
+
199
+
200
+ class MPNetAttention(nn.Module):
201
+ def __init__(self, config):
202
+ super().__init__()
203
+ self.attn = MPNetSelfAttention(config)
204
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
205
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
206
+
207
+ self.pruned_heads = set()
208
+
209
+ def prune_heads(self, heads):
210
+ if len(heads) == 0:
211
+ return
212
+ heads, index = find_pruneable_heads_and_indices(
213
+ heads, self.attn.num_attention_heads, self.attn.attention_head_size, self.pruned_heads
214
+ )
215
+
216
+ self.attn.q = prune_linear_layer(self.attn.q, index)
217
+ self.attn.k = prune_linear_layer(self.attn.k, index)
218
+ self.attn.v = prune_linear_layer(self.attn.v, index)
219
+ self.attn.o = prune_linear_layer(self.attn.o, index, dim=1)
220
+
221
+ self.attn.num_attention_heads = self.attn.num_attention_heads - len(heads)
222
+ self.attn.all_head_size = self.attn.attention_head_size * self.attn.num_attention_heads
223
+ self.pruned_heads = self.pruned_heads.union(heads)
224
+
225
+ def forward(
226
+ self,
227
+ hidden_states,
228
+ attention_mask=None,
229
+ head_mask=None,
230
+ position_bias=None,
231
+ output_attentions=False,
232
+ **kwargs,
233
+ ):
234
+ self_outputs = self.attn(
235
+ hidden_states,
236
+ attention_mask,
237
+ head_mask,
238
+ position_bias,
239
+ output_attentions=output_attentions,
240
+ )
241
+ attention_output = self.LayerNorm(self.dropout(self_outputs[0]) + hidden_states)
242
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
243
+ return outputs
244
+
245
+
246
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate
247
+ class MPNetIntermediate(nn.Module):
248
+ def __init__(self, config):
249
+ super().__init__()
250
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
251
+ if isinstance(config.hidden_act, str):
252
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
253
+ else:
254
+ self.intermediate_act_fn = config.hidden_act
255
+
256
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
257
+ hidden_states = self.dense(hidden_states)
258
+ hidden_states = self.intermediate_act_fn(hidden_states)
259
+ return hidden_states
260
+
261
+
262
+ # Copied from transformers.models.bert.modeling_bert.BertOutput
263
+ class MPNetOutput(nn.Module):
264
+ def __init__(self, config):
265
+ super().__init__()
266
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
267
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
268
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
269
+
270
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
271
+ hidden_states = self.dense(hidden_states)
272
+ hidden_states = self.dropout(hidden_states)
273
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
274
+ return hidden_states
275
+
276
+
277
+ class MPNetLayer(nn.Module):
278
+ def __init__(self, config):
279
+ super().__init__()
280
+ self.attention = MPNetAttention(config)
281
+ self.intermediate = MPNetIntermediate(config)
282
+ self.output = MPNetOutput(config)
283
+
284
+ def forward(
285
+ self,
286
+ hidden_states,
287
+ attention_mask=None,
288
+ head_mask=None,
289
+ position_bias=None,
290
+ output_attentions=False,
291
+ **kwargs,
292
+ ):
293
+ self_attention_outputs = self.attention(
294
+ hidden_states,
295
+ attention_mask,
296
+ head_mask,
297
+ position_bias=position_bias,
298
+ output_attentions=output_attentions,
299
+ )
300
+ attention_output = self_attention_outputs[0]
301
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
302
+
303
+ intermediate_output = self.intermediate(attention_output)
304
+ layer_output = self.output(intermediate_output, attention_output)
305
+ outputs = (layer_output,) + outputs
306
+ return outputs
307
+
308
+
309
+ class MPNetEncoder(nn.Module):
310
+ def __init__(self, config):
311
+ super().__init__()
312
+ self.config = config
313
+ self.n_heads = config.num_attention_heads
314
+ self.layer = nn.ModuleList([MPNetLayer(config) for _ in range(config.num_hidden_layers)])
315
+ self.relative_attention_bias = nn.Embedding(config.relative_attention_num_buckets, self.n_heads)
316
+
317
+ def forward(
318
+ self,
319
+ hidden_states: torch.Tensor,
320
+ attention_mask: Optional[torch.Tensor] = None,
321
+ head_mask: Optional[torch.Tensor] = None,
322
+ output_attentions: bool = False,
323
+ output_hidden_states: bool = False,
324
+ return_dict: bool = False,
325
+ **kwargs,
326
+ ):
327
+ position_bias = self.compute_position_bias(hidden_states)
328
+ all_hidden_states = () if output_hidden_states else None
329
+ all_attentions = () if output_attentions else None
330
+ for i, layer_module in enumerate(self.layer):
331
+ if output_hidden_states:
332
+ all_hidden_states = all_hidden_states + (hidden_states,)
333
+
334
+ layer_outputs = layer_module(
335
+ hidden_states,
336
+ attention_mask,
337
+ head_mask[i],
338
+ position_bias,
339
+ output_attentions=output_attentions,
340
+ **kwargs,
341
+ )
342
+ hidden_states = layer_outputs[0]
343
+
344
+ if output_attentions:
345
+ all_attentions = all_attentions + (layer_outputs[1],)
346
+
347
+ # Add last layer
348
+ if output_hidden_states:
349
+ all_hidden_states = all_hidden_states + (hidden_states,)
350
+
351
+ if not return_dict:
352
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
353
+ return BaseModelOutput(
354
+ last_hidden_state=hidden_states,
355
+ hidden_states=all_hidden_states,
356
+ attentions=all_attentions,
357
+ )
358
+
359
+ def compute_position_bias(self, x, position_ids=None, num_buckets=32):
360
+ bsz, qlen, klen = x.size(0), x.size(1), x.size(1)
361
+ if position_ids is not None:
362
+ context_position = position_ids[:, :, None]
363
+ memory_position = position_ids[:, None, :]
364
+ else:
365
+ context_position = torch.arange(qlen, dtype=torch.long)[:, None]
366
+ memory_position = torch.arange(klen, dtype=torch.long)[None, :]
367
+
368
+ relative_position = memory_position - context_position
369
+
370
+ rp_bucket = self.relative_position_bucket(relative_position, num_buckets=num_buckets)
371
+ rp_bucket = rp_bucket.to(x.device)
372
+ values = self.relative_attention_bias(rp_bucket)
373
+ values = values.permute([2, 0, 1]).unsqueeze(0)
374
+ values = values.expand((bsz, -1, qlen, klen)).contiguous()
375
+ return values
376
+
377
+ @staticmethod
378
+ def relative_position_bucket(relative_position, num_buckets=32, max_distance=128):
379
+ ret = 0
380
+ n = -relative_position
381
+
382
+ num_buckets //= 2
383
+ ret += (n < 0).to(torch.long) * num_buckets
384
+ n = torch.abs(n)
385
+
386
+ max_exact = num_buckets // 2
387
+ is_small = n < max_exact
388
+
389
+ val_if_large = max_exact + (
390
+ torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact)
391
+ ).to(torch.long)
392
+
393
+ val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1))
394
+ ret += torch.where(is_small, n, val_if_large)
395
+ return ret
396
+
397
+
398
+ # Copied from transformers.models.bert.modeling_bert.BertPooler
399
+ class MPNetPooler(nn.Module):
400
+ def __init__(self, config):
401
+ super().__init__()
402
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
403
+ self.activation = nn.Tanh()
404
+
405
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
406
+ # We "pool" the model by simply taking the hidden state corresponding
407
+ # to the first token.
408
+ first_token_tensor = hidden_states[:, 0]
409
+ pooled_output = self.dense(first_token_tensor)
410
+ pooled_output = self.activation(pooled_output)
411
+ return pooled_output
412
+
413
+
414
+ MPNET_START_DOCSTRING = r"""
415
+
416
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
417
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
418
+ etc.)
419
+
420
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
421
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
422
+ and behavior.
423
+
424
+ Parameters:
425
+ config ([`MPNetConfig`]): Model configuration class with all the parameters of the model.
426
+ Initializing with a config file does not load the weights associated with the model, only the
427
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
428
+ """
429
+
430
+ MPNET_INPUTS_DOCSTRING = r"""
431
+ Args:
432
+ input_ids (`torch.LongTensor` of shape `({0})`):
433
+ Indices of input sequence tokens in the vocabulary.
434
+
435
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
436
+ [`PreTrainedTokenizer.__call__`] for details.
437
+
438
+ [What are input IDs?](../glossary#input-ids)
439
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
440
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
441
+
442
+ - 1 for tokens that are **not masked**,
443
+ - 0 for tokens that are **masked**.
444
+
445
+ [What are attention masks?](../glossary#attention-mask)
446
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
447
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
448
+ config.max_position_embeddings - 1]`.
449
+
450
+ [What are position IDs?](../glossary#position-ids)
451
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
452
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
453
+
454
+ - 1 indicates the head is **not masked**,
455
+ - 0 indicates the head is **masked**.
456
+
457
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
458
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
459
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
460
+ model's internal embedding lookup matrix.
461
+ output_attentions (`bool`, *optional*):
462
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
463
+ tensors for more detail.
464
+ output_hidden_states (`bool`, *optional*):
465
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
466
+ more detail.
467
+ return_dict (`bool`, *optional*):
468
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
469
+ """
470
+
471
+
472
+ @add_start_docstrings(
473
+ "The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.",
474
+ MPNET_START_DOCSTRING,
475
+ )
476
+ class MPNetModel(MPNetPreTrainedModel):
477
+ def __init__(self, config, add_pooling_layer=True):
478
+ super().__init__(config)
479
+ self.config = config
480
+
481
+ self.embeddings = MPNetEmbeddings(config)
482
+ self.encoder = MPNetEncoder(config)
483
+ self.pooler = MPNetPooler(config) if add_pooling_layer else None
484
+
485
+ # Initialize weights and apply final processing
486
+ self.post_init()
487
+
488
+ def get_input_embeddings(self):
489
+ return self.embeddings.word_embeddings
490
+
491
+ def set_input_embeddings(self, value):
492
+ self.embeddings.word_embeddings = value
493
+
494
+ def _prune_heads(self, heads_to_prune):
495
+ """
496
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
497
+ class PreTrainedModel
498
+ """
499
+ for layer, heads in heads_to_prune.items():
500
+ self.encoder.layer[layer].attention.prune_heads(heads)
501
+
502
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
503
+ @add_code_sample_docstrings(
504
+ checkpoint=_CHECKPOINT_FOR_DOC,
505
+ output_type=BaseModelOutputWithPooling,
506
+ config_class=_CONFIG_FOR_DOC,
507
+ )
508
+ def forward(
509
+ self,
510
+ input_ids: Optional[torch.LongTensor] = None,
511
+ attention_mask: Optional[torch.FloatTensor] = None,
512
+ position_ids: Optional[torch.LongTensor] = None,
513
+ head_mask: Optional[torch.FloatTensor] = None,
514
+ inputs_embeds: Optional[torch.FloatTensor] = None,
515
+ output_attentions: Optional[bool] = None,
516
+ output_hidden_states: Optional[bool] = None,
517
+ return_dict: Optional[bool] = None,
518
+ **kwargs,
519
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPooling]:
520
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
521
+ output_hidden_states = (
522
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
523
+ )
524
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
525
+
526
+ if input_ids is not None and inputs_embeds is not None:
527
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
528
+ elif input_ids is not None:
529
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
530
+ input_shape = input_ids.size()
531
+ elif inputs_embeds is not None:
532
+ input_shape = inputs_embeds.size()[:-1]
533
+ else:
534
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
535
+
536
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
537
+
538
+ if attention_mask is None:
539
+ attention_mask = torch.ones(input_shape, device=device)
540
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
541
+
542
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
543
+ embedding_output = self.embeddings(input_ids=input_ids, position_ids=position_ids, inputs_embeds=inputs_embeds)
544
+ encoder_outputs = self.encoder(
545
+ embedding_output,
546
+ attention_mask=extended_attention_mask,
547
+ head_mask=head_mask,
548
+ output_attentions=output_attentions,
549
+ output_hidden_states=output_hidden_states,
550
+ return_dict=return_dict,
551
+ )
552
+ sequence_output = encoder_outputs[0]
553
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
554
+
555
+ if not return_dict:
556
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
557
+
558
+ return BaseModelOutputWithPooling(
559
+ last_hidden_state=sequence_output,
560
+ pooler_output=pooled_output,
561
+ hidden_states=encoder_outputs.hidden_states,
562
+ attentions=encoder_outputs.attentions,
563
+ )
564
+
565
+
566
+ class MPNetForMaskedLM(MPNetPreTrainedModel):
567
+ _tied_weights_keys = ["lm_head.decoder"]
568
+
569
+ def __init__(self, config):
570
+ super().__init__(config)
571
+
572
+ self.mpnet = MPNetModel(config, add_pooling_layer=False)
573
+ self.lm_head = MPNetLMHead(config)
574
+
575
+ # Initialize weights and apply final processing
576
+ self.post_init()
577
+
578
+ def get_output_embeddings(self):
579
+ return self.lm_head.decoder
580
+
581
+ def set_output_embeddings(self, new_embeddings):
582
+ self.lm_head.decoder = new_embeddings
583
+ self.lm_head.bias = new_embeddings.bias
584
+
585
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
586
+ @add_code_sample_docstrings(
587
+ checkpoint=_CHECKPOINT_FOR_DOC,
588
+ output_type=MaskedLMOutput,
589
+ config_class=_CONFIG_FOR_DOC,
590
+ )
591
+ def forward(
592
+ self,
593
+ input_ids: Optional[torch.LongTensor] = None,
594
+ attention_mask: Optional[torch.FloatTensor] = None,
595
+ position_ids: Optional[torch.LongTensor] = None,
596
+ head_mask: Optional[torch.FloatTensor] = None,
597
+ inputs_embeds: Optional[torch.FloatTensor] = None,
598
+ labels: Optional[torch.LongTensor] = None,
599
+ output_attentions: Optional[bool] = None,
600
+ output_hidden_states: Optional[bool] = None,
601
+ return_dict: Optional[bool] = None,
602
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
603
+ r"""
604
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
605
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
606
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
607
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
608
+ """
609
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
610
+
611
+ outputs = self.mpnet(
612
+ input_ids,
613
+ attention_mask=attention_mask,
614
+ position_ids=position_ids,
615
+ head_mask=head_mask,
616
+ inputs_embeds=inputs_embeds,
617
+ output_attentions=output_attentions,
618
+ output_hidden_states=output_hidden_states,
619
+ return_dict=return_dict,
620
+ )
621
+
622
+ sequence_output = outputs[0]
623
+ prediction_scores = self.lm_head(sequence_output)
624
+
625
+ masked_lm_loss = None
626
+ if labels is not None:
627
+ loss_fct = CrossEntropyLoss()
628
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
629
+
630
+ if not return_dict:
631
+ output = (prediction_scores,) + outputs[2:]
632
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
633
+
634
+ return MaskedLMOutput(
635
+ loss=masked_lm_loss,
636
+ logits=prediction_scores,
637
+ hidden_states=outputs.hidden_states,
638
+ attentions=outputs.attentions,
639
+ )
640
+
641
+
642
+ class MPNetLMHead(nn.Module):
643
+ """MPNet Head for masked and permuted language modeling."""
644
+
645
+ def __init__(self, config):
646
+ super().__init__()
647
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
648
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
649
+
650
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
651
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
652
+
653
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
654
+ self.decoder.bias = self.bias
655
+
656
+ def _tie_weights(self):
657
+ self.decoder.bias = self.bias
658
+
659
+ def forward(self, features, **kwargs):
660
+ x = self.dense(features)
661
+ x = gelu(x)
662
+ x = self.layer_norm(x)
663
+
664
+ # project back to size of vocabulary with bias
665
+ x = self.decoder(x)
666
+
667
+ return x
668
+
669
+
670
+ @add_start_docstrings(
671
+ """
672
+ MPNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
673
+ output) e.g. for GLUE tasks.
674
+ """,
675
+ MPNET_START_DOCSTRING,
676
+ )
677
+ class MPNetForSequenceClassification(MPNetPreTrainedModel):
678
+ def __init__(self, config):
679
+ super().__init__(config)
680
+
681
+ self.num_labels = config.num_labels
682
+ self.mpnet = MPNetModel(config, add_pooling_layer=False)
683
+ self.classifier = MPNetClassificationHead(config)
684
+
685
+ # Initialize weights and apply final processing
686
+ self.post_init()
687
+
688
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
689
+ @add_code_sample_docstrings(
690
+ checkpoint=_CHECKPOINT_FOR_DOC,
691
+ output_type=SequenceClassifierOutput,
692
+ config_class=_CONFIG_FOR_DOC,
693
+ )
694
+ def forward(
695
+ self,
696
+ input_ids: Optional[torch.LongTensor] = None,
697
+ attention_mask: Optional[torch.FloatTensor] = None,
698
+ position_ids: Optional[torch.LongTensor] = None,
699
+ head_mask: Optional[torch.FloatTensor] = None,
700
+ inputs_embeds: Optional[torch.FloatTensor] = None,
701
+ labels: Optional[torch.LongTensor] = None,
702
+ output_attentions: Optional[bool] = None,
703
+ output_hidden_states: Optional[bool] = None,
704
+ return_dict: Optional[bool] = None,
705
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
706
+ r"""
707
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
708
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
709
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
710
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
711
+ """
712
+
713
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
714
+
715
+ outputs = self.mpnet(
716
+ input_ids,
717
+ attention_mask=attention_mask,
718
+ position_ids=position_ids,
719
+ head_mask=head_mask,
720
+ inputs_embeds=inputs_embeds,
721
+ output_attentions=output_attentions,
722
+ output_hidden_states=output_hidden_states,
723
+ return_dict=return_dict,
724
+ )
725
+ sequence_output = outputs[0]
726
+ logits = self.classifier(sequence_output)
727
+
728
+ loss = None
729
+ if labels is not None:
730
+ if self.config.problem_type is None:
731
+ if self.num_labels == 1:
732
+ self.config.problem_type = "regression"
733
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
734
+ self.config.problem_type = "single_label_classification"
735
+ else:
736
+ self.config.problem_type = "multi_label_classification"
737
+
738
+ if self.config.problem_type == "regression":
739
+ loss_fct = MSELoss()
740
+ if self.num_labels == 1:
741
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
742
+ else:
743
+ loss = loss_fct(logits, labels)
744
+ elif self.config.problem_type == "single_label_classification":
745
+ loss_fct = CrossEntropyLoss()
746
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
747
+ elif self.config.problem_type == "multi_label_classification":
748
+ loss_fct = BCEWithLogitsLoss()
749
+ loss = loss_fct(logits, labels)
750
+ if not return_dict:
751
+ output = (logits,) + outputs[2:]
752
+ return ((loss,) + output) if loss is not None else output
753
+
754
+ return SequenceClassifierOutput(
755
+ loss=loss,
756
+ logits=logits,
757
+ hidden_states=outputs.hidden_states,
758
+ attentions=outputs.attentions,
759
+ )
760
+
761
+
762
+ @add_start_docstrings(
763
+ """
764
+ MPNet Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
765
+ softmax) e.g. for RocStories/SWAG tasks.
766
+ """,
767
+ MPNET_START_DOCSTRING,
768
+ )
769
+ class MPNetForMultipleChoice(MPNetPreTrainedModel):
770
+ def __init__(self, config):
771
+ super().__init__(config)
772
+
773
+ self.mpnet = MPNetModel(config)
774
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
775
+ self.classifier = nn.Linear(config.hidden_size, 1)
776
+
777
+ # Initialize weights and apply final processing
778
+ self.post_init()
779
+
780
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
781
+ @add_code_sample_docstrings(
782
+ checkpoint=_CHECKPOINT_FOR_DOC,
783
+ output_type=MultipleChoiceModelOutput,
784
+ config_class=_CONFIG_FOR_DOC,
785
+ )
786
+ def forward(
787
+ self,
788
+ input_ids: Optional[torch.LongTensor] = None,
789
+ attention_mask: Optional[torch.FloatTensor] = None,
790
+ position_ids: Optional[torch.LongTensor] = None,
791
+ head_mask: Optional[torch.FloatTensor] = None,
792
+ inputs_embeds: Optional[torch.FloatTensor] = None,
793
+ labels: Optional[torch.LongTensor] = None,
794
+ output_attentions: Optional[bool] = None,
795
+ output_hidden_states: Optional[bool] = None,
796
+ return_dict: Optional[bool] = None,
797
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
798
+ r"""
799
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
800
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
801
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
802
+ `input_ids` above)
803
+ """
804
+
805
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
806
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
807
+
808
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
809
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
810
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
811
+ flat_inputs_embeds = (
812
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
813
+ if inputs_embeds is not None
814
+ else None
815
+ )
816
+
817
+ outputs = self.mpnet(
818
+ flat_input_ids,
819
+ position_ids=flat_position_ids,
820
+ attention_mask=flat_attention_mask,
821
+ head_mask=head_mask,
822
+ inputs_embeds=flat_inputs_embeds,
823
+ output_attentions=output_attentions,
824
+ output_hidden_states=output_hidden_states,
825
+ return_dict=return_dict,
826
+ )
827
+ pooled_output = outputs[1]
828
+
829
+ pooled_output = self.dropout(pooled_output)
830
+ logits = self.classifier(pooled_output)
831
+ reshaped_logits = logits.view(-1, num_choices)
832
+
833
+ loss = None
834
+ if labels is not None:
835
+ loss_fct = CrossEntropyLoss()
836
+ loss = loss_fct(reshaped_logits, labels)
837
+
838
+ if not return_dict:
839
+ output = (reshaped_logits,) + outputs[2:]
840
+ return ((loss,) + output) if loss is not None else output
841
+
842
+ return MultipleChoiceModelOutput(
843
+ loss=loss,
844
+ logits=reshaped_logits,
845
+ hidden_states=outputs.hidden_states,
846
+ attentions=outputs.attentions,
847
+ )
848
+
849
+
850
+ @add_start_docstrings(
851
+ """
852
+ MPNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
853
+ Named-Entity-Recognition (NER) tasks.
854
+ """,
855
+ MPNET_START_DOCSTRING,
856
+ )
857
+ class MPNetForTokenClassification(MPNetPreTrainedModel):
858
+ def __init__(self, config):
859
+ super().__init__(config)
860
+ self.num_labels = config.num_labels
861
+
862
+ self.mpnet = MPNetModel(config, add_pooling_layer=False)
863
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
864
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
865
+
866
+ # Initialize weights and apply final processing
867
+ self.post_init()
868
+
869
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
870
+ @add_code_sample_docstrings(
871
+ checkpoint=_CHECKPOINT_FOR_DOC,
872
+ output_type=TokenClassifierOutput,
873
+ config_class=_CONFIG_FOR_DOC,
874
+ )
875
+ def forward(
876
+ self,
877
+ input_ids: Optional[torch.LongTensor] = None,
878
+ attention_mask: Optional[torch.FloatTensor] = None,
879
+ position_ids: Optional[torch.LongTensor] = None,
880
+ head_mask: Optional[torch.FloatTensor] = None,
881
+ inputs_embeds: Optional[torch.FloatTensor] = None,
882
+ labels: Optional[torch.LongTensor] = None,
883
+ output_attentions: Optional[bool] = None,
884
+ output_hidden_states: Optional[bool] = None,
885
+ return_dict: Optional[bool] = None,
886
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
887
+ r"""
888
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
889
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
890
+ """
891
+
892
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
893
+
894
+ outputs = self.mpnet(
895
+ input_ids,
896
+ attention_mask=attention_mask,
897
+ position_ids=position_ids,
898
+ head_mask=head_mask,
899
+ inputs_embeds=inputs_embeds,
900
+ output_attentions=output_attentions,
901
+ output_hidden_states=output_hidden_states,
902
+ return_dict=return_dict,
903
+ )
904
+
905
+ sequence_output = outputs[0]
906
+
907
+ sequence_output = self.dropout(sequence_output)
908
+ logits = self.classifier(sequence_output)
909
+
910
+ loss = None
911
+ if labels is not None:
912
+ loss_fct = CrossEntropyLoss()
913
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
914
+
915
+ if not return_dict:
916
+ output = (logits,) + outputs[2:]
917
+ return ((loss,) + output) if loss is not None else output
918
+
919
+ return TokenClassifierOutput(
920
+ loss=loss,
921
+ logits=logits,
922
+ hidden_states=outputs.hidden_states,
923
+ attentions=outputs.attentions,
924
+ )
925
+
926
+
927
+ class MPNetClassificationHead(nn.Module):
928
+ """Head for sentence-level classification tasks."""
929
+
930
+ def __init__(self, config):
931
+ super().__init__()
932
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
933
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
934
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
935
+
936
+ def forward(self, features, **kwargs):
937
+ x = features[:, 0, :] # take <s> token (equiv. to BERT's [CLS] token)
938
+ x = self.dropout(x)
939
+ x = self.dense(x)
940
+ x = torch.tanh(x)
941
+ x = self.dropout(x)
942
+ x = self.out_proj(x)
943
+ return x
944
+
945
+
946
+ @add_start_docstrings(
947
+ """
948
+ MPNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
949
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
950
+ """,
951
+ MPNET_START_DOCSTRING,
952
+ )
953
+ class MPNetForQuestionAnswering(MPNetPreTrainedModel):
954
+ def __init__(self, config):
955
+ super().__init__(config)
956
+
957
+ self.num_labels = config.num_labels
958
+ self.mpnet = MPNetModel(config, add_pooling_layer=False)
959
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
960
+
961
+ # Initialize weights and apply final processing
962
+ self.post_init()
963
+
964
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
965
+ @add_code_sample_docstrings(
966
+ checkpoint=_CHECKPOINT_FOR_DOC,
967
+ output_type=QuestionAnsweringModelOutput,
968
+ config_class=_CONFIG_FOR_DOC,
969
+ )
970
+ def forward(
971
+ self,
972
+ input_ids: Optional[torch.LongTensor] = None,
973
+ attention_mask: Optional[torch.FloatTensor] = None,
974
+ position_ids: Optional[torch.LongTensor] = None,
975
+ head_mask: Optional[torch.FloatTensor] = None,
976
+ inputs_embeds: Optional[torch.FloatTensor] = None,
977
+ start_positions: Optional[torch.LongTensor] = None,
978
+ end_positions: Optional[torch.LongTensor] = None,
979
+ output_attentions: Optional[bool] = None,
980
+ output_hidden_states: Optional[bool] = None,
981
+ return_dict: Optional[bool] = None,
982
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
983
+ r"""
984
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
985
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
986
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
987
+ are not taken into account for computing the loss.
988
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
989
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
990
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
991
+ are not taken into account for computing the loss.
992
+ """
993
+
994
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
995
+
996
+ outputs = self.mpnet(
997
+ input_ids,
998
+ attention_mask=attention_mask,
999
+ position_ids=position_ids,
1000
+ head_mask=head_mask,
1001
+ inputs_embeds=inputs_embeds,
1002
+ output_attentions=output_attentions,
1003
+ output_hidden_states=output_hidden_states,
1004
+ return_dict=return_dict,
1005
+ )
1006
+
1007
+ sequence_output = outputs[0]
1008
+
1009
+ logits = self.qa_outputs(sequence_output)
1010
+ start_logits, end_logits = logits.split(1, dim=-1)
1011
+ start_logits = start_logits.squeeze(-1).contiguous()
1012
+ end_logits = end_logits.squeeze(-1).contiguous()
1013
+
1014
+ total_loss = None
1015
+ if start_positions is not None and end_positions is not None:
1016
+ # If we are on multi-GPU, split add a dimension
1017
+ if len(start_positions.size()) > 1:
1018
+ start_positions = start_positions.squeeze(-1)
1019
+ if len(end_positions.size()) > 1:
1020
+ end_positions = end_positions.squeeze(-1)
1021
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1022
+ ignored_index = start_logits.size(1)
1023
+ start_positions = start_positions.clamp(0, ignored_index)
1024
+ end_positions = end_positions.clamp(0, ignored_index)
1025
+
1026
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1027
+ start_loss = loss_fct(start_logits, start_positions)
1028
+ end_loss = loss_fct(end_logits, end_positions)
1029
+ total_loss = (start_loss + end_loss) / 2
1030
+
1031
+ if not return_dict:
1032
+ output = (start_logits, end_logits) + outputs[2:]
1033
+ return ((total_loss,) + output) if total_loss is not None else output
1034
+
1035
+ return QuestionAnsweringModelOutput(
1036
+ loss=total_loss,
1037
+ start_logits=start_logits,
1038
+ end_logits=end_logits,
1039
+ hidden_states=outputs.hidden_states,
1040
+ attentions=outputs.attentions,
1041
+ )
1042
+
1043
+
1044
+ def create_position_ids_from_input_ids(input_ids, padding_idx):
1045
+ """
1046
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1047
+ are ignored. This is modified from fairseq's `utils.make_positions`. :param torch.Tensor x: :return torch.Tensor:
1048
+ """
1049
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1050
+ mask = input_ids.ne(padding_idx).int()
1051
+ incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask
1052
+ return incremental_indices.long() + padding_idx
1053
+
1054
+
1055
+ __all__ = [
1056
+ "MPNetForMaskedLM",
1057
+ "MPNetForMultipleChoice",
1058
+ "MPNetForQuestionAnswering",
1059
+ "MPNetForSequenceClassification",
1060
+ "MPNetForTokenClassification",
1061
+ "MPNetLayer",
1062
+ "MPNetModel",
1063
+ "MPNetPreTrainedModel",
1064
+ ]
janus/lib/python3.10/site-packages/transformers/models/mpnet/modeling_tf_mpnet.py ADDED
@@ -0,0 +1,1354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
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 MPNet model."""
17
+
18
+ from __future__ import annotations
19
+
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
+
27
+ from ...activations_tf import get_tf_activation
28
+ from ...modeling_tf_outputs import (
29
+ TFBaseModelOutput,
30
+ TFBaseModelOutputWithPooling,
31
+ TFMaskedLMOutput,
32
+ TFMultipleChoiceModelOutput,
33
+ TFQuestionAnsweringModelOutput,
34
+ TFSequenceClassifierOutput,
35
+ TFTokenClassifierOutput,
36
+ )
37
+ from ...modeling_tf_utils import (
38
+ TFMaskedLanguageModelingLoss,
39
+ TFModelInputType,
40
+ TFMultipleChoiceLoss,
41
+ TFPreTrainedModel,
42
+ TFQuestionAnsweringLoss,
43
+ TFSequenceClassificationLoss,
44
+ TFTokenClassificationLoss,
45
+ get_initializer,
46
+ keras,
47
+ keras_serializable,
48
+ unpack_inputs,
49
+ )
50
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
51
+ from ...utils import (
52
+ add_code_sample_docstrings,
53
+ add_start_docstrings,
54
+ add_start_docstrings_to_model_forward,
55
+ logging,
56
+ )
57
+ from .configuration_mpnet import MPNetConfig
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CHECKPOINT_FOR_DOC = "microsoft/mpnet-base"
63
+ _CONFIG_FOR_DOC = "MPNetConfig"
64
+
65
+
66
+ class TFMPNetPreTrainedModel(TFPreTrainedModel):
67
+ """
68
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
69
+ models.
70
+ """
71
+
72
+ config_class = MPNetConfig
73
+ base_model_prefix = "mpnet"
74
+
75
+
76
+ class TFMPNetEmbeddings(keras.layers.Layer):
77
+ """Construct the embeddings from word, position embeddings."""
78
+
79
+ def __init__(self, config, **kwargs):
80
+ super().__init__(**kwargs)
81
+
82
+ self.padding_idx = 1
83
+ self.config = config
84
+ self.hidden_size = config.hidden_size
85
+ self.max_position_embeddings = config.max_position_embeddings
86
+ self.initializer_range = config.initializer_range
87
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
88
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
89
+
90
+ def build(self, input_shape=None):
91
+ with tf.name_scope("word_embeddings"):
92
+ self.weight = self.add_weight(
93
+ name="weight",
94
+ shape=[self.config.vocab_size, self.hidden_size],
95
+ initializer=get_initializer(initializer_range=self.initializer_range),
96
+ )
97
+
98
+ with tf.name_scope("position_embeddings"):
99
+ self.position_embeddings = self.add_weight(
100
+ name="embeddings",
101
+ shape=[self.max_position_embeddings, self.hidden_size],
102
+ initializer=get_initializer(initializer_range=self.initializer_range),
103
+ )
104
+
105
+ if self.built:
106
+ return
107
+ self.built = True
108
+ if getattr(self, "LayerNorm", None) is not None:
109
+ with tf.name_scope(self.LayerNorm.name):
110
+ self.LayerNorm.build([None, None, self.config.hidden_size])
111
+
112
+ def create_position_ids_from_input_ids(self, input_ids):
113
+ """
114
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
115
+ symbols are ignored. This is modified from fairseq's `utils.make_positions`.
116
+
117
+ Args:
118
+ input_ids: tf.Tensor
119
+ Returns: tf.Tensor
120
+ """
121
+ mask = tf.cast(tf.math.not_equal(input_ids, self.padding_idx), dtype=input_ids.dtype)
122
+ incremental_indices = tf.math.cumsum(mask, axis=1) * mask
123
+
124
+ return incremental_indices + self.padding_idx
125
+
126
+ def call(self, input_ids=None, position_ids=None, inputs_embeds=None, training=False):
127
+ """
128
+ Applies embedding based on inputs tensor.
129
+
130
+ Returns:
131
+ final_embeddings (`tf.Tensor`): output embedding tensor.
132
+ """
133
+ assert not (input_ids is None and inputs_embeds is None)
134
+
135
+ if input_ids is not None:
136
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
137
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
138
+
139
+ input_shape = shape_list(inputs_embeds)[:-1]
140
+
141
+ if position_ids is None:
142
+ if input_ids is not None:
143
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
144
+ position_ids = self.create_position_ids_from_input_ids(input_ids=input_ids)
145
+ else:
146
+ position_ids = tf.expand_dims(
147
+ tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0
148
+ )
149
+
150
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
151
+ final_embeddings = inputs_embeds + position_embeds
152
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
153
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
154
+
155
+ return final_embeddings
156
+
157
+
158
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->MPNet
159
+ class TFMPNetPooler(keras.layers.Layer):
160
+ def __init__(self, config: MPNetConfig, **kwargs):
161
+ super().__init__(**kwargs)
162
+
163
+ self.dense = keras.layers.Dense(
164
+ units=config.hidden_size,
165
+ kernel_initializer=get_initializer(config.initializer_range),
166
+ activation="tanh",
167
+ name="dense",
168
+ )
169
+ self.config = config
170
+
171
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
172
+ # We "pool" the model by simply taking the hidden state corresponding
173
+ # to the first token.
174
+ first_token_tensor = hidden_states[:, 0]
175
+ pooled_output = self.dense(inputs=first_token_tensor)
176
+
177
+ return pooled_output
178
+
179
+ def build(self, input_shape=None):
180
+ if self.built:
181
+ return
182
+ self.built = True
183
+ if getattr(self, "dense", None) is not None:
184
+ with tf.name_scope(self.dense.name):
185
+ self.dense.build([None, None, self.config.hidden_size])
186
+
187
+
188
+ class TFMPNetSelfAttention(keras.layers.Layer):
189
+ def __init__(self, config, **kwargs):
190
+ super().__init__(**kwargs)
191
+
192
+ if config.hidden_size % config.num_attention_heads != 0:
193
+ raise ValueError(
194
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
195
+ f"heads ({config.num_attention_heads}"
196
+ )
197
+
198
+ self.num_attention_heads = config.num_attention_heads
199
+ assert config.hidden_size % config.num_attention_heads == 0
200
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
201
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
202
+
203
+ self.q = keras.layers.Dense(
204
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="q"
205
+ )
206
+ self.k = keras.layers.Dense(
207
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="k"
208
+ )
209
+ self.v = keras.layers.Dense(
210
+ self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="v"
211
+ )
212
+ self.o = keras.layers.Dense(
213
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="o"
214
+ )
215
+ self.dropout = keras.layers.Dropout(config.attention_probs_dropout_prob)
216
+ self.config = config
217
+
218
+ def transpose_for_scores(self, x, batch_size):
219
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
220
+ x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))
221
+
222
+ return tf.transpose(x, perm=[0, 2, 1, 3])
223
+
224
+ def call(self, hidden_states, attention_mask, head_mask, output_attentions, position_bias=None, training=False):
225
+ batch_size = shape_list(hidden_states)[0]
226
+
227
+ q = self.q(hidden_states)
228
+ k = self.k(hidden_states)
229
+ v = self.v(hidden_states)
230
+
231
+ q = self.transpose_for_scores(q, batch_size)
232
+ k = self.transpose_for_scores(k, batch_size)
233
+ v = self.transpose_for_scores(v, batch_size)
234
+
235
+ attention_scores = tf.matmul(q, k, transpose_b=True)
236
+ dk = tf.cast(shape_list(k)[-1], attention_scores.dtype)
237
+ attention_scores = attention_scores / tf.math.sqrt(dk)
238
+
239
+ # Apply relative position embedding (precomputed in MPNetEncoder) if provided.
240
+ if position_bias is not None:
241
+ attention_scores += position_bias
242
+
243
+ if attention_mask is not None:
244
+ attention_scores = attention_scores + attention_mask
245
+
246
+ attention_probs = stable_softmax(attention_scores, axis=-1)
247
+
248
+ attention_probs = self.dropout(attention_probs, training=training)
249
+
250
+ if head_mask is not None:
251
+ attention_probs = attention_probs * head_mask
252
+
253
+ c = tf.matmul(attention_probs, v)
254
+ c = tf.transpose(c, perm=[0, 2, 1, 3])
255
+ c = tf.reshape(c, (batch_size, -1, self.all_head_size))
256
+ o = self.o(c)
257
+
258
+ outputs = (o, attention_probs) if output_attentions else (o,)
259
+ return outputs
260
+
261
+ def build(self, input_shape=None):
262
+ if self.built:
263
+ return
264
+ self.built = True
265
+ if getattr(self, "q", None) is not None:
266
+ with tf.name_scope(self.q.name):
267
+ self.q.build([None, None, self.config.hidden_size])
268
+ if getattr(self, "k", None) is not None:
269
+ with tf.name_scope(self.k.name):
270
+ self.k.build([None, None, self.config.hidden_size])
271
+ if getattr(self, "v", None) is not None:
272
+ with tf.name_scope(self.v.name):
273
+ self.v.build([None, None, self.config.hidden_size])
274
+ if getattr(self, "o", None) is not None:
275
+ with tf.name_scope(self.o.name):
276
+ self.o.build([None, None, self.config.hidden_size])
277
+
278
+
279
+ class TFMPNetAttention(keras.layers.Layer):
280
+ def __init__(self, config, **kwargs):
281
+ super().__init__(**kwargs)
282
+
283
+ self.attn = TFMPNetSelfAttention(config, name="attn")
284
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
285
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
286
+ self.config = config
287
+
288
+ def prune_heads(self, heads):
289
+ raise NotImplementedError
290
+
291
+ def call(self, input_tensor, attention_mask, head_mask, output_attentions, position_bias=None, training=False):
292
+ self_outputs = self.attn(
293
+ input_tensor, attention_mask, head_mask, output_attentions, position_bias=position_bias, training=training
294
+ )
295
+ attention_output = self.LayerNorm(self.dropout(self_outputs[0]) + input_tensor)
296
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
297
+ return outputs
298
+
299
+ def build(self, input_shape=None):
300
+ if self.built:
301
+ return
302
+ self.built = True
303
+ if getattr(self, "attn", None) is not None:
304
+ with tf.name_scope(self.attn.name):
305
+ self.attn.build(None)
306
+ if getattr(self, "LayerNorm", None) is not None:
307
+ with tf.name_scope(self.LayerNorm.name):
308
+ self.LayerNorm.build([None, None, self.config.hidden_size])
309
+
310
+
311
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->MPNet
312
+ class TFMPNetIntermediate(keras.layers.Layer):
313
+ def __init__(self, config: MPNetConfig, **kwargs):
314
+ super().__init__(**kwargs)
315
+
316
+ self.dense = keras.layers.Dense(
317
+ units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
318
+ )
319
+
320
+ if isinstance(config.hidden_act, str):
321
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
322
+ else:
323
+ self.intermediate_act_fn = config.hidden_act
324
+ self.config = config
325
+
326
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
327
+ hidden_states = self.dense(inputs=hidden_states)
328
+ hidden_states = self.intermediate_act_fn(hidden_states)
329
+
330
+ return hidden_states
331
+
332
+ def build(self, input_shape=None):
333
+ if self.built:
334
+ return
335
+ self.built = True
336
+ if getattr(self, "dense", None) is not None:
337
+ with tf.name_scope(self.dense.name):
338
+ self.dense.build([None, None, self.config.hidden_size])
339
+
340
+
341
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertOutput with Bert->MPNet
342
+ class TFMPNetOutput(keras.layers.Layer):
343
+ def __init__(self, config: MPNetConfig, **kwargs):
344
+ super().__init__(**kwargs)
345
+
346
+ self.dense = keras.layers.Dense(
347
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
348
+ )
349
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
350
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
351
+ self.config = config
352
+
353
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
354
+ hidden_states = self.dense(inputs=hidden_states)
355
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
356
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
357
+
358
+ return hidden_states
359
+
360
+ def build(self, input_shape=None):
361
+ if self.built:
362
+ return
363
+ self.built = True
364
+ if getattr(self, "dense", None) is not None:
365
+ with tf.name_scope(self.dense.name):
366
+ self.dense.build([None, None, self.config.intermediate_size])
367
+ if getattr(self, "LayerNorm", None) is not None:
368
+ with tf.name_scope(self.LayerNorm.name):
369
+ self.LayerNorm.build([None, None, self.config.hidden_size])
370
+
371
+
372
+ class TFMPNetLayer(keras.layers.Layer):
373
+ def __init__(self, config, **kwargs):
374
+ super().__init__(**kwargs)
375
+
376
+ self.attention = TFMPNetAttention(config, name="attention")
377
+ self.intermediate = TFMPNetIntermediate(config, name="intermediate")
378
+ self.out = TFMPNetOutput(config, name="output")
379
+
380
+ def call(self, hidden_states, attention_mask, head_mask, output_attentions, position_bias=None, training=False):
381
+ self_attention_outputs = self.attention(
382
+ hidden_states, attention_mask, head_mask, output_attentions, position_bias=position_bias, training=training
383
+ )
384
+ attention_output = self_attention_outputs[0]
385
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
386
+
387
+ intermediate_output = self.intermediate(attention_output)
388
+ layer_output = self.out(intermediate_output, attention_output, training=training)
389
+ outputs = (layer_output,) + outputs # add attentions if we output them
390
+
391
+ return outputs
392
+
393
+ def build(self, input_shape=None):
394
+ if self.built:
395
+ return
396
+ self.built = True
397
+ if getattr(self, "attention", None) is not None:
398
+ with tf.name_scope(self.attention.name):
399
+ self.attention.build(None)
400
+ if getattr(self, "intermediate", None) is not None:
401
+ with tf.name_scope(self.intermediate.name):
402
+ self.intermediate.build(None)
403
+ if getattr(self, "out", None) is not None:
404
+ with tf.name_scope(self.out.name):
405
+ self.out.build(None)
406
+
407
+
408
+ class TFMPNetEncoder(keras.layers.Layer):
409
+ def __init__(self, config, **kwargs):
410
+ super().__init__(**kwargs)
411
+
412
+ self.config = config
413
+ self.n_heads = config.num_attention_heads
414
+ self.output_attentions = config.output_attentions
415
+ self.output_hidden_states = config.output_hidden_states
416
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
417
+ self.initializer_range = config.initializer_range
418
+
419
+ self.layer = [TFMPNetLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
420
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
421
+
422
+ def build(self, input_shape=None):
423
+ if self.built:
424
+ return
425
+ self.built = True
426
+ with tf.name_scope("relative_attention_bias"):
427
+ self.relative_attention_bias = self.add_weight(
428
+ name="embeddings",
429
+ shape=[self.relative_attention_num_buckets, self.n_heads],
430
+ initializer=get_initializer(self.initializer_range),
431
+ )
432
+ if getattr(self, "layer", None) is not None:
433
+ for layer in self.layer:
434
+ with tf.name_scope(layer.name):
435
+ layer.build(None)
436
+
437
+ def call(
438
+ self,
439
+ hidden_states,
440
+ attention_mask,
441
+ head_mask,
442
+ output_attentions,
443
+ output_hidden_states,
444
+ return_dict,
445
+ training=False,
446
+ ):
447
+ position_bias = self.compute_position_bias(hidden_states)
448
+ all_hidden_states = () if output_hidden_states else None
449
+ all_attentions = () if output_attentions else None
450
+
451
+ for i, layer_module in enumerate(self.layer):
452
+ if output_hidden_states:
453
+ all_hidden_states = all_hidden_states + (hidden_states,)
454
+
455
+ layer_outputs = layer_module(
456
+ hidden_states,
457
+ attention_mask,
458
+ head_mask[i],
459
+ output_attentions,
460
+ position_bias=position_bias,
461
+ training=training,
462
+ )
463
+ hidden_states = layer_outputs[0]
464
+
465
+ if output_attentions:
466
+ all_attentions = all_attentions + (layer_outputs[1],)
467
+
468
+ # Add last layer
469
+ if output_hidden_states:
470
+ all_hidden_states = all_hidden_states + (hidden_states,)
471
+
472
+ if not return_dict:
473
+ return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
474
+
475
+ return TFBaseModelOutput(
476
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
477
+ )
478
+
479
+ @staticmethod
480
+ def _relative_position_bucket(relative_position, num_buckets=32, max_distance=128):
481
+ ret = 0
482
+ n = -relative_position
483
+
484
+ num_buckets //= 2
485
+ ret += tf.cast(tf.math.less(n, 0), dtype=relative_position.dtype) * num_buckets
486
+ n = tf.math.abs(n)
487
+
488
+ # now n is in the range [0, inf)
489
+ max_exact = num_buckets // 2
490
+ is_small = tf.math.less(n, max_exact)
491
+
492
+ val_if_large = max_exact + tf.cast(
493
+ tf.math.log(n / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact),
494
+ dtype=relative_position.dtype,
495
+ )
496
+
497
+ val_if_large = tf.math.minimum(val_if_large, num_buckets - 1)
498
+ ret += tf.where(is_small, n, val_if_large)
499
+ return ret
500
+
501
+ def compute_position_bias(self, x, position_ids=None):
502
+ """Compute binned relative position bias"""
503
+ input_shape = shape_list(x)
504
+ qlen, klen = input_shape[1], input_shape[1]
505
+
506
+ if position_ids is not None:
507
+ context_position = position_ids[:, :, None]
508
+ memory_position = position_ids[:, None, :]
509
+ else:
510
+ context_position = tf.range(qlen)[:, None]
511
+ memory_position = tf.range(klen)[None, :]
512
+
513
+ relative_position = memory_position - context_position # shape (qlen, klen)
514
+
515
+ rp_bucket = self._relative_position_bucket(
516
+ relative_position,
517
+ num_buckets=self.relative_attention_num_buckets,
518
+ )
519
+ values = tf.gather(self.relative_attention_bias, rp_bucket) # shape (qlen, klen, num_heads)
520
+ values = tf.expand_dims(tf.transpose(values, [2, 0, 1]), axis=0) # shape (1, num_heads, qlen, klen)
521
+ return values
522
+
523
+
524
+ @keras_serializable
525
+ class TFMPNetMainLayer(keras.layers.Layer):
526
+ config_class = MPNetConfig
527
+
528
+ def __init__(self, config, **kwargs):
529
+ super().__init__(**kwargs)
530
+
531
+ self.config = config
532
+ self.num_hidden_layers = config.num_hidden_layers
533
+ self.initializer_range = config.initializer_range
534
+ self.output_attentions = config.output_attentions
535
+ self.output_hidden_states = config.output_hidden_states
536
+ self.return_dict = config.use_return_dict
537
+ self.encoder = TFMPNetEncoder(config, name="encoder")
538
+ self.pooler = TFMPNetPooler(config, name="pooler")
539
+ # The embeddings must be the last declaration in order to follow the weights order
540
+ self.embeddings = TFMPNetEmbeddings(config, name="embeddings")
541
+
542
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.get_input_embeddings
543
+ def get_input_embeddings(self) -> keras.layers.Layer:
544
+ return self.embeddings
545
+
546
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.set_input_embeddings
547
+ def set_input_embeddings(self, value: tf.Variable):
548
+ self.embeddings.weight = value
549
+ self.embeddings.vocab_size = shape_list(value)[0]
550
+
551
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer._prune_heads
552
+ def _prune_heads(self, heads_to_prune):
553
+ """
554
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
555
+ class PreTrainedModel
556
+ """
557
+ raise NotImplementedError
558
+
559
+ @unpack_inputs
560
+ def call(
561
+ self,
562
+ input_ids=None,
563
+ attention_mask=None,
564
+ position_ids=None,
565
+ head_mask=None,
566
+ inputs_embeds=None,
567
+ output_attentions=None,
568
+ output_hidden_states=None,
569
+ return_dict=None,
570
+ training=False,
571
+ ):
572
+ if input_ids is not None and inputs_embeds is not None:
573
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
574
+ elif input_ids is not None:
575
+ input_shape = shape_list(input_ids)
576
+ elif inputs_embeds is not None:
577
+ input_shape = shape_list(inputs_embeds)[:-1]
578
+ else:
579
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
580
+
581
+ if attention_mask is None:
582
+ attention_mask = tf.fill(input_shape, 1)
583
+
584
+ embedding_output = self.embeddings(
585
+ input_ids,
586
+ position_ids,
587
+ inputs_embeds,
588
+ training=training,
589
+ )
590
+
591
+ # We create a 3D attention mask from a 2D tensor mask.
592
+ # Sizes are [batch_size, 1, 1, to_seq_length]
593
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
594
+ # this attention mask is more simple than the triangular masking of causal attention
595
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
596
+ extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
597
+
598
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
599
+ # masked positions, this operation will create a tensor which is 0.0 for
600
+ # positions we want to attend and -10000.0 for masked positions.
601
+ # Since we are adding it to the raw scores before the softmax, this is
602
+ # effectively the same as removing these entirely.
603
+ extended_attention_mask = tf.cast(extended_attention_mask, embedding_output.dtype)
604
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
605
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
606
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
607
+
608
+ # Prepare head mask if needed
609
+ # 1.0 in head_mask indicate we keep the head
610
+ # attention_probs has shape bsz x n_heads x N x N
611
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
612
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
613
+ if head_mask is not None:
614
+ raise NotImplementedError
615
+ else:
616
+ head_mask = [None] * self.num_hidden_layers
617
+
618
+ encoder_outputs = self.encoder(
619
+ embedding_output,
620
+ extended_attention_mask,
621
+ head_mask,
622
+ output_attentions,
623
+ output_hidden_states,
624
+ return_dict,
625
+ training=training,
626
+ )
627
+
628
+ sequence_output = encoder_outputs[0]
629
+ pooled_output = self.pooler(sequence_output)
630
+
631
+ if not return_dict:
632
+ return (
633
+ sequence_output,
634
+ pooled_output,
635
+ ) + encoder_outputs[1:]
636
+
637
+ return TFBaseModelOutputWithPooling(
638
+ last_hidden_state=sequence_output,
639
+ pooler_output=pooled_output,
640
+ hidden_states=encoder_outputs.hidden_states,
641
+ attentions=encoder_outputs.attentions,
642
+ )
643
+
644
+ def build(self, input_shape=None):
645
+ if self.built:
646
+ return
647
+ self.built = True
648
+ if getattr(self, "encoder", None) is not None:
649
+ with tf.name_scope(self.encoder.name):
650
+ self.encoder.build(None)
651
+ if getattr(self, "pooler", None) is not None:
652
+ with tf.name_scope(self.pooler.name):
653
+ self.pooler.build(None)
654
+ if getattr(self, "embeddings", None) is not None:
655
+ with tf.name_scope(self.embeddings.name):
656
+ self.embeddings.build(None)
657
+
658
+
659
+ MPNET_START_DOCSTRING = r"""
660
+
661
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
662
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
663
+ etc.)
664
+
665
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
666
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
667
+ behavior.
668
+
669
+ <Tip>
670
+
671
+ TensorFlow models and layers in `transformers` accept two formats as input:
672
+
673
+ - having all inputs as keyword arguments (like PyTorch models), or
674
+ - having all inputs as a list, tuple or dict in the first positional argument.
675
+
676
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
677
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
678
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
679
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
680
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
681
+ positional argument:
682
+
683
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
684
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
685
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
686
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
687
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
688
+
689
+ Note that when creating models and layers with
690
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
691
+ about any of this, as you can just pass inputs like you would to any other Python function!
692
+
693
+ </Tip>
694
+
695
+ Args:
696
+ config ([`MPNetConfig`]): Model configuration class with all the parameters of the model.
697
+ Initializing with a config file does not load the weights associated with the model, only the
698
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
699
+ """
700
+
701
+ MPNET_INPUTS_DOCSTRING = r"""
702
+ Args:
703
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
704
+ Indices of input sequence tokens in the vocabulary.
705
+
706
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
707
+ [`PreTrainedTokenizer.encode`] for details.
708
+
709
+ [What are input IDs?](../glossary#input-ids)
710
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
711
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
712
+
713
+ - 1 for tokens that are **not masked**,
714
+ - 0 for tokens that are **masked**.
715
+
716
+ [What are attention masks?](../glossary#attention-mask)
717
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
718
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
719
+ config.max_position_embeddings - 1]`.
720
+
721
+ [What are position IDs?](../glossary#position-ids)
722
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
723
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
724
+
725
+ - 1 indicates the head is **not masked**,
726
+ - 0 indicates the head is **masked**.
727
+
728
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
729
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
730
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
731
+ model's internal embedding lookup matrix.
732
+ output_attentions (`bool`, *optional*):
733
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
734
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
735
+ config will be used instead.
736
+ output_hidden_states (`bool`, *optional*):
737
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
738
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
739
+ used instead.
740
+ return_dict (`bool`, *optional*):
741
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
742
+ eager mode, in graph mode the value will always be set to True.
743
+ training (`bool`, *optional*, defaults to `False`):
744
+ Whether or not to use the model in training mode (some modules like dropout modules have different
745
+ behaviors between training and evaluation).
746
+ """
747
+
748
+
749
+ @add_start_docstrings(
750
+ "The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.",
751
+ MPNET_START_DOCSTRING,
752
+ )
753
+ class TFMPNetModel(TFMPNetPreTrainedModel):
754
+ def __init__(self, config, *inputs, **kwargs):
755
+ super().__init__(config, *inputs, **kwargs)
756
+ self.mpnet = TFMPNetMainLayer(config, name="mpnet")
757
+
758
+ @unpack_inputs
759
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
760
+ @add_code_sample_docstrings(
761
+ checkpoint=_CHECKPOINT_FOR_DOC,
762
+ output_type=TFBaseModelOutput,
763
+ config_class=_CONFIG_FOR_DOC,
764
+ )
765
+ def call(
766
+ self,
767
+ input_ids: TFModelInputType | None = None,
768
+ attention_mask: Optional[Union[np.array, tf.Tensor]] = None,
769
+ position_ids: Optional[Union[np.array, tf.Tensor]] = None,
770
+ head_mask: Optional[Union[np.array, tf.Tensor]] = None,
771
+ inputs_embeds: tf.Tensor | None = None,
772
+ output_attentions: Optional[bool] = None,
773
+ output_hidden_states: Optional[bool] = None,
774
+ return_dict: Optional[bool] = None,
775
+ training: bool = False,
776
+ ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
777
+ outputs = self.mpnet(
778
+ input_ids=input_ids,
779
+ attention_mask=attention_mask,
780
+ position_ids=position_ids,
781
+ head_mask=head_mask,
782
+ inputs_embeds=inputs_embeds,
783
+ output_attentions=output_attentions,
784
+ output_hidden_states=output_hidden_states,
785
+ return_dict=return_dict,
786
+ training=training,
787
+ )
788
+ return outputs
789
+
790
+ def build(self, input_shape=None):
791
+ if self.built:
792
+ return
793
+ self.built = True
794
+ if getattr(self, "mpnet", None) is not None:
795
+ with tf.name_scope(self.mpnet.name):
796
+ self.mpnet.build(None)
797
+
798
+
799
+ class TFMPNetLMHead(keras.layers.Layer):
800
+ """MPNet head for masked and permuted language modeling"""
801
+
802
+ def __init__(self, config, input_embeddings, **kwargs):
803
+ super().__init__(**kwargs)
804
+
805
+ self.config = config
806
+ self.hidden_size = config.hidden_size
807
+ self.dense = keras.layers.Dense(
808
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
809
+ )
810
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
811
+ self.act = get_tf_activation("gelu")
812
+
813
+ # The output weights are the same as the input embeddings, but there is
814
+ # an output-only bias for each token.
815
+ self.decoder = input_embeddings
816
+
817
+ def build(self, input_shape=None):
818
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
819
+
820
+ if self.built:
821
+ return
822
+ self.built = True
823
+ if getattr(self, "dense", None) is not None:
824
+ with tf.name_scope(self.dense.name):
825
+ self.dense.build([None, None, self.config.hidden_size])
826
+ if getattr(self, "layer_norm", None) is not None:
827
+ with tf.name_scope(self.layer_norm.name):
828
+ self.layer_norm.build([None, None, self.config.hidden_size])
829
+
830
+ def get_output_embeddings(self):
831
+ return self.decoder
832
+
833
+ def set_output_embeddings(self, value):
834
+ self.decoder.weight = value
835
+ self.decoder.vocab_size = shape_list(value)[0]
836
+
837
+ def get_bias(self):
838
+ return {"bias": self.bias}
839
+
840
+ def set_bias(self, value):
841
+ self.bias = value["bias"]
842
+ self.config.vocab_size = shape_list(value["bias"])[0]
843
+
844
+ def call(self, hidden_states):
845
+ hidden_states = self.dense(hidden_states)
846
+ hidden_states = self.act(hidden_states)
847
+ hidden_states = self.layer_norm(hidden_states)
848
+
849
+ # project back to size of vocabulary with bias
850
+ seq_length = shape_list(tensor=hidden_states)[1]
851
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
852
+ hidden_states = tf.matmul(a=hidden_states, b=self.decoder.weight, transpose_b=True)
853
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
854
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
855
+
856
+ return hidden_states
857
+
858
+
859
+ @add_start_docstrings("""MPNet Model with a `language modeling` head on top.""", MPNET_START_DOCSTRING)
860
+ class TFMPNetForMaskedLM(TFMPNetPreTrainedModel, TFMaskedLanguageModelingLoss):
861
+ _keys_to_ignore_on_load_missing = [r"pooler"]
862
+
863
+ def __init__(self, config, *inputs, **kwargs):
864
+ super().__init__(config, *inputs, **kwargs)
865
+
866
+ self.mpnet = TFMPNetMainLayer(config, name="mpnet")
867
+ self.lm_head = TFMPNetLMHead(config, self.mpnet.embeddings, name="lm_head")
868
+
869
+ def get_lm_head(self):
870
+ return self.lm_head
871
+
872
+ def get_prefix_bias_name(self):
873
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
874
+ return self.name + "/" + self.lm_head.name
875
+
876
+ @unpack_inputs
877
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
878
+ @add_code_sample_docstrings(
879
+ checkpoint=_CHECKPOINT_FOR_DOC,
880
+ output_type=TFMaskedLMOutput,
881
+ config_class=_CONFIG_FOR_DOC,
882
+ )
883
+ def call(
884
+ self,
885
+ input_ids: TFModelInputType | None = None,
886
+ attention_mask: np.ndarray | tf.Tensor | None = None,
887
+ position_ids: np.ndarray | tf.Tensor | None = None,
888
+ head_mask: np.ndarray | tf.Tensor | None = None,
889
+ inputs_embeds: tf.Tensor | None = None,
890
+ output_attentions: Optional[bool] = None,
891
+ output_hidden_states: Optional[bool] = None,
892
+ return_dict: Optional[bool] = None,
893
+ labels: tf.Tensor | None = None,
894
+ training: bool = False,
895
+ ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
896
+ r"""
897
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
898
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
899
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
900
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
901
+ """
902
+ outputs = self.mpnet(
903
+ input_ids,
904
+ attention_mask=attention_mask,
905
+ position_ids=position_ids,
906
+ head_mask=head_mask,
907
+ inputs_embeds=inputs_embeds,
908
+ output_attentions=output_attentions,
909
+ output_hidden_states=output_hidden_states,
910
+ return_dict=return_dict,
911
+ training=training,
912
+ )
913
+ sequence_output = outputs[0]
914
+ prediction_scores = self.lm_head(sequence_output)
915
+
916
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
917
+
918
+ if not return_dict:
919
+ output = (prediction_scores,) + outputs[2:]
920
+ return ((loss,) + output) if loss is not None else output
921
+
922
+ return TFMaskedLMOutput(
923
+ loss=loss,
924
+ logits=prediction_scores,
925
+ hidden_states=outputs.hidden_states,
926
+ attentions=outputs.attentions,
927
+ )
928
+
929
+ def build(self, input_shape=None):
930
+ if self.built:
931
+ return
932
+ self.built = True
933
+ if getattr(self, "mpnet", None) is not None:
934
+ with tf.name_scope(self.mpnet.name):
935
+ self.mpnet.build(None)
936
+ if getattr(self, "lm_head", None) is not None:
937
+ with tf.name_scope(self.lm_head.name):
938
+ self.lm_head.build(None)
939
+
940
+
941
+ class TFMPNetClassificationHead(keras.layers.Layer):
942
+ """Head for sentence-level classification tasks."""
943
+
944
+ def __init__(self, config, **kwargs):
945
+ super().__init__(**kwargs)
946
+ self.dense = keras.layers.Dense(
947
+ config.hidden_size,
948
+ kernel_initializer=get_initializer(config.initializer_range),
949
+ activation="tanh",
950
+ name="dense",
951
+ )
952
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
953
+ self.out_proj = keras.layers.Dense(
954
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
955
+ )
956
+ self.config = config
957
+
958
+ def call(self, features, training=False):
959
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
960
+ x = self.dropout(x, training=training)
961
+ x = self.dense(x)
962
+ x = self.dropout(x, training=training)
963
+ x = self.out_proj(x)
964
+ return x
965
+
966
+ def build(self, input_shape=None):
967
+ if self.built:
968
+ return
969
+ self.built = True
970
+ if getattr(self, "dense", None) is not None:
971
+ with tf.name_scope(self.dense.name):
972
+ self.dense.build([None, None, self.config.hidden_size])
973
+ if getattr(self, "out_proj", None) is not None:
974
+ with tf.name_scope(self.out_proj.name):
975
+ self.out_proj.build([None, None, self.config.hidden_size])
976
+
977
+
978
+ @add_start_docstrings(
979
+ """
980
+ MPNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
981
+ output) e.g. for GLUE tasks.
982
+ """,
983
+ MPNET_START_DOCSTRING,
984
+ )
985
+ class TFMPNetForSequenceClassification(TFMPNetPreTrainedModel, TFSequenceClassificationLoss):
986
+ _keys_to_ignore_on_load_missing = [r"pooler"]
987
+
988
+ def __init__(self, config, *inputs, **kwargs):
989
+ super().__init__(config, *inputs, **kwargs)
990
+ self.num_labels = config.num_labels
991
+
992
+ self.mpnet = TFMPNetMainLayer(config, name="mpnet")
993
+ self.classifier = TFMPNetClassificationHead(config, name="classifier")
994
+
995
+ @unpack_inputs
996
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
997
+ @add_code_sample_docstrings(
998
+ checkpoint=_CHECKPOINT_FOR_DOC,
999
+ output_type=TFSequenceClassifierOutput,
1000
+ config_class=_CONFIG_FOR_DOC,
1001
+ )
1002
+ def call(
1003
+ self,
1004
+ input_ids: TFModelInputType | None = None,
1005
+ attention_mask: Optional[Union[np.array, tf.Tensor]] = None,
1006
+ position_ids: Optional[Union[np.array, tf.Tensor]] = None,
1007
+ head_mask: Optional[Union[np.array, tf.Tensor]] = None,
1008
+ inputs_embeds: tf.Tensor | None = None,
1009
+ output_attentions: Optional[bool] = None,
1010
+ output_hidden_states: Optional[bool] = None,
1011
+ return_dict: Optional[bool] = None,
1012
+ labels: tf.Tensor | None = None,
1013
+ training: bool = False,
1014
+ ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
1015
+ r"""
1016
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1017
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1018
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1019
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1020
+ """
1021
+ outputs = self.mpnet(
1022
+ input_ids,
1023
+ attention_mask=attention_mask,
1024
+ position_ids=position_ids,
1025
+ head_mask=head_mask,
1026
+ inputs_embeds=inputs_embeds,
1027
+ output_attentions=output_attentions,
1028
+ output_hidden_states=output_hidden_states,
1029
+ return_dict=return_dict,
1030
+ training=training,
1031
+ )
1032
+
1033
+ sequence_output = outputs[0]
1034
+ logits = self.classifier(sequence_output, training=training)
1035
+
1036
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1037
+
1038
+ if not return_dict:
1039
+ output = (logits,) + outputs[2:]
1040
+ return ((loss,) + output) if loss is not None else output
1041
+
1042
+ return TFSequenceClassifierOutput(
1043
+ loss=loss,
1044
+ logits=logits,
1045
+ hidden_states=outputs.hidden_states,
1046
+ attentions=outputs.attentions,
1047
+ )
1048
+
1049
+ def build(self, input_shape=None):
1050
+ if self.built:
1051
+ return
1052
+ self.built = True
1053
+ if getattr(self, "mpnet", None) is not None:
1054
+ with tf.name_scope(self.mpnet.name):
1055
+ self.mpnet.build(None)
1056
+ if getattr(self, "classifier", None) is not None:
1057
+ with tf.name_scope(self.classifier.name):
1058
+ self.classifier.build(None)
1059
+
1060
+
1061
+ @add_start_docstrings(
1062
+ """
1063
+ MPNet Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1064
+ softmax) e.g. for RocStories/SWAG tasks.
1065
+ """,
1066
+ MPNET_START_DOCSTRING,
1067
+ )
1068
+ class TFMPNetForMultipleChoice(TFMPNetPreTrainedModel, TFMultipleChoiceLoss):
1069
+ def __init__(self, config, *inputs, **kwargs):
1070
+ super().__init__(config, *inputs, **kwargs)
1071
+
1072
+ self.mpnet = TFMPNetMainLayer(config, name="mpnet")
1073
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
1074
+ self.classifier = keras.layers.Dense(
1075
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1076
+ )
1077
+ self.config = config
1078
+
1079
+ @unpack_inputs
1080
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1081
+ @add_code_sample_docstrings(
1082
+ checkpoint=_CHECKPOINT_FOR_DOC,
1083
+ output_type=TFMultipleChoiceModelOutput,
1084
+ config_class=_CONFIG_FOR_DOC,
1085
+ )
1086
+ def call(
1087
+ self,
1088
+ input_ids: TFModelInputType | None = None,
1089
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1090
+ position_ids: np.ndarray | tf.Tensor | None = None,
1091
+ head_mask: np.ndarray | tf.Tensor | None = None,
1092
+ inputs_embeds: tf.Tensor | None = None,
1093
+ output_attentions: Optional[bool] = None,
1094
+ output_hidden_states: Optional[bool] = None,
1095
+ return_dict: Optional[bool] = None,
1096
+ labels: tf.Tensor | None = None,
1097
+ training: bool = False,
1098
+ ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
1099
+ r"""
1100
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1101
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1102
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1103
+ """
1104
+ if input_ids is not None:
1105
+ num_choices = shape_list(input_ids)[1]
1106
+ seq_length = shape_list(input_ids)[2]
1107
+ else:
1108
+ num_choices = shape_list(inputs_embeds)[1]
1109
+ seq_length = shape_list(inputs_embeds)[2]
1110
+
1111
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1112
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1113
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
1114
+ flat_inputs_embeds = (
1115
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1116
+ if inputs_embeds is not None
1117
+ else None
1118
+ )
1119
+ outputs = self.mpnet(
1120
+ flat_input_ids,
1121
+ flat_attention_mask,
1122
+ flat_position_ids,
1123
+ head_mask,
1124
+ flat_inputs_embeds,
1125
+ output_attentions,
1126
+ output_hidden_states,
1127
+ return_dict=return_dict,
1128
+ training=training,
1129
+ )
1130
+ pooled_output = outputs[1]
1131
+ pooled_output = self.dropout(pooled_output, training=training)
1132
+ logits = self.classifier(pooled_output)
1133
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1134
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1135
+
1136
+ if not return_dict:
1137
+ output = (reshaped_logits,) + outputs[2:]
1138
+ return ((loss,) + output) if loss is not None else output
1139
+
1140
+ return TFMultipleChoiceModelOutput(
1141
+ loss=loss,
1142
+ logits=reshaped_logits,
1143
+ hidden_states=outputs.hidden_states,
1144
+ attentions=outputs.attentions,
1145
+ )
1146
+
1147
+ def build(self, input_shape=None):
1148
+ if self.built:
1149
+ return
1150
+ self.built = True
1151
+ if getattr(self, "mpnet", None) is not None:
1152
+ with tf.name_scope(self.mpnet.name):
1153
+ self.mpnet.build(None)
1154
+ if getattr(self, "classifier", None) is not None:
1155
+ with tf.name_scope(self.classifier.name):
1156
+ self.classifier.build([None, None, self.config.hidden_size])
1157
+
1158
+
1159
+ @add_start_docstrings(
1160
+ """
1161
+ MPNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1162
+ Named-Entity-Recognition (NER) tasks.
1163
+ """,
1164
+ MPNET_START_DOCSTRING,
1165
+ )
1166
+ class TFMPNetForTokenClassification(TFMPNetPreTrainedModel, TFTokenClassificationLoss):
1167
+ _keys_to_ignore_on_load_missing = [r"pooler"]
1168
+
1169
+ def __init__(self, config, *inputs, **kwargs):
1170
+ super().__init__(config, *inputs, **kwargs)
1171
+
1172
+ self.num_labels = config.num_labels
1173
+ self.mpnet = TFMPNetMainLayer(config, name="mpnet")
1174
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
1175
+ self.classifier = keras.layers.Dense(
1176
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1177
+ )
1178
+ self.config = config
1179
+
1180
+ @unpack_inputs
1181
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1182
+ @add_code_sample_docstrings(
1183
+ checkpoint=_CHECKPOINT_FOR_DOC,
1184
+ output_type=TFTokenClassifierOutput,
1185
+ config_class=_CONFIG_FOR_DOC,
1186
+ )
1187
+ def call(
1188
+ self,
1189
+ input_ids: TFModelInputType | None = None,
1190
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1191
+ position_ids: np.ndarray | tf.Tensor | None = None,
1192
+ head_mask: np.ndarray | tf.Tensor | None = None,
1193
+ inputs_embeds: tf.Tensor | None = None,
1194
+ output_attentions: Optional[bool] = None,
1195
+ output_hidden_states: Optional[bool] = None,
1196
+ return_dict: Optional[bool] = None,
1197
+ labels: tf.Tensor | None = None,
1198
+ training: bool = False,
1199
+ ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
1200
+ r"""
1201
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1202
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1203
+ """
1204
+ outputs = self.mpnet(
1205
+ input_ids=input_ids,
1206
+ attention_mask=attention_mask,
1207
+ position_ids=position_ids,
1208
+ head_mask=head_mask,
1209
+ inputs_embeds=inputs_embeds,
1210
+ output_attentions=output_attentions,
1211
+ output_hidden_states=output_hidden_states,
1212
+ return_dict=return_dict,
1213
+ training=training,
1214
+ )
1215
+ sequence_output = outputs[0]
1216
+
1217
+ sequence_output = self.dropout(sequence_output, training=training)
1218
+ logits = self.classifier(sequence_output)
1219
+
1220
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1221
+
1222
+ if not return_dict:
1223
+ output = (logits,) + outputs[1:]
1224
+ return ((loss,) + output) if loss is not None else output
1225
+
1226
+ return TFTokenClassifierOutput(
1227
+ loss=loss,
1228
+ logits=logits,
1229
+ hidden_states=outputs.hidden_states,
1230
+ attentions=outputs.attentions,
1231
+ )
1232
+
1233
+ def build(self, input_shape=None):
1234
+ if self.built:
1235
+ return
1236
+ self.built = True
1237
+ if getattr(self, "mpnet", None) is not None:
1238
+ with tf.name_scope(self.mpnet.name):
1239
+ self.mpnet.build(None)
1240
+ if getattr(self, "classifier", None) is not None:
1241
+ with tf.name_scope(self.classifier.name):
1242
+ self.classifier.build([None, None, self.config.hidden_size])
1243
+
1244
+
1245
+ @add_start_docstrings(
1246
+ """
1247
+ MPNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1248
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1249
+ """,
1250
+ MPNET_START_DOCSTRING,
1251
+ )
1252
+ class TFMPNetForQuestionAnswering(TFMPNetPreTrainedModel, TFQuestionAnsweringLoss):
1253
+ _keys_to_ignore_on_load_missing = [r"pooler"]
1254
+
1255
+ def __init__(self, config, *inputs, **kwargs):
1256
+ super().__init__(config, *inputs, **kwargs)
1257
+ self.num_labels = config.num_labels
1258
+
1259
+ self.mpnet = TFMPNetMainLayer(config, name="mpnet")
1260
+ self.qa_outputs = keras.layers.Dense(
1261
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1262
+ )
1263
+ self.config = config
1264
+
1265
+ @unpack_inputs
1266
+ @add_start_docstrings_to_model_forward(MPNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1267
+ @add_code_sample_docstrings(
1268
+ checkpoint=_CHECKPOINT_FOR_DOC,
1269
+ output_type=TFQuestionAnsweringModelOutput,
1270
+ config_class=_CONFIG_FOR_DOC,
1271
+ )
1272
+ def call(
1273
+ self,
1274
+ input_ids: TFModelInputType | None = None,
1275
+ attention_mask: Optional[Union[np.array, tf.Tensor]] = None,
1276
+ position_ids: Optional[Union[np.array, tf.Tensor]] = None,
1277
+ head_mask: Optional[Union[np.array, tf.Tensor]] = None,
1278
+ inputs_embeds: tf.Tensor | None = None,
1279
+ output_attentions: Optional[bool] = None,
1280
+ output_hidden_states: Optional[bool] = None,
1281
+ return_dict: Optional[bool] = None,
1282
+ start_positions: tf.Tensor | None = None,
1283
+ end_positions: tf.Tensor | None = None,
1284
+ training: bool = False,
1285
+ **kwargs,
1286
+ ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
1287
+ r"""
1288
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1289
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1290
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1291
+ are not taken into account for computing the loss.
1292
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1293
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1294
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1295
+ are not taken into account for computing the loss.
1296
+ """
1297
+ outputs = self.mpnet(
1298
+ input_ids,
1299
+ attention_mask=attention_mask,
1300
+ position_ids=position_ids,
1301
+ head_mask=head_mask,
1302
+ inputs_embeds=inputs_embeds,
1303
+ output_attentions=output_attentions,
1304
+ output_hidden_states=output_hidden_states,
1305
+ return_dict=return_dict,
1306
+ training=training,
1307
+ )
1308
+ sequence_output = outputs[0]
1309
+
1310
+ logits = self.qa_outputs(sequence_output)
1311
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1312
+ start_logits = tf.squeeze(start_logits, axis=-1)
1313
+ end_logits = tf.squeeze(end_logits, axis=-1)
1314
+ loss = None
1315
+
1316
+ if start_positions is not None and end_positions is not None:
1317
+ labels = {"start_position": start_positions, "end_position": end_positions}
1318
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1319
+
1320
+ if not return_dict:
1321
+ output = (start_logits, end_logits) + outputs[2:]
1322
+ return ((loss,) + output) if loss is not None else output
1323
+
1324
+ return TFQuestionAnsweringModelOutput(
1325
+ loss=loss,
1326
+ start_logits=start_logits,
1327
+ end_logits=end_logits,
1328
+ hidden_states=outputs.hidden_states,
1329
+ attentions=outputs.attentions,
1330
+ )
1331
+
1332
+ def build(self, input_shape=None):
1333
+ if self.built:
1334
+ return
1335
+ self.built = True
1336
+ if getattr(self, "mpnet", None) is not None:
1337
+ with tf.name_scope(self.mpnet.name):
1338
+ self.mpnet.build(None)
1339
+ if getattr(self, "qa_outputs", None) is not None:
1340
+ with tf.name_scope(self.qa_outputs.name):
1341
+ self.qa_outputs.build([None, None, self.config.hidden_size])
1342
+
1343
+
1344
+ __all__ = [
1345
+ "TFMPNetEmbeddings",
1346
+ "TFMPNetForMaskedLM",
1347
+ "TFMPNetForMultipleChoice",
1348
+ "TFMPNetForQuestionAnswering",
1349
+ "TFMPNetForSequenceClassification",
1350
+ "TFMPNetForTokenClassification",
1351
+ "TFMPNetMainLayer",
1352
+ "TFMPNetModel",
1353
+ "TFMPNetPreTrainedModel",
1354
+ ]
janus/lib/python3.10/site-packages/transformers/models/mpnet/tokenization_mpnet.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
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
+ """Tokenization classes for MPNet."""
17
+
18
+ import collections
19
+ import os
20
+ import unicodedata
21
+ from typing import List, Optional, Tuple
22
+
23
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
30
+
31
+
32
+ def load_vocab(vocab_file):
33
+ """Loads a vocabulary file into a dictionary."""
34
+ vocab = collections.OrderedDict()
35
+ with open(vocab_file, "r", encoding="utf-8") as reader:
36
+ tokens = reader.readlines()
37
+ for index, token in enumerate(tokens):
38
+ token = token.rstrip("\n")
39
+ vocab[token] = index
40
+ return vocab
41
+
42
+
43
+ def whitespace_tokenize(text):
44
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
45
+ text = text.strip()
46
+ if not text:
47
+ return []
48
+ tokens = text.split()
49
+ return tokens
50
+
51
+
52
+ class MPNetTokenizer(PreTrainedTokenizer):
53
+ """
54
+
55
+ This tokenizer inherits from [`BertTokenizer`] which contains most of the methods. Users should refer to the
56
+ superclass for more information regarding methods.
57
+
58
+ Args:
59
+ vocab_file (`str`):
60
+ Path to the vocabulary file.
61
+ do_lower_case (`bool`, *optional*, defaults to `True`):
62
+ Whether or not to lowercase the input when tokenizing.
63
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
64
+ Whether or not to do basic tokenization before WordPiece.
65
+ never_split (`Iterable`, *optional*):
66
+ Collection of tokens which will never be split during tokenization. Only has an effect when
67
+ `do_basic_tokenize=True`
68
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
69
+ The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
70
+
71
+ <Tip>
72
+
73
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
74
+ sequence. The token used is the `cls_token`.
75
+
76
+ </Tip>
77
+
78
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
79
+ The end of sequence token.
80
+
81
+ <Tip>
82
+
83
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
84
+ The token used is the `sep_token`.
85
+
86
+ </Tip>
87
+
88
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
89
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
90
+ sequence classification or for a text and a question for question answering. It is also used as the last
91
+ token of a sequence built with special tokens.
92
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
93
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
94
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
95
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
96
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
97
+ token instead.
98
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
99
+ The token used for padding, for example when batching sequences of different lengths.
100
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
101
+ The token used for masking values. This is the token used when training this model with masked language
102
+ modeling. This is the token which the model will try to predict.
103
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
104
+ Whether or not to tokenize Chinese characters.
105
+
106
+ This should likely be deactivated for Japanese (see this
107
+ [issue](https://github.com/huggingface/transformers/issues/328)).
108
+ strip_accents (`bool`, *optional*):
109
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
110
+ value for `lowercase` (as in the original BERT).
111
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
112
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
113
+ extra spaces.
114
+ """
115
+
116
+ vocab_files_names = VOCAB_FILES_NAMES
117
+ model_input_names = ["input_ids", "attention_mask"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_file,
122
+ do_lower_case=True,
123
+ do_basic_tokenize=True,
124
+ never_split=None,
125
+ bos_token="<s>",
126
+ eos_token="</s>",
127
+ sep_token="</s>",
128
+ cls_token="<s>",
129
+ unk_token="[UNK]",
130
+ pad_token="<pad>",
131
+ mask_token="<mask>",
132
+ tokenize_chinese_chars=True,
133
+ strip_accents=None,
134
+ clean_up_tokenization_spaces=True,
135
+ **kwargs,
136
+ ):
137
+ bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
138
+ eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
139
+ sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
140
+ cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
141
+ unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
142
+ pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
143
+
144
+ # Mask token behave like a normal word, i.e. include the space before it
145
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
146
+
147
+ if not os.path.isfile(vocab_file):
148
+ raise ValueError(
149
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
150
+ " model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
151
+ )
152
+ self.vocab = load_vocab(vocab_file)
153
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
154
+ self.do_basic_tokenize = do_basic_tokenize
155
+ if do_basic_tokenize:
156
+ self.basic_tokenizer = BasicTokenizer(
157
+ do_lower_case=do_lower_case,
158
+ never_split=never_split,
159
+ tokenize_chinese_chars=tokenize_chinese_chars,
160
+ strip_accents=strip_accents,
161
+ )
162
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
163
+
164
+ super().__init__(
165
+ do_lower_case=do_lower_case,
166
+ do_basic_tokenize=do_basic_tokenize,
167
+ never_split=never_split,
168
+ bos_token=bos_token,
169
+ eos_token=eos_token,
170
+ unk_token=unk_token,
171
+ sep_token=sep_token,
172
+ cls_token=cls_token,
173
+ pad_token=pad_token,
174
+ mask_token=mask_token,
175
+ tokenize_chinese_chars=tokenize_chinese_chars,
176
+ strip_accents=strip_accents,
177
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
178
+ **kwargs,
179
+ )
180
+
181
+ @property
182
+ def do_lower_case(self):
183
+ return self.basic_tokenizer.do_lower_case
184
+
185
+ @property
186
+ def vocab_size(self):
187
+ return len(self.vocab)
188
+
189
+ def get_vocab(self):
190
+ # "<mask>" is part of the vocab, but was wrongfully added at a wrong index in the fast saved version
191
+ vocab = self.added_tokens_encoder.copy()
192
+ vocab.update(self.vocab)
193
+ return vocab
194
+
195
+ def _tokenize(self, text):
196
+ split_tokens = []
197
+ if self.do_basic_tokenize:
198
+ for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
199
+ # If the token is part of the never_split set
200
+ if token in self.basic_tokenizer.never_split:
201
+ split_tokens.append(token)
202
+ else:
203
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
204
+ else:
205
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
206
+ return split_tokens
207
+
208
+ def _convert_token_to_id(self, token):
209
+ """Converts a token (str) in an id using the vocab."""
210
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
211
+
212
+ def _convert_id_to_token(self, index):
213
+ """Converts an index (integer) in a token (str) using the vocab."""
214
+ return self.ids_to_tokens.get(index, self.unk_token)
215
+
216
+ def convert_tokens_to_string(self, tokens):
217
+ """Converts a sequence of tokens (string) in a single string."""
218
+ out_string = " ".join(tokens).replace(" ##", "").strip()
219
+ return out_string
220
+
221
+ def build_inputs_with_special_tokens(
222
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
223
+ ) -> List[int]:
224
+ """
225
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
226
+ adding special tokens. A MPNet sequence has the following format:
227
+
228
+ - single sequence: `<s> X </s>`
229
+ - pair of sequences: `<s> A </s></s> B </s>`
230
+
231
+ Args:
232
+ token_ids_0 (`List[int]`):
233
+ List of IDs to which the special tokens will be added
234
+ token_ids_1 (`List[int]`, *optional*):
235
+ Optional second list of IDs for sequence pairs.
236
+
237
+ Returns:
238
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
239
+ """
240
+ if token_ids_1 is None:
241
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
242
+ cls = [self.cls_token_id]
243
+ sep = [self.sep_token_id]
244
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
245
+
246
+ def get_special_tokens_mask(
247
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
248
+ ) -> List[int]:
249
+ """
250
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
251
+ special tokens using the tokenizer `prepare_for_model` methods.
252
+
253
+ Args:
254
+ token_ids_0 (`List[int]`):
255
+ List of ids.
256
+ token_ids_1 (`List[int]`, *optional*):
257
+ Optional second list of IDs for sequence pairs.
258
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
259
+ Set to True if the token list is already formatted with special tokens for the model
260
+
261
+ Returns:
262
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
263
+ """
264
+ if already_has_special_tokens:
265
+ return super().get_special_tokens_mask(
266
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
267
+ )
268
+
269
+ if token_ids_1 is None:
270
+ return [1] + ([0] * len(token_ids_0)) + [1]
271
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
272
+
273
+ def create_token_type_ids_from_sequences(
274
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
275
+ ) -> List[int]:
276
+ """
277
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not
278
+ make use of token type ids, therefore a list of zeros is returned.
279
+
280
+ Args:
281
+ token_ids_0 (`List[int]`):
282
+ List of ids.
283
+ token_ids_1 (`List[int]`, *optional*):
284
+ Optional second list of IDs for sequence pairs.
285
+
286
+ Returns:
287
+ `List[int]`: List of zeros.
288
+ """
289
+ sep = [self.sep_token_id]
290
+ cls = [self.cls_token_id]
291
+
292
+ if token_ids_1 is None:
293
+ return len(cls + token_ids_0 + sep) * [0]
294
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
295
+
296
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
297
+ index = 0
298
+ if os.path.isdir(save_directory):
299
+ vocab_file = os.path.join(
300
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
301
+ )
302
+ else:
303
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
304
+ with open(vocab_file, "w", encoding="utf-8") as writer:
305
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
306
+ if index != token_index:
307
+ logger.warning(
308
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
309
+ " Please check that the vocabulary is not corrupted!"
310
+ )
311
+ index = token_index
312
+ writer.write(token + "\n")
313
+ index += 1
314
+ return (vocab_file,)
315
+
316
+
317
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
318
+ class BasicTokenizer:
319
+ """
320
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
321
+
322
+ Args:
323
+ do_lower_case (`bool`, *optional*, defaults to `True`):
324
+ Whether or not to lowercase the input when tokenizing.
325
+ never_split (`Iterable`, *optional*):
326
+ Collection of tokens which will never be split during tokenization. Only has an effect when
327
+ `do_basic_tokenize=True`
328
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
329
+ Whether or not to tokenize Chinese characters.
330
+
331
+ This should likely be deactivated for Japanese (see this
332
+ [issue](https://github.com/huggingface/transformers/issues/328)).
333
+ strip_accents (`bool`, *optional*):
334
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
335
+ value for `lowercase` (as in the original BERT).
336
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
337
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
338
+ the full context of the words, such as contractions.
339
+ """
340
+
341
+ def __init__(
342
+ self,
343
+ do_lower_case=True,
344
+ never_split=None,
345
+ tokenize_chinese_chars=True,
346
+ strip_accents=None,
347
+ do_split_on_punc=True,
348
+ ):
349
+ if never_split is None:
350
+ never_split = []
351
+ self.do_lower_case = do_lower_case
352
+ self.never_split = set(never_split)
353
+ self.tokenize_chinese_chars = tokenize_chinese_chars
354
+ self.strip_accents = strip_accents
355
+ self.do_split_on_punc = do_split_on_punc
356
+
357
+ def tokenize(self, text, never_split=None):
358
+ """
359
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
360
+
361
+ Args:
362
+ never_split (`List[str]`, *optional*)
363
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
364
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
365
+ """
366
+ # union() returns a new set by concatenating the two sets.
367
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
368
+ text = self._clean_text(text)
369
+
370
+ # This was added on November 1st, 2018 for the multilingual and Chinese
371
+ # models. This is also applied to the English models now, but it doesn't
372
+ # matter since the English models were not trained on any Chinese data
373
+ # and generally don't have any Chinese data in them (there are Chinese
374
+ # characters in the vocabulary because Wikipedia does have some Chinese
375
+ # words in the English Wikipedia.).
376
+ if self.tokenize_chinese_chars:
377
+ text = self._tokenize_chinese_chars(text)
378
+ # prevents treating the same character with different unicode codepoints as different characters
379
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
380
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
381
+ split_tokens = []
382
+ for token in orig_tokens:
383
+ if token not in never_split:
384
+ if self.do_lower_case:
385
+ token = token.lower()
386
+ if self.strip_accents is not False:
387
+ token = self._run_strip_accents(token)
388
+ elif self.strip_accents:
389
+ token = self._run_strip_accents(token)
390
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
391
+
392
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
393
+ return output_tokens
394
+
395
+ def _run_strip_accents(self, text):
396
+ """Strips accents from a piece of text."""
397
+ text = unicodedata.normalize("NFD", text)
398
+ output = []
399
+ for char in text:
400
+ cat = unicodedata.category(char)
401
+ if cat == "Mn":
402
+ continue
403
+ output.append(char)
404
+ return "".join(output)
405
+
406
+ def _run_split_on_punc(self, text, never_split=None):
407
+ """Splits punctuation on a piece of text."""
408
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
409
+ return [text]
410
+ chars = list(text)
411
+ i = 0
412
+ start_new_word = True
413
+ output = []
414
+ while i < len(chars):
415
+ char = chars[i]
416
+ if _is_punctuation(char):
417
+ output.append([char])
418
+ start_new_word = True
419
+ else:
420
+ if start_new_word:
421
+ output.append([])
422
+ start_new_word = False
423
+ output[-1].append(char)
424
+ i += 1
425
+
426
+ return ["".join(x) for x in output]
427
+
428
+ def _tokenize_chinese_chars(self, text):
429
+ """Adds whitespace around any CJK character."""
430
+ output = []
431
+ for char in text:
432
+ cp = ord(char)
433
+ if self._is_chinese_char(cp):
434
+ output.append(" ")
435
+ output.append(char)
436
+ output.append(" ")
437
+ else:
438
+ output.append(char)
439
+ return "".join(output)
440
+
441
+ def _is_chinese_char(self, cp):
442
+ """Checks whether CP is the codepoint of a CJK character."""
443
+ # This defines a "chinese character" as anything in the CJK Unicode block:
444
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
445
+ #
446
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
447
+ # despite its name. The modern Korean Hangul alphabet is a different block,
448
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
449
+ # space-separated words, so they are not treated specially and handled
450
+ # like the all of the other languages.
451
+ if (
452
+ (cp >= 0x4E00 and cp <= 0x9FFF)
453
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
454
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
455
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
456
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
457
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
458
+ or (cp >= 0xF900 and cp <= 0xFAFF)
459
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
460
+ ): #
461
+ return True
462
+
463
+ return False
464
+
465
+ def _clean_text(self, text):
466
+ """Performs invalid character removal and whitespace cleanup on text."""
467
+ output = []
468
+ for char in text:
469
+ cp = ord(char)
470
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
471
+ continue
472
+ if _is_whitespace(char):
473
+ output.append(" ")
474
+ else:
475
+ output.append(char)
476
+ return "".join(output)
477
+
478
+
479
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
480
+ class WordpieceTokenizer:
481
+ """Runs WordPiece tokenization."""
482
+
483
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
484
+ self.vocab = vocab
485
+ self.unk_token = unk_token
486
+ self.max_input_chars_per_word = max_input_chars_per_word
487
+
488
+ def tokenize(self, text):
489
+ """
490
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
491
+ tokenization using the given vocabulary.
492
+
493
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
494
+
495
+ Args:
496
+ text: A single token or whitespace separated tokens. This should have
497
+ already been passed through *BasicTokenizer*.
498
+
499
+ Returns:
500
+ A list of wordpiece tokens.
501
+ """
502
+
503
+ output_tokens = []
504
+ for token in whitespace_tokenize(text):
505
+ chars = list(token)
506
+ if len(chars) > self.max_input_chars_per_word:
507
+ output_tokens.append(self.unk_token)
508
+ continue
509
+
510
+ is_bad = False
511
+ start = 0
512
+ sub_tokens = []
513
+ while start < len(chars):
514
+ end = len(chars)
515
+ cur_substr = None
516
+ while start < end:
517
+ substr = "".join(chars[start:end])
518
+ if start > 0:
519
+ substr = "##" + substr
520
+ if substr in self.vocab:
521
+ cur_substr = substr
522
+ break
523
+ end -= 1
524
+ if cur_substr is None:
525
+ is_bad = True
526
+ break
527
+ sub_tokens.append(cur_substr)
528
+ start = end
529
+
530
+ if is_bad:
531
+ output_tokens.append(self.unk_token)
532
+ else:
533
+ output_tokens.extend(sub_tokens)
534
+ return output_tokens
535
+
536
+
537
+ __all__ = ["MPNetTokenizer"]
janus/lib/python3.10/site-packages/transformers/models/mpnet/tokenization_mpnet_fast.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team, Microsoft Corporation.
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
+ """Fast Tokenization classes for MPNet."""
17
+
18
+ import json
19
+ from typing import List, Optional, Tuple
20
+
21
+ from tokenizers import normalizers
22
+
23
+ from ...tokenization_utils import AddedToken
24
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
25
+ from ...utils import logging
26
+ from .tokenization_mpnet import MPNetTokenizer
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
32
+
33
+
34
+ class MPNetTokenizerFast(PreTrainedTokenizerFast):
35
+ r"""
36
+ Construct a "fast" MPNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
37
+
38
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
39
+ refer to this superclass for more information regarding those methods.
40
+
41
+ Args:
42
+ vocab_file (`str`):
43
+ File containing the vocabulary.
44
+ do_lower_case (`bool`, *optional*, defaults to `True`):
45
+ Whether or not to lowercase the input when tokenizing.
46
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
47
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
48
+
49
+ <Tip>
50
+
51
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
52
+ sequence. The token used is the `cls_token`.
53
+
54
+ </Tip>
55
+
56
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
57
+ The end of sequence token.
58
+
59
+ <Tip>
60
+
61
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
62
+ The token used is the `sep_token`.
63
+
64
+ </Tip>
65
+
66
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
67
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
68
+ sequence classification or for a text and a question for question answering. It is also used as the last
69
+ token of a sequence built with special tokens.
70
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
71
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
72
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
73
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
74
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
75
+ token instead.
76
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
77
+ The token used for padding, for example when batching sequences of different lengths.
78
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
79
+ The token used for masking values. This is the token used when training this model with masked language
80
+ modeling. This is the token which the model will try to predict.
81
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
82
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
83
+ issue](https://github.com/huggingface/transformers/issues/328)).
84
+ strip_accents (`bool`, *optional*):
85
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
86
+ value for `lowercase` (as in the original BERT).
87
+ """
88
+
89
+ vocab_files_names = VOCAB_FILES_NAMES
90
+ slow_tokenizer_class = MPNetTokenizer
91
+ model_input_names = ["input_ids", "attention_mask"]
92
+
93
+ def __init__(
94
+ self,
95
+ vocab_file=None,
96
+ tokenizer_file=None,
97
+ do_lower_case=True,
98
+ bos_token="<s>",
99
+ eos_token="</s>",
100
+ sep_token="</s>",
101
+ cls_token="<s>",
102
+ unk_token="[UNK]",
103
+ pad_token="<pad>",
104
+ mask_token="<mask>",
105
+ tokenize_chinese_chars=True,
106
+ strip_accents=None,
107
+ **kwargs,
108
+ ):
109
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
110
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
111
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
112
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
113
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
114
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
115
+
116
+ # Mask token behave like a normal word, i.e. include the space before it
117
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
118
+
119
+ super().__init__(
120
+ vocab_file,
121
+ tokenizer_file=tokenizer_file,
122
+ do_lower_case=do_lower_case,
123
+ bos_token=bos_token,
124
+ eos_token=eos_token,
125
+ sep_token=sep_token,
126
+ cls_token=cls_token,
127
+ unk_token=unk_token,
128
+ pad_token=pad_token,
129
+ mask_token=mask_token,
130
+ tokenize_chinese_chars=tokenize_chinese_chars,
131
+ strip_accents=strip_accents,
132
+ **kwargs,
133
+ )
134
+
135
+ pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
136
+ if (
137
+ pre_tok_state.get("lowercase", do_lower_case) != do_lower_case
138
+ or pre_tok_state.get("strip_accents", strip_accents) != strip_accents
139
+ ):
140
+ pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))
141
+ pre_tok_state["lowercase"] = do_lower_case
142
+ pre_tok_state["strip_accents"] = strip_accents
143
+ self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)
144
+
145
+ self.do_lower_case = do_lower_case
146
+
147
+ @property
148
+ def mask_token(self) -> str:
149
+ """
150
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
151
+ having been set.
152
+
153
+ MPNet tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
154
+ comprise the space before the *<mask>*.
155
+ """
156
+ if self._mask_token is None:
157
+ if self.verbose:
158
+ logger.error("Using mask_token, but it is not set yet.")
159
+ return None
160
+ return str(self._mask_token)
161
+
162
+ @mask_token.setter
163
+ def mask_token(self, value):
164
+ """
165
+ Overriding the default behavior of the mask token to have it eat the space before it.
166
+
167
+ This is needed to preserve backward compatibility with all the previously used models based on MPNet.
168
+ """
169
+ # Mask token behave like a normal word, i.e. include the space before it
170
+ # So we set lstrip to True
171
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
172
+ self._mask_token = value
173
+
174
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
175
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
176
+ if token_ids_1 is None:
177
+ return output
178
+
179
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
180
+
181
+ def create_token_type_ids_from_sequences(
182
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
183
+ ) -> List[int]:
184
+ """
185
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not
186
+ make use of token type ids, therefore a list of zeros is returned
187
+
188
+ Args:
189
+ token_ids_0 (`List[int]`):
190
+ List of ids.
191
+ token_ids_1 (`List[int]`, *optional*):
192
+ Optional second list of IDs for sequence pairs
193
+
194
+ Returns:
195
+ `List[int]`: List of zeros.
196
+ """
197
+ sep = [self.sep_token_id]
198
+ cls = [self.cls_token_id]
199
+
200
+ if token_ids_1 is None:
201
+ return len(cls + token_ids_0 + sep) * [0]
202
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
203
+
204
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
205
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
206
+ return tuple(files)
207
+
208
+
209
+ __all__ = ["MPNetTokenizerFast"]
janus/lib/python3.10/site-packages/transformers/models/nllb/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (539 Bytes). View file