ZTWHHH commited on
Commit
87fb89a
·
verified ·
1 Parent(s): 6e78224

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. .gitattributes +2 -0
  2. evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/__init__.py +142 -0
  3. evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-310.pyc +0 -0
  4. evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/__pycache__/modeling_tf_camembert.cpython-310.pyc +0 -0
  5. evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/configuration_camembert.py +162 -0
  6. evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/modeling_camembert.py +1574 -0
  7. evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/modeling_tf_camembert.py +1793 -0
  8. evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert.py +330 -0
  9. evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__init__.py +120 -0
  10. evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__pycache__/configuration_layoutlm.cpython-310.pyc +0 -0
  11. evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__pycache__/modeling_tf_layoutlm.cpython-310.pyc +0 -0
  12. evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__pycache__/tokenization_layoutlm_fast.cpython-310.pyc +0 -0
  13. evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/configuration_layoutlm.py +204 -0
  14. evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/tokenization_layoutlm_fast.py +205 -0
  15. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__init__.py +135 -0
  16. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/__init__.cpython-310.pyc +0 -0
  17. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/configuration_longformer.cpython-310.pyc +0 -0
  18. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/convert_longformer_original_pytorch_lightning_to_pytorch.cpython-310.pyc +0 -0
  19. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/modeling_longformer.cpython-310.pyc +0 -0
  20. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/modeling_tf_longformer.cpython-310.pyc +0 -0
  21. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/tokenization_longformer.cpython-310.pyc +0 -0
  22. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/configuration_longformer.py +214 -0
  23. evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/tokenization_longformer_fast.py +329 -0
  24. evalkit_tf437/lib/python3.10/site-packages/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py +83 -0
  25. evalkit_tf437/lib/python3.10/site-packages/transformers/models/mbart50/__init__.py +58 -0
  26. evalkit_tf437/lib/python3.10/site-packages/transformers/models/mbart50/__pycache__/__init__.cpython-310.pyc +0 -0
  27. evalkit_tf437/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/__init__.cpython-310.pyc +0 -0
  28. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__init__.py +121 -0
  29. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__pycache__/__init__.cpython-310.pyc +0 -0
  30. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__pycache__/feature_extraction_vit.cpython-310.pyc +0 -0
  31. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__pycache__/modeling_flax_vit.cpython-310.pyc +0 -0
  32. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/configuration_vit.py +143 -0
  33. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/convert_dino_to_pytorch.py +219 -0
  34. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/convert_vit_timm_to_pytorch.py +255 -0
  35. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/image_processing_vit.py +267 -0
  36. evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/modeling_vit.py +841 -0
  37. falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/INSTALLER +1 -0
  38. falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/RECORD +32 -0
  39. falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/REQUESTED +0 -0
  40. falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/WHEEL +5 -0
  41. falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt +27 -0
  42. falcon/lib/python3.10/site-packages/dateutil/__init__.py +24 -0
  43. falcon/lib/python3.10/site-packages/dateutil/__pycache__/relativedelta.cpython-310.pyc +0 -0
  44. falcon/lib/python3.10/site-packages/dateutil/__pycache__/tzwin.cpython-310.pyc +0 -0
  45. falcon/lib/python3.10/site-packages/dateutil/__pycache__/utils.cpython-310.pyc +0 -0
  46. falcon/lib/python3.10/site-packages/dateutil/_common.py +43 -0
  47. falcon/lib/python3.10/site-packages/dateutil/_version.py +4 -0
  48. falcon/lib/python3.10/site-packages/dateutil/easter.py +89 -0
  49. falcon/lib/python3.10/site-packages/dateutil/parser/__init__.py +61 -0
  50. falcon/lib/python3.10/site-packages/dateutil/parser/__pycache__/_parser.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -547,3 +547,5 @@ falcon/lib/python3.10/site-packages/sympy/core/__pycache__/numbers.cpython-310.p
547
  falcon/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
548
  falcon/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
549
  falcon/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_latex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
547
  falcon/lib/python3.10/site-packages/sympy/core/__pycache__/function.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
548
  falcon/lib/python3.10/site-packages/sympy/core/__pycache__/expr.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
549
  falcon/lib/python3.10/site-packages/sympy/printing/tests/__pycache__/test_latex.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
550
+ falcon/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solveset.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
551
+ falcon/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/__init__.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_sentencepiece_available,
21
+ is_tf_available,
22
+ is_tokenizers_available,
23
+ is_torch_available,
24
+ )
25
+
26
+
27
+ _import_structure = {
28
+ "configuration_camembert": ["CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CamembertConfig", "CamembertOnnxConfig"],
29
+ }
30
+
31
+ try:
32
+ if not is_sentencepiece_available():
33
+ raise OptionalDependencyNotAvailable()
34
+ except OptionalDependencyNotAvailable:
35
+ pass
36
+ else:
37
+ _import_structure["tokenization_camembert"] = ["CamembertTokenizer"]
38
+
39
+ try:
40
+ if not is_tokenizers_available():
41
+ raise OptionalDependencyNotAvailable()
42
+ except OptionalDependencyNotAvailable:
43
+ pass
44
+ else:
45
+ _import_structure["tokenization_camembert_fast"] = ["CamembertTokenizerFast"]
46
+
47
+ try:
48
+ if not is_torch_available():
49
+ raise OptionalDependencyNotAvailable()
50
+ except OptionalDependencyNotAvailable:
51
+ pass
52
+ else:
53
+ _import_structure["modeling_camembert"] = [
54
+ "CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
55
+ "CamembertForCausalLM",
56
+ "CamembertForMaskedLM",
57
+ "CamembertForMultipleChoice",
58
+ "CamembertForQuestionAnswering",
59
+ "CamembertForSequenceClassification",
60
+ "CamembertForTokenClassification",
61
+ "CamembertModel",
62
+ "CamembertPreTrainedModel",
63
+ ]
64
+
65
+ try:
66
+ if not is_tf_available():
67
+ raise OptionalDependencyNotAvailable()
68
+ except OptionalDependencyNotAvailable:
69
+ pass
70
+ else:
71
+ _import_structure["modeling_tf_camembert"] = [
72
+ "TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
73
+ "TFCamembertForCausalLM",
74
+ "TFCamembertForMaskedLM",
75
+ "TFCamembertForMultipleChoice",
76
+ "TFCamembertForQuestionAnswering",
77
+ "TFCamembertForSequenceClassification",
78
+ "TFCamembertForTokenClassification",
79
+ "TFCamembertModel",
80
+ "TFCamembertPreTrainedModel",
81
+ ]
82
+
83
+
84
+ if TYPE_CHECKING:
85
+ from .configuration_camembert import CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CamembertConfig, CamembertOnnxConfig
86
+
87
+ try:
88
+ if not is_sentencepiece_available():
89
+ raise OptionalDependencyNotAvailable()
90
+ except OptionalDependencyNotAvailable:
91
+ pass
92
+ else:
93
+ from .tokenization_camembert import CamembertTokenizer
94
+
95
+ try:
96
+ if not is_tokenizers_available():
97
+ raise OptionalDependencyNotAvailable()
98
+ except OptionalDependencyNotAvailable:
99
+ pass
100
+ else:
101
+ from .tokenization_camembert_fast import CamembertTokenizerFast
102
+
103
+ try:
104
+ if not is_torch_available():
105
+ raise OptionalDependencyNotAvailable()
106
+ except OptionalDependencyNotAvailable:
107
+ pass
108
+ else:
109
+ from .modeling_camembert import (
110
+ CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
111
+ CamembertForCausalLM,
112
+ CamembertForMaskedLM,
113
+ CamembertForMultipleChoice,
114
+ CamembertForQuestionAnswering,
115
+ CamembertForSequenceClassification,
116
+ CamembertForTokenClassification,
117
+ CamembertModel,
118
+ CamembertPreTrainedModel,
119
+ )
120
+
121
+ try:
122
+ if not is_tf_available():
123
+ raise OptionalDependencyNotAvailable()
124
+ except OptionalDependencyNotAvailable:
125
+ pass
126
+ else:
127
+ from .modeling_tf_camembert import (
128
+ TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
129
+ TFCamembertForCausalLM,
130
+ TFCamembertForMaskedLM,
131
+ TFCamembertForMultipleChoice,
132
+ TFCamembertForQuestionAnswering,
133
+ TFCamembertForSequenceClassification,
134
+ TFCamembertForTokenClassification,
135
+ TFCamembertModel,
136
+ TFCamembertPreTrainedModel,
137
+ )
138
+
139
+ else:
140
+ import sys
141
+
142
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-310.pyc ADDED
Binary file (45 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/__pycache__/modeling_tf_camembert.cpython-310.pyc ADDED
Binary file (51.1 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/configuration_camembert.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ CamemBERT configuration"""
17
+
18
+ from collections import OrderedDict
19
+ from typing import Mapping
20
+
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfig
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
29
+ "camembert-base": "https://huggingface.co/camembert-base/resolve/main/config.json",
30
+ "umberto-commoncrawl-cased-v1": (
31
+ "https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json"
32
+ ),
33
+ "umberto-wikipedia-uncased-v1": (
34
+ "https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json"
35
+ ),
36
+ }
37
+
38
+
39
+ class CamembertConfig(PretrainedConfig):
40
+ """
41
+ This is the configuration class to store the configuration of a [`CamembertModel`] or a [`TFCamembertModel`]. It is
42
+ used to instantiate a Camembert model according to the specified arguments, defining the model architecture.
43
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Camembert
44
+ [camembert-base](https://huggingface.co/camembert-base) architecture.
45
+
46
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
47
+ documentation from [`PretrainedConfig`] for more information.
48
+
49
+
50
+ Args:
51
+ vocab_size (`int`, *optional*, defaults to 30522):
52
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
53
+ `inputs_ids` passed when calling [`CamembertModel`] or [`TFCamembertModel`].
54
+ hidden_size (`int`, *optional*, defaults to 768):
55
+ Dimensionality of the encoder layers and the pooler layer.
56
+ num_hidden_layers (`int`, *optional*, defaults to 12):
57
+ Number of hidden layers in the Transformer encoder.
58
+ num_attention_heads (`int`, *optional*, defaults to 12):
59
+ Number of attention heads for each attention layer in the Transformer encoder.
60
+ intermediate_size (`int`, *optional*, defaults to 3072):
61
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
62
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
63
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
64
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
65
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
66
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
67
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
68
+ The dropout ratio for the attention probabilities.
69
+ max_position_embeddings (`int`, *optional*, defaults to 512):
70
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
71
+ just in case (e.g., 512 or 1024 or 2048).
72
+ type_vocab_size (`int`, *optional*, defaults to 2):
73
+ The vocabulary size of the `token_type_ids` passed when calling [`CamembertModel`] or [`TFCamembertModel`].
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
77
+ The epsilon used by the layer normalization layers.
78
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
79
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
80
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
81
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
82
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
83
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
84
+ is_decoder (`bool`, *optional*, defaults to `False`):
85
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
86
+ use_cache (`bool`, *optional*, defaults to `True`):
87
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
88
+ relevant if `config.is_decoder=True`.
89
+ classifier_dropout (`float`, *optional*):
90
+ The dropout ratio for the classification head.
91
+
92
+ Example:
93
+
94
+ ```python
95
+ >>> from transformers import CamembertConfig, CamembertModel
96
+
97
+ >>> # Initializing a Camembert camembert-base style configuration
98
+ >>> configuration = CamembertConfig()
99
+
100
+ >>> # Initializing a model (with random weights) from the camembert-base style configuration
101
+ >>> model = CamembertModel(configuration)
102
+
103
+ >>> # Accessing the model configuration
104
+ >>> configuration = model.config
105
+ ```"""
106
+
107
+ model_type = "camembert"
108
+
109
+ def __init__(
110
+ self,
111
+ vocab_size=30522,
112
+ hidden_size=768,
113
+ num_hidden_layers=12,
114
+ num_attention_heads=12,
115
+ intermediate_size=3072,
116
+ hidden_act="gelu",
117
+ hidden_dropout_prob=0.1,
118
+ attention_probs_dropout_prob=0.1,
119
+ max_position_embeddings=512,
120
+ type_vocab_size=2,
121
+ initializer_range=0.02,
122
+ layer_norm_eps=1e-12,
123
+ pad_token_id=1,
124
+ bos_token_id=0,
125
+ eos_token_id=2,
126
+ position_embedding_type="absolute",
127
+ use_cache=True,
128
+ classifier_dropout=None,
129
+ **kwargs,
130
+ ):
131
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
132
+
133
+ self.vocab_size = vocab_size
134
+ self.hidden_size = hidden_size
135
+ self.num_hidden_layers = num_hidden_layers
136
+ self.num_attention_heads = num_attention_heads
137
+ self.hidden_act = hidden_act
138
+ self.intermediate_size = intermediate_size
139
+ self.hidden_dropout_prob = hidden_dropout_prob
140
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
141
+ self.max_position_embeddings = max_position_embeddings
142
+ self.type_vocab_size = type_vocab_size
143
+ self.initializer_range = initializer_range
144
+ self.layer_norm_eps = layer_norm_eps
145
+ self.position_embedding_type = position_embedding_type
146
+ self.use_cache = use_cache
147
+ self.classifier_dropout = classifier_dropout
148
+
149
+
150
+ class CamembertOnnxConfig(OnnxConfig):
151
+ @property
152
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
153
+ if self.task == "multiple-choice":
154
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
155
+ else:
156
+ dynamic_axis = {0: "batch", 1: "sequence"}
157
+ return OrderedDict(
158
+ [
159
+ ("input_ids", dynamic_axis),
160
+ ("attention_mask", dynamic_axis),
161
+ ]
162
+ )
evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/modeling_camembert.py ADDED
@@ -0,0 +1,1574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019 Inria, Facebook AI Research and the HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch CamemBERT model."""
17
+
18
+ import math
19
+ from typing import List, 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, gelu
27
+ from ...modeling_outputs import (
28
+ BaseModelOutputWithPastAndCrossAttentions,
29
+ BaseModelOutputWithPoolingAndCrossAttentions,
30
+ CausalLMOutputWithCrossAttentions,
31
+ MaskedLMOutput,
32
+ MultipleChoiceModelOutput,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutput,
35
+ TokenClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
39
+ from ...utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from .configuration_camembert import CamembertConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "camembert-base"
52
+ _CONFIG_FOR_DOC = "CamembertConfig"
53
+
54
+ CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
55
+ "camembert-base",
56
+ "Musixmatch/umberto-commoncrawl-cased-v1",
57
+ "Musixmatch/umberto-wikipedia-uncased-v1",
58
+ # See all CamemBERT models at https://huggingface.co/models?filter=camembert
59
+ ]
60
+
61
+ CAMEMBERT_START_DOCSTRING = r"""
62
+
63
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
64
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
65
+ etc.)
66
+
67
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
68
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
69
+ and behavior.
70
+
71
+ Parameters:
72
+ config ([`CamembertConfig`]): Model configuration class with all the parameters of the
73
+ model. Initializing with a config file does not load the weights associated with the model, only the
74
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
75
+ """
76
+
77
+
78
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->Camembert
79
+ class CamembertEmbeddings(nn.Module):
80
+ """
81
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
82
+ """
83
+
84
+ # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
85
+ def __init__(self, config):
86
+ super().__init__()
87
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
88
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
89
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
90
+
91
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
92
+ # any TensorFlow checkpoint file
93
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
94
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
95
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
96
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
97
+ self.register_buffer(
98
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
99
+ )
100
+ self.register_buffer(
101
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
102
+ )
103
+
104
+ # End copy
105
+ self.padding_idx = config.pad_token_id
106
+ self.position_embeddings = nn.Embedding(
107
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
108
+ )
109
+
110
+ def forward(
111
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
112
+ ):
113
+ if position_ids is None:
114
+ if input_ids is not None:
115
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
116
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
117
+ else:
118
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
119
+
120
+ if input_ids is not None:
121
+ input_shape = input_ids.size()
122
+ else:
123
+ input_shape = inputs_embeds.size()[:-1]
124
+
125
+ seq_length = input_shape[1]
126
+
127
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
128
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
129
+ # issue #5664
130
+ if token_type_ids is None:
131
+ if hasattr(self, "token_type_ids"):
132
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
133
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
134
+ token_type_ids = buffered_token_type_ids_expanded
135
+ else:
136
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
137
+
138
+ if inputs_embeds is None:
139
+ inputs_embeds = self.word_embeddings(input_ids)
140
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
141
+
142
+ embeddings = inputs_embeds + token_type_embeddings
143
+ if self.position_embedding_type == "absolute":
144
+ position_embeddings = self.position_embeddings(position_ids)
145
+ embeddings += position_embeddings
146
+ embeddings = self.LayerNorm(embeddings)
147
+ embeddings = self.dropout(embeddings)
148
+ return embeddings
149
+
150
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
151
+ """
152
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
153
+
154
+ Args:
155
+ inputs_embeds: torch.Tensor
156
+
157
+ Returns: torch.Tensor
158
+ """
159
+ input_shape = inputs_embeds.size()[:-1]
160
+ sequence_length = input_shape[1]
161
+
162
+ position_ids = torch.arange(
163
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
164
+ )
165
+ return position_ids.unsqueeze(0).expand(input_shape)
166
+
167
+
168
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->Camembert
169
+ class CamembertSelfAttention(nn.Module):
170
+ def __init__(self, config, position_embedding_type=None):
171
+ super().__init__()
172
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
173
+ raise ValueError(
174
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
175
+ f"heads ({config.num_attention_heads})"
176
+ )
177
+
178
+ self.num_attention_heads = config.num_attention_heads
179
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
180
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
181
+
182
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
183
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
184
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
185
+
186
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
187
+ self.position_embedding_type = position_embedding_type or getattr(
188
+ config, "position_embedding_type", "absolute"
189
+ )
190
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
191
+ self.max_position_embeddings = config.max_position_embeddings
192
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
193
+
194
+ self.is_decoder = config.is_decoder
195
+
196
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
197
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
198
+ x = x.view(new_x_shape)
199
+ return x.permute(0, 2, 1, 3)
200
+
201
+ def forward(
202
+ self,
203
+ hidden_states: torch.Tensor,
204
+ attention_mask: Optional[torch.FloatTensor] = None,
205
+ head_mask: Optional[torch.FloatTensor] = None,
206
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
207
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
208
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
209
+ output_attentions: Optional[bool] = False,
210
+ ) -> Tuple[torch.Tensor]:
211
+ mixed_query_layer = self.query(hidden_states)
212
+
213
+ # If this is instantiated as a cross-attention module, the keys
214
+ # and values come from an encoder; the attention mask needs to be
215
+ # such that the encoder's padding tokens are not attended to.
216
+ is_cross_attention = encoder_hidden_states is not None
217
+
218
+ if is_cross_attention and past_key_value is not None:
219
+ # reuse k,v, cross_attentions
220
+ key_layer = past_key_value[0]
221
+ value_layer = past_key_value[1]
222
+ attention_mask = encoder_attention_mask
223
+ elif is_cross_attention:
224
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
225
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
226
+ attention_mask = encoder_attention_mask
227
+ elif past_key_value is not None:
228
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
229
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
230
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
231
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
232
+ else:
233
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
234
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
235
+
236
+ query_layer = self.transpose_for_scores(mixed_query_layer)
237
+
238
+ use_cache = past_key_value is not None
239
+ if self.is_decoder:
240
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
241
+ # Further calls to cross_attention layer can then reuse all cross-attention
242
+ # key/value_states (first "if" case)
243
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
244
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
245
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
246
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
247
+ past_key_value = (key_layer, value_layer)
248
+
249
+ # Take the dot product between "query" and "key" to get the raw attention scores.
250
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
251
+
252
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
253
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
254
+ if use_cache:
255
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
256
+ -1, 1
257
+ )
258
+ else:
259
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
260
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
261
+ distance = position_ids_l - position_ids_r
262
+
263
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
264
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
265
+
266
+ if self.position_embedding_type == "relative_key":
267
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
268
+ attention_scores = attention_scores + relative_position_scores
269
+ elif self.position_embedding_type == "relative_key_query":
270
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
271
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
272
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
273
+
274
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
275
+ if attention_mask is not None:
276
+ # Apply the attention mask is (precomputed for all layers in CamembertModel forward() function)
277
+ attention_scores = attention_scores + attention_mask
278
+
279
+ # Normalize the attention scores to probabilities.
280
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
281
+
282
+ # This is actually dropping out entire tokens to attend to, which might
283
+ # seem a bit unusual, but is taken from the original Transformer paper.
284
+ attention_probs = self.dropout(attention_probs)
285
+
286
+ # Mask heads if we want to
287
+ if head_mask is not None:
288
+ attention_probs = attention_probs * head_mask
289
+
290
+ context_layer = torch.matmul(attention_probs, value_layer)
291
+
292
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
293
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
294
+ context_layer = context_layer.view(new_context_layer_shape)
295
+
296
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
297
+
298
+ if self.is_decoder:
299
+ outputs = outputs + (past_key_value,)
300
+ return outputs
301
+
302
+
303
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput with Roberta->Camembert
304
+ class CamembertSelfOutput(nn.Module):
305
+ def __init__(self, config):
306
+ super().__init__()
307
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
308
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
309
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
310
+
311
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
312
+ hidden_states = self.dense(hidden_states)
313
+ hidden_states = self.dropout(hidden_states)
314
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
315
+ return hidden_states
316
+
317
+
318
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaAttention with Roberta->Camembert
319
+ class CamembertAttention(nn.Module):
320
+ def __init__(self, config, position_embedding_type=None):
321
+ super().__init__()
322
+ self.self = CamembertSelfAttention(config, position_embedding_type=position_embedding_type)
323
+ self.output = CamembertSelfOutput(config)
324
+ self.pruned_heads = set()
325
+
326
+ def prune_heads(self, heads):
327
+ if len(heads) == 0:
328
+ return
329
+ heads, index = find_pruneable_heads_and_indices(
330
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
331
+ )
332
+
333
+ # Prune linear layers
334
+ self.self.query = prune_linear_layer(self.self.query, index)
335
+ self.self.key = prune_linear_layer(self.self.key, index)
336
+ self.self.value = prune_linear_layer(self.self.value, index)
337
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
338
+
339
+ # Update hyper params and store pruned heads
340
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
341
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
342
+ self.pruned_heads = self.pruned_heads.union(heads)
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ attention_mask: Optional[torch.FloatTensor] = None,
348
+ head_mask: Optional[torch.FloatTensor] = None,
349
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
350
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
351
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
352
+ output_attentions: Optional[bool] = False,
353
+ ) -> Tuple[torch.Tensor]:
354
+ self_outputs = self.self(
355
+ hidden_states,
356
+ attention_mask,
357
+ head_mask,
358
+ encoder_hidden_states,
359
+ encoder_attention_mask,
360
+ past_key_value,
361
+ output_attentions,
362
+ )
363
+ attention_output = self.output(self_outputs[0], hidden_states)
364
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
365
+ return outputs
366
+
367
+
368
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Roberta->Camembert
369
+ class CamembertIntermediate(nn.Module):
370
+ def __init__(self, config):
371
+ super().__init__()
372
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
373
+ if isinstance(config.hidden_act, str):
374
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
375
+ else:
376
+ self.intermediate_act_fn = config.hidden_act
377
+
378
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
379
+ hidden_states = self.dense(hidden_states)
380
+ hidden_states = self.intermediate_act_fn(hidden_states)
381
+ return hidden_states
382
+
383
+
384
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Roberta->Camembert
385
+ class CamembertOutput(nn.Module):
386
+ def __init__(self, config):
387
+ super().__init__()
388
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
389
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
390
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
391
+
392
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
393
+ hidden_states = self.dense(hidden_states)
394
+ hidden_states = self.dropout(hidden_states)
395
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
396
+ return hidden_states
397
+
398
+
399
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaLayer with Roberta->Camembert
400
+ class CamembertLayer(nn.Module):
401
+ def __init__(self, config):
402
+ super().__init__()
403
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
404
+ self.seq_len_dim = 1
405
+ self.attention = CamembertAttention(config)
406
+ self.is_decoder = config.is_decoder
407
+ self.add_cross_attention = config.add_cross_attention
408
+ if self.add_cross_attention:
409
+ if not self.is_decoder:
410
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
411
+ self.crossattention = CamembertAttention(config, position_embedding_type="absolute")
412
+ self.intermediate = CamembertIntermediate(config)
413
+ self.output = CamembertOutput(config)
414
+
415
+ def forward(
416
+ self,
417
+ hidden_states: torch.Tensor,
418
+ attention_mask: Optional[torch.FloatTensor] = None,
419
+ head_mask: Optional[torch.FloatTensor] = None,
420
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
421
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
422
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
423
+ output_attentions: Optional[bool] = False,
424
+ ) -> Tuple[torch.Tensor]:
425
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
426
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
427
+ self_attention_outputs = self.attention(
428
+ hidden_states,
429
+ attention_mask,
430
+ head_mask,
431
+ output_attentions=output_attentions,
432
+ past_key_value=self_attn_past_key_value,
433
+ )
434
+ attention_output = self_attention_outputs[0]
435
+
436
+ # if decoder, the last output is tuple of self-attn cache
437
+ if self.is_decoder:
438
+ outputs = self_attention_outputs[1:-1]
439
+ present_key_value = self_attention_outputs[-1]
440
+ else:
441
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
442
+
443
+ cross_attn_present_key_value = None
444
+ if self.is_decoder and encoder_hidden_states is not None:
445
+ if not hasattr(self, "crossattention"):
446
+ raise ValueError(
447
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
448
+ " by setting `config.add_cross_attention=True`"
449
+ )
450
+
451
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
452
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
453
+ cross_attention_outputs = self.crossattention(
454
+ attention_output,
455
+ attention_mask,
456
+ head_mask,
457
+ encoder_hidden_states,
458
+ encoder_attention_mask,
459
+ cross_attn_past_key_value,
460
+ output_attentions,
461
+ )
462
+ attention_output = cross_attention_outputs[0]
463
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
464
+
465
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
466
+ cross_attn_present_key_value = cross_attention_outputs[-1]
467
+ present_key_value = present_key_value + cross_attn_present_key_value
468
+
469
+ layer_output = apply_chunking_to_forward(
470
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
471
+ )
472
+ outputs = (layer_output,) + outputs
473
+
474
+ # if decoder, return the attn key/values as the last output
475
+ if self.is_decoder:
476
+ outputs = outputs + (present_key_value,)
477
+
478
+ return outputs
479
+
480
+ def feed_forward_chunk(self, attention_output):
481
+ intermediate_output = self.intermediate(attention_output)
482
+ layer_output = self.output(intermediate_output, attention_output)
483
+ return layer_output
484
+
485
+
486
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->Camembert
487
+ class CamembertEncoder(nn.Module):
488
+ def __init__(self, config):
489
+ super().__init__()
490
+ self.config = config
491
+ self.layer = nn.ModuleList([CamembertLayer(config) for _ in range(config.num_hidden_layers)])
492
+ self.gradient_checkpointing = False
493
+
494
+ def forward(
495
+ self,
496
+ hidden_states: torch.Tensor,
497
+ attention_mask: Optional[torch.FloatTensor] = None,
498
+ head_mask: Optional[torch.FloatTensor] = None,
499
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
500
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
501
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
502
+ use_cache: Optional[bool] = None,
503
+ output_attentions: Optional[bool] = False,
504
+ output_hidden_states: Optional[bool] = False,
505
+ return_dict: Optional[bool] = True,
506
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
507
+ all_hidden_states = () if output_hidden_states else None
508
+ all_self_attentions = () if output_attentions else None
509
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
510
+
511
+ if self.gradient_checkpointing and self.training:
512
+ if use_cache:
513
+ logger.warning_once(
514
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
515
+ )
516
+ use_cache = False
517
+
518
+ next_decoder_cache = () if use_cache else None
519
+ for i, layer_module in enumerate(self.layer):
520
+ if output_hidden_states:
521
+ all_hidden_states = all_hidden_states + (hidden_states,)
522
+
523
+ layer_head_mask = head_mask[i] if head_mask is not None else None
524
+ past_key_value = past_key_values[i] if past_key_values is not None else None
525
+
526
+ if self.gradient_checkpointing and self.training:
527
+ layer_outputs = self._gradient_checkpointing_func(
528
+ layer_module.__call__,
529
+ hidden_states,
530
+ attention_mask,
531
+ layer_head_mask,
532
+ encoder_hidden_states,
533
+ encoder_attention_mask,
534
+ past_key_value,
535
+ output_attentions,
536
+ )
537
+ else:
538
+ layer_outputs = layer_module(
539
+ hidden_states,
540
+ attention_mask,
541
+ layer_head_mask,
542
+ encoder_hidden_states,
543
+ encoder_attention_mask,
544
+ past_key_value,
545
+ output_attentions,
546
+ )
547
+
548
+ hidden_states = layer_outputs[0]
549
+ if use_cache:
550
+ next_decoder_cache += (layer_outputs[-1],)
551
+ if output_attentions:
552
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
553
+ if self.config.add_cross_attention:
554
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
555
+
556
+ if output_hidden_states:
557
+ all_hidden_states = all_hidden_states + (hidden_states,)
558
+
559
+ if not return_dict:
560
+ return tuple(
561
+ v
562
+ for v in [
563
+ hidden_states,
564
+ next_decoder_cache,
565
+ all_hidden_states,
566
+ all_self_attentions,
567
+ all_cross_attentions,
568
+ ]
569
+ if v is not None
570
+ )
571
+ return BaseModelOutputWithPastAndCrossAttentions(
572
+ last_hidden_state=hidden_states,
573
+ past_key_values=next_decoder_cache,
574
+ hidden_states=all_hidden_states,
575
+ attentions=all_self_attentions,
576
+ cross_attentions=all_cross_attentions,
577
+ )
578
+
579
+
580
+ # Copied from transformers.models.bert.modeling_bert.BertPooler
581
+ class CamembertPooler(nn.Module):
582
+ def __init__(self, config):
583
+ super().__init__()
584
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
585
+ self.activation = nn.Tanh()
586
+
587
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
588
+ # We "pool" the model by simply taking the hidden state corresponding
589
+ # to the first token.
590
+ first_token_tensor = hidden_states[:, 0]
591
+ pooled_output = self.dense(first_token_tensor)
592
+ pooled_output = self.activation(pooled_output)
593
+ return pooled_output
594
+
595
+
596
+ class CamembertPreTrainedModel(PreTrainedModel):
597
+ """
598
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
599
+ models.
600
+ """
601
+
602
+ config_class = CamembertConfig
603
+ base_model_prefix = "roberta"
604
+ supports_gradient_checkpointing = True
605
+
606
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
607
+ def _init_weights(self, module):
608
+ """Initialize the weights"""
609
+ if isinstance(module, nn.Linear):
610
+ # Slightly different from the TF version which uses truncated_normal for initialization
611
+ # cf https://github.com/pytorch/pytorch/pull/5617
612
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
613
+ if module.bias is not None:
614
+ module.bias.data.zero_()
615
+ elif isinstance(module, nn.Embedding):
616
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
617
+ if module.padding_idx is not None:
618
+ module.weight.data[module.padding_idx].zero_()
619
+ elif isinstance(module, nn.LayerNorm):
620
+ module.bias.data.zero_()
621
+ module.weight.data.fill_(1.0)
622
+
623
+
624
+ CAMEMBERT_INPUTS_DOCSTRING = r"""
625
+ Args:
626
+ input_ids (`torch.LongTensor` of shape `({0})`):
627
+ Indices of input sequence tokens in the vocabulary.
628
+
629
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
630
+ [`PreTrainedTokenizer.__call__`] for details.
631
+
632
+ [What are input IDs?](../glossary#input-ids)
633
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
634
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
635
+
636
+ - 1 for tokens that are **not masked**,
637
+ - 0 for tokens that are **masked**.
638
+
639
+ [What are attention masks?](../glossary#attention-mask)
640
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
641
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
642
+ 1]`:
643
+
644
+ - 0 corresponds to a *sentence A* token,
645
+ - 1 corresponds to a *sentence B* token.
646
+
647
+ [What are token type IDs?](../glossary#token-type-ids)
648
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
649
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
650
+ config.max_position_embeddings - 1]`.
651
+
652
+ [What are position IDs?](../glossary#position-ids)
653
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
654
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
655
+
656
+ - 1 indicates the head is **not masked**,
657
+ - 0 indicates the head is **masked**.
658
+
659
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
660
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
661
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
662
+ model's internal embedding lookup matrix.
663
+ output_attentions (`bool`, *optional*):
664
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
665
+ tensors for more detail.
666
+ output_hidden_states (`bool`, *optional*):
667
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
668
+ more detail.
669
+ return_dict (`bool`, *optional*):
670
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
671
+ """
672
+
673
+
674
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->Camembert
675
+ class CamembertClassificationHead(nn.Module):
676
+ """Head for sentence-level classification tasks."""
677
+
678
+ def __init__(self, config):
679
+ super().__init__()
680
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
681
+ classifier_dropout = (
682
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
683
+ )
684
+ self.dropout = nn.Dropout(classifier_dropout)
685
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
686
+
687
+ def forward(self, features, **kwargs):
688
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
689
+ x = self.dropout(x)
690
+ x = self.dense(x)
691
+ x = torch.tanh(x)
692
+ x = self.dropout(x)
693
+ x = self.out_proj(x)
694
+ return x
695
+
696
+
697
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead with Roberta->Camembert
698
+ class CamembertLMHead(nn.Module):
699
+ """Camembert Head for masked language modeling."""
700
+
701
+ def __init__(self, config):
702
+ super().__init__()
703
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
704
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
705
+
706
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
707
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
708
+ self.decoder.bias = self.bias
709
+
710
+ def forward(self, features, **kwargs):
711
+ x = self.dense(features)
712
+ x = gelu(x)
713
+ x = self.layer_norm(x)
714
+
715
+ # project back to size of vocabulary with bias
716
+ x = self.decoder(x)
717
+
718
+ return x
719
+
720
+ def _tie_weights(self):
721
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
722
+ # For accelerate compatibility and to not break backward compatibility
723
+ if self.decoder.bias.device.type == "meta":
724
+ self.decoder.bias = self.bias
725
+ else:
726
+ self.bias = self.decoder.bias
727
+
728
+
729
+ @add_start_docstrings(
730
+ "The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.",
731
+ CAMEMBERT_START_DOCSTRING,
732
+ )
733
+ class CamembertModel(CamembertPreTrainedModel):
734
+ """
735
+
736
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
737
+ cross-attention is added between the self-attention layers, following the architecture described in *Attention is
738
+ all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
739
+ Kaiser and Illia Polosukhin.
740
+
741
+ To behave as a decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to
742
+ `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
743
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
744
+
745
+ .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
746
+
747
+ """
748
+
749
+ _no_split_modules = []
750
+
751
+ # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Camembert
752
+ def __init__(self, config, add_pooling_layer=True):
753
+ super().__init__(config)
754
+ self.config = config
755
+
756
+ self.embeddings = CamembertEmbeddings(config)
757
+ self.encoder = CamembertEncoder(config)
758
+
759
+ self.pooler = CamembertPooler(config) if add_pooling_layer else None
760
+
761
+ # Initialize weights and apply final processing
762
+ self.post_init()
763
+
764
+ def get_input_embeddings(self):
765
+ return self.embeddings.word_embeddings
766
+
767
+ def set_input_embeddings(self, value):
768
+ self.embeddings.word_embeddings = value
769
+
770
+ def _prune_heads(self, heads_to_prune):
771
+ """
772
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
773
+ class PreTrainedModel
774
+ """
775
+ for layer, heads in heads_to_prune.items():
776
+ self.encoder.layer[layer].attention.prune_heads(heads)
777
+
778
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
779
+ @add_code_sample_docstrings(
780
+ checkpoint=_CHECKPOINT_FOR_DOC,
781
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
782
+ config_class=_CONFIG_FOR_DOC,
783
+ )
784
+ # Copied from transformers.models.bert.modeling_bert.BertModel.forward
785
+ def forward(
786
+ self,
787
+ input_ids: Optional[torch.Tensor] = None,
788
+ attention_mask: Optional[torch.Tensor] = None,
789
+ token_type_ids: Optional[torch.Tensor] = None,
790
+ position_ids: Optional[torch.Tensor] = None,
791
+ head_mask: Optional[torch.Tensor] = None,
792
+ inputs_embeds: Optional[torch.Tensor] = None,
793
+ encoder_hidden_states: Optional[torch.Tensor] = None,
794
+ encoder_attention_mask: Optional[torch.Tensor] = None,
795
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
796
+ use_cache: Optional[bool] = None,
797
+ output_attentions: Optional[bool] = None,
798
+ output_hidden_states: Optional[bool] = None,
799
+ return_dict: Optional[bool] = None,
800
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
801
+ r"""
802
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
803
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
804
+ the model is configured as a decoder.
805
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
806
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
807
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
808
+
809
+ - 1 for tokens that are **not masked**,
810
+ - 0 for tokens that are **masked**.
811
+ 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)`):
812
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
813
+
814
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
815
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
816
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
817
+ use_cache (`bool`, *optional*):
818
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
819
+ `past_key_values`).
820
+ """
821
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
822
+ output_hidden_states = (
823
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
824
+ )
825
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
826
+
827
+ if self.config.is_decoder:
828
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
829
+ else:
830
+ use_cache = False
831
+
832
+ if input_ids is not None and inputs_embeds is not None:
833
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
834
+ elif input_ids is not None:
835
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
836
+ input_shape = input_ids.size()
837
+ elif inputs_embeds is not None:
838
+ input_shape = inputs_embeds.size()[:-1]
839
+ else:
840
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
841
+
842
+ batch_size, seq_length = input_shape
843
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
844
+
845
+ # past_key_values_length
846
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
847
+
848
+ if attention_mask is None:
849
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
850
+
851
+ if token_type_ids is None:
852
+ if hasattr(self.embeddings, "token_type_ids"):
853
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
854
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
855
+ token_type_ids = buffered_token_type_ids_expanded
856
+ else:
857
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
858
+
859
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
860
+ # ourselves in which case we just need to make it broadcastable to all heads.
861
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
862
+
863
+ # If a 2D or 3D attention mask is provided for the cross-attention
864
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
865
+ if self.config.is_decoder and encoder_hidden_states is not None:
866
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
867
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
868
+ if encoder_attention_mask is None:
869
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
870
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
871
+ else:
872
+ encoder_extended_attention_mask = None
873
+
874
+ # Prepare head mask if needed
875
+ # 1.0 in head_mask indicate we keep the head
876
+ # attention_probs has shape bsz x n_heads x N x N
877
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
878
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
879
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
880
+
881
+ embedding_output = self.embeddings(
882
+ input_ids=input_ids,
883
+ position_ids=position_ids,
884
+ token_type_ids=token_type_ids,
885
+ inputs_embeds=inputs_embeds,
886
+ past_key_values_length=past_key_values_length,
887
+ )
888
+ encoder_outputs = self.encoder(
889
+ embedding_output,
890
+ attention_mask=extended_attention_mask,
891
+ head_mask=head_mask,
892
+ encoder_hidden_states=encoder_hidden_states,
893
+ encoder_attention_mask=encoder_extended_attention_mask,
894
+ past_key_values=past_key_values,
895
+ use_cache=use_cache,
896
+ output_attentions=output_attentions,
897
+ output_hidden_states=output_hidden_states,
898
+ return_dict=return_dict,
899
+ )
900
+ sequence_output = encoder_outputs[0]
901
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
902
+
903
+ if not return_dict:
904
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
905
+
906
+ return BaseModelOutputWithPoolingAndCrossAttentions(
907
+ last_hidden_state=sequence_output,
908
+ pooler_output=pooled_output,
909
+ past_key_values=encoder_outputs.past_key_values,
910
+ hidden_states=encoder_outputs.hidden_states,
911
+ attentions=encoder_outputs.attentions,
912
+ cross_attentions=encoder_outputs.cross_attentions,
913
+ )
914
+
915
+
916
+ @add_start_docstrings(
917
+ """CamemBERT Model with a `language modeling` head on top.""",
918
+ CAMEMBERT_START_DOCSTRING,
919
+ )
920
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT
921
+ class CamembertForMaskedLM(CamembertPreTrainedModel):
922
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
923
+
924
+ def __init__(self, config):
925
+ super().__init__(config)
926
+
927
+ if config.is_decoder:
928
+ logger.warning(
929
+ "If you want to use `CamembertForMaskedLM` make sure `config.is_decoder=False` for "
930
+ "bi-directional self-attention."
931
+ )
932
+
933
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
934
+ self.lm_head = CamembertLMHead(config)
935
+
936
+ # Initialize weights and apply final processing
937
+ self.post_init()
938
+
939
+ def get_output_embeddings(self):
940
+ return self.lm_head.decoder
941
+
942
+ def set_output_embeddings(self, new_embeddings):
943
+ self.lm_head.decoder = new_embeddings
944
+
945
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
946
+ @add_code_sample_docstrings(
947
+ checkpoint=_CHECKPOINT_FOR_DOC,
948
+ output_type=MaskedLMOutput,
949
+ config_class=_CONFIG_FOR_DOC,
950
+ mask="<mask>",
951
+ expected_output="' Paris'",
952
+ expected_loss=0.1,
953
+ )
954
+ def forward(
955
+ self,
956
+ input_ids: Optional[torch.LongTensor] = None,
957
+ attention_mask: Optional[torch.FloatTensor] = None,
958
+ token_type_ids: Optional[torch.LongTensor] = None,
959
+ position_ids: Optional[torch.LongTensor] = None,
960
+ head_mask: Optional[torch.FloatTensor] = None,
961
+ inputs_embeds: Optional[torch.FloatTensor] = None,
962
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
963
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
964
+ labels: Optional[torch.LongTensor] = None,
965
+ output_attentions: Optional[bool] = None,
966
+ output_hidden_states: Optional[bool] = None,
967
+ return_dict: Optional[bool] = None,
968
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
969
+ r"""
970
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
971
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
972
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
973
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
974
+ kwargs (`Dict[str, any]`, optional, defaults to *{}*):
975
+ Used to hide legacy arguments that have been deprecated.
976
+ """
977
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
978
+
979
+ outputs = self.roberta(
980
+ input_ids,
981
+ attention_mask=attention_mask,
982
+ token_type_ids=token_type_ids,
983
+ position_ids=position_ids,
984
+ head_mask=head_mask,
985
+ inputs_embeds=inputs_embeds,
986
+ encoder_hidden_states=encoder_hidden_states,
987
+ encoder_attention_mask=encoder_attention_mask,
988
+ output_attentions=output_attentions,
989
+ output_hidden_states=output_hidden_states,
990
+ return_dict=return_dict,
991
+ )
992
+ sequence_output = outputs[0]
993
+ prediction_scores = self.lm_head(sequence_output)
994
+
995
+ masked_lm_loss = None
996
+ if labels is not None:
997
+ # move labels to correct device to enable model parallelism
998
+ labels = labels.to(prediction_scores.device)
999
+ loss_fct = CrossEntropyLoss()
1000
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1001
+
1002
+ if not return_dict:
1003
+ output = (prediction_scores,) + outputs[2:]
1004
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1005
+
1006
+ return MaskedLMOutput(
1007
+ loss=masked_lm_loss,
1008
+ logits=prediction_scores,
1009
+ hidden_states=outputs.hidden_states,
1010
+ attentions=outputs.attentions,
1011
+ )
1012
+
1013
+
1014
+ @add_start_docstrings(
1015
+ """
1016
+ CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1017
+ pooled output) e.g. for GLUE tasks.
1018
+ """,
1019
+ CAMEMBERT_START_DOCSTRING,
1020
+ )
1021
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
1022
+ class CamembertForSequenceClassification(CamembertPreTrainedModel):
1023
+ def __init__(self, config):
1024
+ super().__init__(config)
1025
+ self.num_labels = config.num_labels
1026
+ self.config = config
1027
+
1028
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
1029
+ self.classifier = CamembertClassificationHead(config)
1030
+
1031
+ # Initialize weights and apply final processing
1032
+ self.post_init()
1033
+
1034
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1035
+ @add_code_sample_docstrings(
1036
+ checkpoint="cardiffnlp/twitter-roberta-base-emotion",
1037
+ output_type=SequenceClassifierOutput,
1038
+ config_class=_CONFIG_FOR_DOC,
1039
+ expected_output="'optimism'",
1040
+ expected_loss=0.08,
1041
+ )
1042
+ def forward(
1043
+ self,
1044
+ input_ids: Optional[torch.LongTensor] = None,
1045
+ attention_mask: Optional[torch.FloatTensor] = None,
1046
+ token_type_ids: Optional[torch.LongTensor] = None,
1047
+ position_ids: Optional[torch.LongTensor] = None,
1048
+ head_mask: Optional[torch.FloatTensor] = None,
1049
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1050
+ labels: Optional[torch.LongTensor] = None,
1051
+ output_attentions: Optional[bool] = None,
1052
+ output_hidden_states: Optional[bool] = None,
1053
+ return_dict: Optional[bool] = None,
1054
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1055
+ r"""
1056
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1057
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1058
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1059
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1060
+ """
1061
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1062
+
1063
+ outputs = self.roberta(
1064
+ input_ids,
1065
+ attention_mask=attention_mask,
1066
+ token_type_ids=token_type_ids,
1067
+ position_ids=position_ids,
1068
+ head_mask=head_mask,
1069
+ inputs_embeds=inputs_embeds,
1070
+ output_attentions=output_attentions,
1071
+ output_hidden_states=output_hidden_states,
1072
+ return_dict=return_dict,
1073
+ )
1074
+ sequence_output = outputs[0]
1075
+ logits = self.classifier(sequence_output)
1076
+
1077
+ loss = None
1078
+ if labels is not None:
1079
+ # move labels to correct device to enable model parallelism
1080
+ labels = labels.to(logits.device)
1081
+ if self.config.problem_type is None:
1082
+ if self.num_labels == 1:
1083
+ self.config.problem_type = "regression"
1084
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1085
+ self.config.problem_type = "single_label_classification"
1086
+ else:
1087
+ self.config.problem_type = "multi_label_classification"
1088
+
1089
+ if self.config.problem_type == "regression":
1090
+ loss_fct = MSELoss()
1091
+ if self.num_labels == 1:
1092
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1093
+ else:
1094
+ loss = loss_fct(logits, labels)
1095
+ elif self.config.problem_type == "single_label_classification":
1096
+ loss_fct = CrossEntropyLoss()
1097
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1098
+ elif self.config.problem_type == "multi_label_classification":
1099
+ loss_fct = BCEWithLogitsLoss()
1100
+ loss = loss_fct(logits, labels)
1101
+
1102
+ if not return_dict:
1103
+ output = (logits,) + outputs[2:]
1104
+ return ((loss,) + output) if loss is not None else output
1105
+
1106
+ return SequenceClassifierOutput(
1107
+ loss=loss,
1108
+ logits=logits,
1109
+ hidden_states=outputs.hidden_states,
1110
+ attentions=outputs.attentions,
1111
+ )
1112
+
1113
+
1114
+ @add_start_docstrings(
1115
+ """
1116
+ CamemBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1117
+ softmax) e.g. for RocStories/SWAG tasks.
1118
+ """,
1119
+ CAMEMBERT_START_DOCSTRING,
1120
+ )
1121
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMultipleChoice with Roberta->Camembert, ROBERTA->CAMEMBERT
1122
+ class CamembertForMultipleChoice(CamembertPreTrainedModel):
1123
+ def __init__(self, config):
1124
+ super().__init__(config)
1125
+
1126
+ self.roberta = CamembertModel(config)
1127
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1128
+ self.classifier = nn.Linear(config.hidden_size, 1)
1129
+
1130
+ # Initialize weights and apply final processing
1131
+ self.post_init()
1132
+
1133
+ @add_start_docstrings_to_model_forward(
1134
+ CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1135
+ )
1136
+ @add_code_sample_docstrings(
1137
+ checkpoint=_CHECKPOINT_FOR_DOC,
1138
+ output_type=MultipleChoiceModelOutput,
1139
+ config_class=_CONFIG_FOR_DOC,
1140
+ )
1141
+ def forward(
1142
+ self,
1143
+ input_ids: Optional[torch.LongTensor] = None,
1144
+ token_type_ids: Optional[torch.LongTensor] = None,
1145
+ attention_mask: Optional[torch.FloatTensor] = None,
1146
+ labels: Optional[torch.LongTensor] = None,
1147
+ position_ids: Optional[torch.LongTensor] = None,
1148
+ head_mask: Optional[torch.FloatTensor] = None,
1149
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1150
+ output_attentions: Optional[bool] = None,
1151
+ output_hidden_states: Optional[bool] = None,
1152
+ return_dict: Optional[bool] = None,
1153
+ ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
1154
+ r"""
1155
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1156
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1157
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1158
+ `input_ids` above)
1159
+ """
1160
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1161
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1162
+
1163
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1164
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1165
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1166
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1167
+ flat_inputs_embeds = (
1168
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1169
+ if inputs_embeds is not None
1170
+ else None
1171
+ )
1172
+
1173
+ outputs = self.roberta(
1174
+ flat_input_ids,
1175
+ position_ids=flat_position_ids,
1176
+ token_type_ids=flat_token_type_ids,
1177
+ attention_mask=flat_attention_mask,
1178
+ head_mask=head_mask,
1179
+ inputs_embeds=flat_inputs_embeds,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ )
1184
+ pooled_output = outputs[1]
1185
+
1186
+ pooled_output = self.dropout(pooled_output)
1187
+ logits = self.classifier(pooled_output)
1188
+ reshaped_logits = logits.view(-1, num_choices)
1189
+
1190
+ loss = None
1191
+ if labels is not None:
1192
+ # move labels to correct device to enable model parallelism
1193
+ labels = labels.to(reshaped_logits.device)
1194
+ loss_fct = CrossEntropyLoss()
1195
+ loss = loss_fct(reshaped_logits, labels)
1196
+
1197
+ if not return_dict:
1198
+ output = (reshaped_logits,) + outputs[2:]
1199
+ return ((loss,) + output) if loss is not None else output
1200
+
1201
+ return MultipleChoiceModelOutput(
1202
+ loss=loss,
1203
+ logits=reshaped_logits,
1204
+ hidden_states=outputs.hidden_states,
1205
+ attentions=outputs.attentions,
1206
+ )
1207
+
1208
+
1209
+ @add_start_docstrings(
1210
+ """
1211
+ CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1212
+ for Named-Entity-Recognition (NER) tasks.
1213
+ """,
1214
+ CAMEMBERT_START_DOCSTRING,
1215
+ )
1216
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
1217
+ class CamembertForTokenClassification(CamembertPreTrainedModel):
1218
+ def __init__(self, config):
1219
+ super().__init__(config)
1220
+ self.num_labels = config.num_labels
1221
+
1222
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
1223
+ classifier_dropout = (
1224
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1225
+ )
1226
+ self.dropout = nn.Dropout(classifier_dropout)
1227
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1228
+
1229
+ # Initialize weights and apply final processing
1230
+ self.post_init()
1231
+
1232
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1233
+ @add_code_sample_docstrings(
1234
+ checkpoint="Jean-Baptiste/roberta-large-ner-english",
1235
+ output_type=TokenClassifierOutput,
1236
+ config_class=_CONFIG_FOR_DOC,
1237
+ expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']",
1238
+ expected_loss=0.01,
1239
+ )
1240
+ def forward(
1241
+ self,
1242
+ input_ids: Optional[torch.LongTensor] = None,
1243
+ attention_mask: Optional[torch.FloatTensor] = None,
1244
+ token_type_ids: Optional[torch.LongTensor] = None,
1245
+ position_ids: Optional[torch.LongTensor] = None,
1246
+ head_mask: Optional[torch.FloatTensor] = None,
1247
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1248
+ labels: Optional[torch.LongTensor] = None,
1249
+ output_attentions: Optional[bool] = None,
1250
+ output_hidden_states: Optional[bool] = None,
1251
+ return_dict: Optional[bool] = None,
1252
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1253
+ r"""
1254
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1255
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1256
+ """
1257
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1258
+
1259
+ outputs = self.roberta(
1260
+ input_ids,
1261
+ attention_mask=attention_mask,
1262
+ token_type_ids=token_type_ids,
1263
+ position_ids=position_ids,
1264
+ head_mask=head_mask,
1265
+ inputs_embeds=inputs_embeds,
1266
+ output_attentions=output_attentions,
1267
+ output_hidden_states=output_hidden_states,
1268
+ return_dict=return_dict,
1269
+ )
1270
+
1271
+ sequence_output = outputs[0]
1272
+
1273
+ sequence_output = self.dropout(sequence_output)
1274
+ logits = self.classifier(sequence_output)
1275
+
1276
+ loss = None
1277
+ if labels is not None:
1278
+ # move labels to correct device to enable model parallelism
1279
+ labels = labels.to(logits.device)
1280
+ loss_fct = CrossEntropyLoss()
1281
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1282
+
1283
+ if not return_dict:
1284
+ output = (logits,) + outputs[2:]
1285
+ return ((loss,) + output) if loss is not None else output
1286
+
1287
+ return TokenClassifierOutput(
1288
+ loss=loss,
1289
+ logits=logits,
1290
+ hidden_states=outputs.hidden_states,
1291
+ attentions=outputs.attentions,
1292
+ )
1293
+
1294
+
1295
+ @add_start_docstrings(
1296
+ """
1297
+ CamemBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1298
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`
1299
+ """,
1300
+ CAMEMBERT_START_DOCSTRING,
1301
+ )
1302
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering with Roberta->Camembert, ROBERTA->CAMEMBERT
1303
+ class CamembertForQuestionAnswering(CamembertPreTrainedModel):
1304
+ def __init__(self, config):
1305
+ super().__init__(config)
1306
+ self.num_labels = config.num_labels
1307
+
1308
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
1309
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1310
+
1311
+ # Initialize weights and apply final processing
1312
+ self.post_init()
1313
+
1314
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1315
+ @add_code_sample_docstrings(
1316
+ checkpoint="deepset/roberta-base-squad2",
1317
+ output_type=QuestionAnsweringModelOutput,
1318
+ config_class=_CONFIG_FOR_DOC,
1319
+ expected_output="' puppet'",
1320
+ expected_loss=0.86,
1321
+ )
1322
+ def forward(
1323
+ self,
1324
+ input_ids: Optional[torch.LongTensor] = None,
1325
+ attention_mask: Optional[torch.FloatTensor] = None,
1326
+ token_type_ids: Optional[torch.LongTensor] = None,
1327
+ position_ids: Optional[torch.LongTensor] = None,
1328
+ head_mask: Optional[torch.FloatTensor] = None,
1329
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1330
+ start_positions: Optional[torch.LongTensor] = None,
1331
+ end_positions: Optional[torch.LongTensor] = None,
1332
+ output_attentions: Optional[bool] = None,
1333
+ output_hidden_states: Optional[bool] = None,
1334
+ return_dict: Optional[bool] = None,
1335
+ ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1336
+ r"""
1337
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1338
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1339
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1340
+ are not taken into account for computing the loss.
1341
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1342
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1343
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1344
+ are not taken into account for computing the loss.
1345
+ """
1346
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1347
+
1348
+ outputs = self.roberta(
1349
+ input_ids,
1350
+ attention_mask=attention_mask,
1351
+ token_type_ids=token_type_ids,
1352
+ position_ids=position_ids,
1353
+ head_mask=head_mask,
1354
+ inputs_embeds=inputs_embeds,
1355
+ output_attentions=output_attentions,
1356
+ output_hidden_states=output_hidden_states,
1357
+ return_dict=return_dict,
1358
+ )
1359
+
1360
+ sequence_output = outputs[0]
1361
+
1362
+ logits = self.qa_outputs(sequence_output)
1363
+ start_logits, end_logits = logits.split(1, dim=-1)
1364
+ start_logits = start_logits.squeeze(-1).contiguous()
1365
+ end_logits = end_logits.squeeze(-1).contiguous()
1366
+
1367
+ total_loss = None
1368
+ if start_positions is not None and end_positions is not None:
1369
+ # If we are on multi-GPU, split add a dimension
1370
+ if len(start_positions.size()) > 1:
1371
+ start_positions = start_positions.squeeze(-1)
1372
+ if len(end_positions.size()) > 1:
1373
+ end_positions = end_positions.squeeze(-1)
1374
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1375
+ ignored_index = start_logits.size(1)
1376
+ start_positions = start_positions.clamp(0, ignored_index)
1377
+ end_positions = end_positions.clamp(0, ignored_index)
1378
+
1379
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1380
+ start_loss = loss_fct(start_logits, start_positions)
1381
+ end_loss = loss_fct(end_logits, end_positions)
1382
+ total_loss = (start_loss + end_loss) / 2
1383
+
1384
+ if not return_dict:
1385
+ output = (start_logits, end_logits) + outputs[2:]
1386
+ return ((total_loss,) + output) if total_loss is not None else output
1387
+
1388
+ return QuestionAnsweringModelOutput(
1389
+ loss=total_loss,
1390
+ start_logits=start_logits,
1391
+ end_logits=end_logits,
1392
+ hidden_states=outputs.hidden_states,
1393
+ attentions=outputs.attentions,
1394
+ )
1395
+
1396
+
1397
+ @add_start_docstrings(
1398
+ """CamemBERT Model with a `language modeling` head on top for CLM fine-tuning.""", CAMEMBERT_START_DOCSTRING
1399
+ )
1400
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM with Roberta->Camembert, ROBERTA->CAMEMBERT, roberta-base->camembert-base
1401
+ class CamembertForCausalLM(CamembertPreTrainedModel):
1402
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
1403
+
1404
+ def __init__(self, config):
1405
+ super().__init__(config)
1406
+
1407
+ if not config.is_decoder:
1408
+ logger.warning("If you want to use `CamembertLMHeadModel` as a standalone, add `is_decoder=True.`")
1409
+
1410
+ self.roberta = CamembertModel(config, add_pooling_layer=False)
1411
+ self.lm_head = CamembertLMHead(config)
1412
+
1413
+ # Initialize weights and apply final processing
1414
+ self.post_init()
1415
+
1416
+ def get_output_embeddings(self):
1417
+ return self.lm_head.decoder
1418
+
1419
+ def set_output_embeddings(self, new_embeddings):
1420
+ self.lm_head.decoder = new_embeddings
1421
+
1422
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1423
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1424
+ def forward(
1425
+ self,
1426
+ input_ids: Optional[torch.LongTensor] = None,
1427
+ attention_mask: Optional[torch.FloatTensor] = None,
1428
+ token_type_ids: Optional[torch.LongTensor] = None,
1429
+ position_ids: Optional[torch.LongTensor] = None,
1430
+ head_mask: Optional[torch.FloatTensor] = None,
1431
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1432
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1433
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1434
+ labels: Optional[torch.LongTensor] = None,
1435
+ past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,
1436
+ use_cache: Optional[bool] = None,
1437
+ output_attentions: Optional[bool] = None,
1438
+ output_hidden_states: Optional[bool] = None,
1439
+ return_dict: Optional[bool] = None,
1440
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1441
+ r"""
1442
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1443
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1444
+ the model is configured as a decoder.
1445
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1446
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1447
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1448
+
1449
+ - 1 for tokens that are **not masked**,
1450
+ - 0 for tokens that are **masked**.
1451
+
1452
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1453
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1454
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1455
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1456
+ 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)`):
1457
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1458
+
1459
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1460
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1461
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1462
+ use_cache (`bool`, *optional*):
1463
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1464
+ `past_key_values`).
1465
+
1466
+ Returns:
1467
+
1468
+ Example:
1469
+
1470
+ ```python
1471
+ >>> from transformers import AutoTokenizer, CamembertForCausalLM, AutoConfig
1472
+ >>> import torch
1473
+
1474
+ >>> tokenizer = AutoTokenizer.from_pretrained("camembert-base")
1475
+ >>> config = AutoConfig.from_pretrained("camembert-base")
1476
+ >>> config.is_decoder = True
1477
+ >>> model = CamembertForCausalLM.from_pretrained("camembert-base", config=config)
1478
+
1479
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1480
+ >>> outputs = model(**inputs)
1481
+
1482
+ >>> prediction_logits = outputs.logits
1483
+ ```"""
1484
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1485
+ if labels is not None:
1486
+ use_cache = False
1487
+
1488
+ outputs = self.roberta(
1489
+ input_ids,
1490
+ attention_mask=attention_mask,
1491
+ token_type_ids=token_type_ids,
1492
+ position_ids=position_ids,
1493
+ head_mask=head_mask,
1494
+ inputs_embeds=inputs_embeds,
1495
+ encoder_hidden_states=encoder_hidden_states,
1496
+ encoder_attention_mask=encoder_attention_mask,
1497
+ past_key_values=past_key_values,
1498
+ use_cache=use_cache,
1499
+ output_attentions=output_attentions,
1500
+ output_hidden_states=output_hidden_states,
1501
+ return_dict=return_dict,
1502
+ )
1503
+
1504
+ sequence_output = outputs[0]
1505
+ prediction_scores = self.lm_head(sequence_output)
1506
+
1507
+ lm_loss = None
1508
+ if labels is not None:
1509
+ # move labels to correct device to enable model parallelism
1510
+ labels = labels.to(prediction_scores.device)
1511
+ # we are doing next-token prediction; shift prediction scores and input ids by one
1512
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
1513
+ labels = labels[:, 1:].contiguous()
1514
+ loss_fct = CrossEntropyLoss()
1515
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1516
+
1517
+ if not return_dict:
1518
+ output = (prediction_scores,) + outputs[2:]
1519
+ return ((lm_loss,) + output) if lm_loss is not None else output
1520
+
1521
+ return CausalLMOutputWithCrossAttentions(
1522
+ loss=lm_loss,
1523
+ logits=prediction_scores,
1524
+ past_key_values=outputs.past_key_values,
1525
+ hidden_states=outputs.hidden_states,
1526
+ attentions=outputs.attentions,
1527
+ cross_attentions=outputs.cross_attentions,
1528
+ )
1529
+
1530
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
1531
+ input_shape = input_ids.shape
1532
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1533
+ if attention_mask is None:
1534
+ attention_mask = input_ids.new_ones(input_shape)
1535
+
1536
+ # cut decoder_input_ids if past_key_values is used
1537
+ if past_key_values is not None:
1538
+ past_length = past_key_values[0][0].shape[2]
1539
+
1540
+ # Some generation methods already pass only the last input ID
1541
+ if input_ids.shape[1] > past_length:
1542
+ remove_prefix_length = past_length
1543
+ else:
1544
+ # Default to old behavior: keep only final ID
1545
+ remove_prefix_length = input_ids.shape[1] - 1
1546
+
1547
+ input_ids = input_ids[:, remove_prefix_length:]
1548
+
1549
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
1550
+
1551
+ def _reorder_cache(self, past_key_values, beam_idx):
1552
+ reordered_past = ()
1553
+ for layer_past in past_key_values:
1554
+ reordered_past += (
1555
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1556
+ )
1557
+ return reordered_past
1558
+
1559
+
1560
+ # Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
1561
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
1562
+ """
1563
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1564
+ are ignored. This is modified from fairseq's `utils.make_positions`.
1565
+
1566
+ Args:
1567
+ x: torch.Tensor x:
1568
+
1569
+ Returns: torch.Tensor
1570
+ """
1571
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1572
+ mask = input_ids.ne(padding_idx).int()
1573
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
1574
+ return incremental_indices.long() + padding_idx
evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/modeling_tf_camembert.py ADDED
@@ -0,0 +1,1793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ TF 2.0 CamemBERT model."""
17
+
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ import warnings
23
+ from typing import Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import tensorflow as tf
27
+
28
+ from ...activations_tf import get_tf_activation
29
+ from ...modeling_tf_outputs import (
30
+ TFBaseModelOutputWithPastAndCrossAttentions,
31
+ TFBaseModelOutputWithPoolingAndCrossAttentions,
32
+ TFCausalLMOutputWithCrossAttentions,
33
+ TFMaskedLMOutput,
34
+ TFMultipleChoiceModelOutput,
35
+ TFQuestionAnsweringModelOutput,
36
+ TFSequenceClassifierOutput,
37
+ TFTokenClassifierOutput,
38
+ )
39
+ from ...modeling_tf_utils import (
40
+ TFCausalLanguageModelingLoss,
41
+ TFMaskedLanguageModelingLoss,
42
+ TFModelInputType,
43
+ TFMultipleChoiceLoss,
44
+ TFPreTrainedModel,
45
+ TFQuestionAnsweringLoss,
46
+ TFSequenceClassificationLoss,
47
+ TFTokenClassificationLoss,
48
+ get_initializer,
49
+ keras_serializable,
50
+ unpack_inputs,
51
+ )
52
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
53
+ from ...utils import (
54
+ add_code_sample_docstrings,
55
+ add_start_docstrings,
56
+ add_start_docstrings_to_model_forward,
57
+ logging,
58
+ )
59
+ from .configuration_camembert import CamembertConfig
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+ _CHECKPOINT_FOR_DOC = "camembert-base"
65
+ _CONFIG_FOR_DOC = "CamembertConfig"
66
+
67
+ TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
68
+ # See all CamemBERT models at https://huggingface.co/models?filter=camembert
69
+ ]
70
+
71
+
72
+ CAMEMBERT_START_DOCSTRING = r"""
73
+
74
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
75
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
76
+ etc.)
77
+
78
+ This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
79
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
80
+ behavior.
81
+
82
+ <Tip>
83
+
84
+ TensorFlow models and layers in `transformers` accept two formats as input:
85
+
86
+ - having all inputs as keyword arguments (like PyTorch models), or
87
+ - having all inputs as a list, tuple or dict in the first positional argument.
88
+
89
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
90
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
91
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
92
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
93
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
94
+ positional argument:
95
+
96
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
97
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
98
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
99
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
100
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
101
+
102
+ Note that when creating models and layers with
103
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
104
+ about any of this, as you can just pass inputs like you would to any other Python function!
105
+
106
+ </Tip>
107
+
108
+ Parameters:
109
+ config ([`CamembertConfig`]): Model configuration class with all the parameters of the
110
+ model. Initializing with a config file does not load the weights associated with the model, only the
111
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
112
+ """
113
+
114
+ CAMEMBERT_INPUTS_DOCSTRING = r"""
115
+ Args:
116
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
117
+ Indices of input sequence tokens in the vocabulary.
118
+
119
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
120
+ [`PreTrainedTokenizer.encode`] for details.
121
+
122
+ [What are input IDs?](../glossary#input-ids)
123
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
124
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
125
+
126
+ - 1 for tokens that are **not masked**,
127
+ - 0 for tokens that are **masked**.
128
+
129
+ [What are attention masks?](../glossary#attention-mask)
130
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
131
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
132
+ 1]`:
133
+
134
+ - 0 corresponds to a *sentence A* token,
135
+ - 1 corresponds to a *sentence B* token.
136
+
137
+ [What are token type IDs?](../glossary#token-type-ids)
138
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
139
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
140
+ config.max_position_embeddings - 1]`.
141
+
142
+ [What are position IDs?](../glossary#position-ids)
143
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
144
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
145
+
146
+ - 1 indicates the head is **not masked**,
147
+ - 0 indicates the head is **masked**.
148
+
149
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
150
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
151
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
152
+ model's internal embedding lookup matrix.
153
+ output_attentions (`bool`, *optional*):
154
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
155
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
156
+ config will be used instead.
157
+ output_hidden_states (`bool`, *optional*):
158
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
159
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
160
+ used instead.
161
+ return_dict (`bool`, *optional*):
162
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
163
+ eager mode, in graph mode the value will always be set to True.
164
+ training (`bool`, *optional*, defaults to `False`):
165
+ Whether or not to use the model in training mode (some modules like dropout modules have different
166
+ behaviors between training and evaluation).
167
+ """
168
+
169
+
170
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaEmbeddings
171
+ class TFCamembertEmbeddings(tf.keras.layers.Layer):
172
+ """
173
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
174
+ """
175
+
176
+ def __init__(self, config, **kwargs):
177
+ super().__init__(**kwargs)
178
+
179
+ self.padding_idx = 1
180
+ self.config = config
181
+ self.hidden_size = config.hidden_size
182
+ self.max_position_embeddings = config.max_position_embeddings
183
+ self.initializer_range = config.initializer_range
184
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
185
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
186
+
187
+ def build(self, input_shape=None):
188
+ with tf.name_scope("word_embeddings"):
189
+ self.weight = self.add_weight(
190
+ name="weight",
191
+ shape=[self.config.vocab_size, self.hidden_size],
192
+ initializer=get_initializer(self.initializer_range),
193
+ )
194
+
195
+ with tf.name_scope("token_type_embeddings"):
196
+ self.token_type_embeddings = self.add_weight(
197
+ name="embeddings",
198
+ shape=[self.config.type_vocab_size, self.hidden_size],
199
+ initializer=get_initializer(self.initializer_range),
200
+ )
201
+
202
+ with tf.name_scope("position_embeddings"):
203
+ self.position_embeddings = self.add_weight(
204
+ name="embeddings",
205
+ shape=[self.max_position_embeddings, self.hidden_size],
206
+ initializer=get_initializer(self.initializer_range),
207
+ )
208
+
209
+ if self.built:
210
+ return
211
+ self.built = True
212
+ if getattr(self, "LayerNorm", None) is not None:
213
+ with tf.name_scope(self.LayerNorm.name):
214
+ self.LayerNorm.build([None, None, self.config.hidden_size])
215
+
216
+ def create_position_ids_from_input_ids(self, input_ids, past_key_values_length=0):
217
+ """
218
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
219
+ symbols are ignored. This is modified from fairseq's `utils.make_positions`.
220
+
221
+ Args:
222
+ input_ids: tf.Tensor
223
+ Returns: tf.Tensor
224
+ """
225
+ mask = tf.cast(tf.math.not_equal(input_ids, self.padding_idx), dtype=input_ids.dtype)
226
+ incremental_indices = (tf.math.cumsum(mask, axis=1) + past_key_values_length) * mask
227
+
228
+ return incremental_indices + self.padding_idx
229
+
230
+ def call(
231
+ self,
232
+ input_ids=None,
233
+ position_ids=None,
234
+ token_type_ids=None,
235
+ inputs_embeds=None,
236
+ past_key_values_length=0,
237
+ training=False,
238
+ ):
239
+ """
240
+ Applies embedding based on inputs tensor.
241
+
242
+ Returns:
243
+ final_embeddings (`tf.Tensor`): output embedding tensor.
244
+ """
245
+ assert not (input_ids is None and inputs_embeds is None)
246
+
247
+ if input_ids is not None:
248
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
249
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
250
+
251
+ input_shape = shape_list(inputs_embeds)[:-1]
252
+
253
+ if token_type_ids is None:
254
+ token_type_ids = tf.fill(dims=input_shape, value=0)
255
+
256
+ if position_ids is None:
257
+ if input_ids is not None:
258
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
259
+ position_ids = self.create_position_ids_from_input_ids(
260
+ input_ids=input_ids, past_key_values_length=past_key_values_length
261
+ )
262
+ else:
263
+ position_ids = tf.expand_dims(
264
+ tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0
265
+ )
266
+
267
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
268
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
269
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
270
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
271
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
272
+
273
+ return final_embeddings
274
+
275
+
276
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->Camembert
277
+ class TFCamembertPooler(tf.keras.layers.Layer):
278
+ def __init__(self, config: CamembertConfig, **kwargs):
279
+ super().__init__(**kwargs)
280
+
281
+ self.dense = tf.keras.layers.Dense(
282
+ units=config.hidden_size,
283
+ kernel_initializer=get_initializer(config.initializer_range),
284
+ activation="tanh",
285
+ name="dense",
286
+ )
287
+ self.config = config
288
+
289
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
290
+ # We "pool" the model by simply taking the hidden state corresponding
291
+ # to the first token.
292
+ first_token_tensor = hidden_states[:, 0]
293
+ pooled_output = self.dense(inputs=first_token_tensor)
294
+
295
+ return pooled_output
296
+
297
+ def build(self, input_shape=None):
298
+ if self.built:
299
+ return
300
+ self.built = True
301
+ if getattr(self, "dense", None) is not None:
302
+ with tf.name_scope(self.dense.name):
303
+ self.dense.build([None, None, self.config.hidden_size])
304
+
305
+
306
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfAttention with Bert->Camembert
307
+ class TFCamembertSelfAttention(tf.keras.layers.Layer):
308
+ def __init__(self, config: CamembertConfig, **kwargs):
309
+ super().__init__(**kwargs)
310
+
311
+ if config.hidden_size % config.num_attention_heads != 0:
312
+ raise ValueError(
313
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number "
314
+ f"of attention heads ({config.num_attention_heads})"
315
+ )
316
+
317
+ self.num_attention_heads = config.num_attention_heads
318
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
319
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
320
+ self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
321
+
322
+ self.query = tf.keras.layers.Dense(
323
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
324
+ )
325
+ self.key = tf.keras.layers.Dense(
326
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
327
+ )
328
+ self.value = tf.keras.layers.Dense(
329
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
330
+ )
331
+ self.dropout = tf.keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
332
+
333
+ self.is_decoder = config.is_decoder
334
+ self.config = config
335
+
336
+ def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
337
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
338
+ tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
339
+
340
+ # Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
341
+ return tf.transpose(tensor, perm=[0, 2, 1, 3])
342
+
343
+ def call(
344
+ self,
345
+ hidden_states: tf.Tensor,
346
+ attention_mask: tf.Tensor,
347
+ head_mask: tf.Tensor,
348
+ encoder_hidden_states: tf.Tensor,
349
+ encoder_attention_mask: tf.Tensor,
350
+ past_key_value: Tuple[tf.Tensor],
351
+ output_attentions: bool,
352
+ training: bool = False,
353
+ ) -> Tuple[tf.Tensor]:
354
+ batch_size = shape_list(hidden_states)[0]
355
+ mixed_query_layer = self.query(inputs=hidden_states)
356
+
357
+ # If this is instantiated as a cross-attention module, the keys
358
+ # and values come from an encoder; the attention mask needs to be
359
+ # such that the encoder's padding tokens are not attended to.
360
+ is_cross_attention = encoder_hidden_states is not None
361
+
362
+ if is_cross_attention and past_key_value is not None:
363
+ # reuse k,v, cross_attentions
364
+ key_layer = past_key_value[0]
365
+ value_layer = past_key_value[1]
366
+ attention_mask = encoder_attention_mask
367
+ elif is_cross_attention:
368
+ key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
369
+ value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
370
+ attention_mask = encoder_attention_mask
371
+ elif past_key_value is not None:
372
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
373
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
374
+ key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
375
+ value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
376
+ else:
377
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
378
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
379
+
380
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
381
+
382
+ if self.is_decoder:
383
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
384
+ # Further calls to cross_attention layer can then reuse all cross-attention
385
+ # key/value_states (first "if" case)
386
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
387
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
388
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
389
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
390
+ past_key_value = (key_layer, value_layer)
391
+
392
+ # Take the dot product between "query" and "key" to get the raw attention scores.
393
+ # (batch size, num_heads, seq_len_q, seq_len_k)
394
+ attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
395
+ dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
396
+ attention_scores = tf.divide(attention_scores, dk)
397
+
398
+ if attention_mask is not None:
399
+ # Apply the attention mask is (precomputed for all layers in TFCamembertModel call() function)
400
+ attention_scores = tf.add(attention_scores, attention_mask)
401
+
402
+ # Normalize the attention scores to probabilities.
403
+ attention_probs = stable_softmax(logits=attention_scores, axis=-1)
404
+
405
+ # This is actually dropping out entire tokens to attend to, which might
406
+ # seem a bit unusual, but is taken from the original Transformer paper.
407
+ attention_probs = self.dropout(inputs=attention_probs, training=training)
408
+
409
+ # Mask heads if we want to
410
+ if head_mask is not None:
411
+ attention_probs = tf.multiply(attention_probs, head_mask)
412
+
413
+ attention_output = tf.matmul(attention_probs, value_layer)
414
+ attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
415
+
416
+ # (batch_size, seq_len_q, all_head_size)
417
+ attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
418
+ outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
419
+
420
+ if self.is_decoder:
421
+ outputs = outputs + (past_key_value,)
422
+ return outputs
423
+
424
+ def build(self, input_shape=None):
425
+ if self.built:
426
+ return
427
+ self.built = True
428
+ if getattr(self, "query", None) is not None:
429
+ with tf.name_scope(self.query.name):
430
+ self.query.build([None, None, self.config.hidden_size])
431
+ if getattr(self, "key", None) is not None:
432
+ with tf.name_scope(self.key.name):
433
+ self.key.build([None, None, self.config.hidden_size])
434
+ if getattr(self, "value", None) is not None:
435
+ with tf.name_scope(self.value.name):
436
+ self.value.build([None, None, self.config.hidden_size])
437
+
438
+
439
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfOutput with Bert->Camembert
440
+ class TFCamembertSelfOutput(tf.keras.layers.Layer):
441
+ def __init__(self, config: CamembertConfig, **kwargs):
442
+ super().__init__(**kwargs)
443
+
444
+ self.dense = tf.keras.layers.Dense(
445
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
446
+ )
447
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
448
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
449
+ self.config = config
450
+
451
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
452
+ hidden_states = self.dense(inputs=hidden_states)
453
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
454
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
455
+
456
+ return hidden_states
457
+
458
+ def build(self, input_shape=None):
459
+ if self.built:
460
+ return
461
+ self.built = True
462
+ if getattr(self, "dense", None) is not None:
463
+ with tf.name_scope(self.dense.name):
464
+ self.dense.build([None, None, self.config.hidden_size])
465
+ if getattr(self, "LayerNorm", None) is not None:
466
+ with tf.name_scope(self.LayerNorm.name):
467
+ self.LayerNorm.build([None, None, self.config.hidden_size])
468
+
469
+
470
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertAttention with Bert->Camembert
471
+ class TFCamembertAttention(tf.keras.layers.Layer):
472
+ def __init__(self, config: CamembertConfig, **kwargs):
473
+ super().__init__(**kwargs)
474
+
475
+ self.self_attention = TFCamembertSelfAttention(config, name="self")
476
+ self.dense_output = TFCamembertSelfOutput(config, name="output")
477
+
478
+ def prune_heads(self, heads):
479
+ raise NotImplementedError
480
+
481
+ def call(
482
+ self,
483
+ input_tensor: tf.Tensor,
484
+ attention_mask: tf.Tensor,
485
+ head_mask: tf.Tensor,
486
+ encoder_hidden_states: tf.Tensor,
487
+ encoder_attention_mask: tf.Tensor,
488
+ past_key_value: Tuple[tf.Tensor],
489
+ output_attentions: bool,
490
+ training: bool = False,
491
+ ) -> Tuple[tf.Tensor]:
492
+ self_outputs = self.self_attention(
493
+ hidden_states=input_tensor,
494
+ attention_mask=attention_mask,
495
+ head_mask=head_mask,
496
+ encoder_hidden_states=encoder_hidden_states,
497
+ encoder_attention_mask=encoder_attention_mask,
498
+ past_key_value=past_key_value,
499
+ output_attentions=output_attentions,
500
+ training=training,
501
+ )
502
+ attention_output = self.dense_output(
503
+ hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
504
+ )
505
+ # add attentions (possibly with past_key_value) if we output them
506
+ outputs = (attention_output,) + self_outputs[1:]
507
+
508
+ return outputs
509
+
510
+ def build(self, input_shape=None):
511
+ if self.built:
512
+ return
513
+ self.built = True
514
+ if getattr(self, "self_attention", None) is not None:
515
+ with tf.name_scope(self.self_attention.name):
516
+ self.self_attention.build(None)
517
+ if getattr(self, "dense_output", None) is not None:
518
+ with tf.name_scope(self.dense_output.name):
519
+ self.dense_output.build(None)
520
+
521
+
522
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->Camembert
523
+ class TFCamembertIntermediate(tf.keras.layers.Layer):
524
+ def __init__(self, config: CamembertConfig, **kwargs):
525
+ super().__init__(**kwargs)
526
+
527
+ self.dense = tf.keras.layers.Dense(
528
+ units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
529
+ )
530
+
531
+ if isinstance(config.hidden_act, str):
532
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
533
+ else:
534
+ self.intermediate_act_fn = config.hidden_act
535
+ self.config = config
536
+
537
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
538
+ hidden_states = self.dense(inputs=hidden_states)
539
+ hidden_states = self.intermediate_act_fn(hidden_states)
540
+
541
+ return hidden_states
542
+
543
+ def build(self, input_shape=None):
544
+ if self.built:
545
+ return
546
+ self.built = True
547
+ if getattr(self, "dense", None) is not None:
548
+ with tf.name_scope(self.dense.name):
549
+ self.dense.build([None, None, self.config.hidden_size])
550
+
551
+
552
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertOutput with Bert->Camembert
553
+ class TFCamembertOutput(tf.keras.layers.Layer):
554
+ def __init__(self, config: CamembertConfig, **kwargs):
555
+ super().__init__(**kwargs)
556
+
557
+ self.dense = tf.keras.layers.Dense(
558
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
559
+ )
560
+ self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
561
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
562
+ self.config = config
563
+
564
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
565
+ hidden_states = self.dense(inputs=hidden_states)
566
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
567
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
568
+
569
+ return hidden_states
570
+
571
+ def build(self, input_shape=None):
572
+ if self.built:
573
+ return
574
+ self.built = True
575
+ if getattr(self, "dense", None) is not None:
576
+ with tf.name_scope(self.dense.name):
577
+ self.dense.build([None, None, self.config.intermediate_size])
578
+ if getattr(self, "LayerNorm", None) is not None:
579
+ with tf.name_scope(self.LayerNorm.name):
580
+ self.LayerNorm.build([None, None, self.config.hidden_size])
581
+
582
+
583
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertLayer with Bert->Camembert
584
+ class TFCamembertLayer(tf.keras.layers.Layer):
585
+ def __init__(self, config: CamembertConfig, **kwargs):
586
+ super().__init__(**kwargs)
587
+
588
+ self.attention = TFCamembertAttention(config, name="attention")
589
+ self.is_decoder = config.is_decoder
590
+ self.add_cross_attention = config.add_cross_attention
591
+ if self.add_cross_attention:
592
+ if not self.is_decoder:
593
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
594
+ self.crossattention = TFCamembertAttention(config, name="crossattention")
595
+ self.intermediate = TFCamembertIntermediate(config, name="intermediate")
596
+ self.bert_output = TFCamembertOutput(config, name="output")
597
+
598
+ def call(
599
+ self,
600
+ hidden_states: tf.Tensor,
601
+ attention_mask: tf.Tensor,
602
+ head_mask: tf.Tensor,
603
+ encoder_hidden_states: tf.Tensor | None,
604
+ encoder_attention_mask: tf.Tensor | None,
605
+ past_key_value: Tuple[tf.Tensor] | None,
606
+ output_attentions: bool,
607
+ training: bool = False,
608
+ ) -> Tuple[tf.Tensor]:
609
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
610
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
611
+ self_attention_outputs = self.attention(
612
+ input_tensor=hidden_states,
613
+ attention_mask=attention_mask,
614
+ head_mask=head_mask,
615
+ encoder_hidden_states=None,
616
+ encoder_attention_mask=None,
617
+ past_key_value=self_attn_past_key_value,
618
+ output_attentions=output_attentions,
619
+ training=training,
620
+ )
621
+ attention_output = self_attention_outputs[0]
622
+
623
+ # if decoder, the last output is tuple of self-attn cache
624
+ if self.is_decoder:
625
+ outputs = self_attention_outputs[1:-1]
626
+ present_key_value = self_attention_outputs[-1]
627
+ else:
628
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
629
+
630
+ cross_attn_present_key_value = None
631
+ if self.is_decoder and encoder_hidden_states is not None:
632
+ if not hasattr(self, "crossattention"):
633
+ raise ValueError(
634
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
635
+ " by setting `config.add_cross_attention=True`"
636
+ )
637
+
638
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
639
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
640
+ cross_attention_outputs = self.crossattention(
641
+ input_tensor=attention_output,
642
+ attention_mask=attention_mask,
643
+ head_mask=head_mask,
644
+ encoder_hidden_states=encoder_hidden_states,
645
+ encoder_attention_mask=encoder_attention_mask,
646
+ past_key_value=cross_attn_past_key_value,
647
+ output_attentions=output_attentions,
648
+ training=training,
649
+ )
650
+ attention_output = cross_attention_outputs[0]
651
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
652
+
653
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
654
+ cross_attn_present_key_value = cross_attention_outputs[-1]
655
+ present_key_value = present_key_value + cross_attn_present_key_value
656
+
657
+ intermediate_output = self.intermediate(hidden_states=attention_output)
658
+ layer_output = self.bert_output(
659
+ hidden_states=intermediate_output, input_tensor=attention_output, training=training
660
+ )
661
+ outputs = (layer_output,) + outputs # add attentions if we output them
662
+
663
+ # if decoder, return the attn key/values as the last output
664
+ if self.is_decoder:
665
+ outputs = outputs + (present_key_value,)
666
+
667
+ return outputs
668
+
669
+ def build(self, input_shape=None):
670
+ if self.built:
671
+ return
672
+ self.built = True
673
+ if getattr(self, "attention", None) is not None:
674
+ with tf.name_scope(self.attention.name):
675
+ self.attention.build(None)
676
+ if getattr(self, "intermediate", None) is not None:
677
+ with tf.name_scope(self.intermediate.name):
678
+ self.intermediate.build(None)
679
+ if getattr(self, "bert_output", None) is not None:
680
+ with tf.name_scope(self.bert_output.name):
681
+ self.bert_output.build(None)
682
+ if getattr(self, "crossattention", None) is not None:
683
+ with tf.name_scope(self.crossattention.name):
684
+ self.crossattention.build(None)
685
+
686
+
687
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertEncoder with Bert->Camembert
688
+ class TFCamembertEncoder(tf.keras.layers.Layer):
689
+ def __init__(self, config: CamembertConfig, **kwargs):
690
+ super().__init__(**kwargs)
691
+ self.config = config
692
+ self.layer = [TFCamembertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
693
+
694
+ def call(
695
+ self,
696
+ hidden_states: tf.Tensor,
697
+ attention_mask: tf.Tensor,
698
+ head_mask: tf.Tensor,
699
+ encoder_hidden_states: tf.Tensor | None,
700
+ encoder_attention_mask: tf.Tensor | None,
701
+ past_key_values: Tuple[Tuple[tf.Tensor]] | None,
702
+ use_cache: Optional[bool],
703
+ output_attentions: bool,
704
+ output_hidden_states: bool,
705
+ return_dict: bool,
706
+ training: bool = False,
707
+ ) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
708
+ all_hidden_states = () if output_hidden_states else None
709
+ all_attentions = () if output_attentions else None
710
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
711
+
712
+ next_decoder_cache = () if use_cache else None
713
+ for i, layer_module in enumerate(self.layer):
714
+ if output_hidden_states:
715
+ all_hidden_states = all_hidden_states + (hidden_states,)
716
+
717
+ past_key_value = past_key_values[i] if past_key_values is not None else None
718
+
719
+ layer_outputs = layer_module(
720
+ hidden_states=hidden_states,
721
+ attention_mask=attention_mask,
722
+ head_mask=head_mask[i],
723
+ encoder_hidden_states=encoder_hidden_states,
724
+ encoder_attention_mask=encoder_attention_mask,
725
+ past_key_value=past_key_value,
726
+ output_attentions=output_attentions,
727
+ training=training,
728
+ )
729
+ hidden_states = layer_outputs[0]
730
+
731
+ if use_cache:
732
+ next_decoder_cache += (layer_outputs[-1],)
733
+
734
+ if output_attentions:
735
+ all_attentions = all_attentions + (layer_outputs[1],)
736
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
737
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
738
+
739
+ # Add last layer
740
+ if output_hidden_states:
741
+ all_hidden_states = all_hidden_states + (hidden_states,)
742
+
743
+ if not return_dict:
744
+ return tuple(
745
+ v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
746
+ )
747
+
748
+ return TFBaseModelOutputWithPastAndCrossAttentions(
749
+ last_hidden_state=hidden_states,
750
+ past_key_values=next_decoder_cache,
751
+ hidden_states=all_hidden_states,
752
+ attentions=all_attentions,
753
+ cross_attentions=all_cross_attentions,
754
+ )
755
+
756
+ def build(self, input_shape=None):
757
+ if self.built:
758
+ return
759
+ self.built = True
760
+ if getattr(self, "layer", None) is not None:
761
+ for layer in self.layer:
762
+ with tf.name_scope(layer.name):
763
+ layer.build(None)
764
+
765
+
766
+ @keras_serializable
767
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaMainLayer with Roberta->Camembert
768
+ class TFCamembertMainLayer(tf.keras.layers.Layer):
769
+ config_class = CamembertConfig
770
+
771
+ def __init__(self, config, add_pooling_layer=True, **kwargs):
772
+ super().__init__(**kwargs)
773
+
774
+ self.config = config
775
+ self.is_decoder = config.is_decoder
776
+
777
+ self.num_hidden_layers = config.num_hidden_layers
778
+ self.initializer_range = config.initializer_range
779
+ self.output_attentions = config.output_attentions
780
+ self.output_hidden_states = config.output_hidden_states
781
+ self.return_dict = config.use_return_dict
782
+ self.encoder = TFCamembertEncoder(config, name="encoder")
783
+ self.pooler = TFCamembertPooler(config, name="pooler") if add_pooling_layer else None
784
+ # The embeddings must be the last declaration in order to follow the weights order
785
+ self.embeddings = TFCamembertEmbeddings(config, name="embeddings")
786
+
787
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.get_input_embeddings
788
+ def get_input_embeddings(self) -> tf.keras.layers.Layer:
789
+ return self.embeddings
790
+
791
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.set_input_embeddings
792
+ def set_input_embeddings(self, value: tf.Variable):
793
+ self.embeddings.weight = value
794
+ self.embeddings.vocab_size = shape_list(value)[0]
795
+
796
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer._prune_heads
797
+ def _prune_heads(self, heads_to_prune):
798
+ """
799
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
800
+ class PreTrainedModel
801
+ """
802
+ raise NotImplementedError
803
+
804
+ @unpack_inputs
805
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.call
806
+ def call(
807
+ self,
808
+ input_ids: TFModelInputType | None = None,
809
+ attention_mask: np.ndarray | tf.Tensor | None = None,
810
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
811
+ position_ids: np.ndarray | tf.Tensor | None = None,
812
+ head_mask: np.ndarray | tf.Tensor | None = None,
813
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
814
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
815
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
816
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
817
+ use_cache: Optional[bool] = None,
818
+ output_attentions: Optional[bool] = None,
819
+ output_hidden_states: Optional[bool] = None,
820
+ return_dict: Optional[bool] = None,
821
+ training: bool = False,
822
+ ) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:
823
+ if not self.config.is_decoder:
824
+ use_cache = False
825
+
826
+ if input_ids is not None and inputs_embeds is not None:
827
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
828
+ elif input_ids is not None:
829
+ input_shape = shape_list(input_ids)
830
+ elif inputs_embeds is not None:
831
+ input_shape = shape_list(inputs_embeds)[:-1]
832
+ else:
833
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
834
+
835
+ batch_size, seq_length = input_shape
836
+
837
+ if past_key_values is None:
838
+ past_key_values_length = 0
839
+ past_key_values = [None] * len(self.encoder.layer)
840
+ else:
841
+ past_key_values_length = shape_list(past_key_values[0][0])[-2]
842
+
843
+ if attention_mask is None:
844
+ attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
845
+
846
+ if token_type_ids is None:
847
+ token_type_ids = tf.fill(dims=input_shape, value=0)
848
+
849
+ embedding_output = self.embeddings(
850
+ input_ids=input_ids,
851
+ position_ids=position_ids,
852
+ token_type_ids=token_type_ids,
853
+ inputs_embeds=inputs_embeds,
854
+ past_key_values_length=past_key_values_length,
855
+ training=training,
856
+ )
857
+
858
+ # We create a 3D attention mask from a 2D tensor mask.
859
+ # Sizes are [batch_size, 1, 1, to_seq_length]
860
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
861
+ # this attention mask is more simple than the triangular masking of causal attention
862
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
863
+ attention_mask_shape = shape_list(attention_mask)
864
+
865
+ mask_seq_length = seq_length + past_key_values_length
866
+ # Copied from `modeling_tf_t5.py`
867
+ # Provided a padding mask of dimensions [batch_size, mask_seq_length]
868
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
869
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
870
+ if self.is_decoder:
871
+ seq_ids = tf.range(mask_seq_length)
872
+ causal_mask = tf.less_equal(
873
+ tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
874
+ seq_ids[None, :, None],
875
+ )
876
+ causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
877
+ extended_attention_mask = causal_mask * attention_mask[:, None, :]
878
+ attention_mask_shape = shape_list(extended_attention_mask)
879
+ extended_attention_mask = tf.reshape(
880
+ extended_attention_mask, (attention_mask_shape[0], 1, attention_mask_shape[1], attention_mask_shape[2])
881
+ )
882
+ if past_key_values[0] is not None:
883
+ # attention_mask needs to be sliced to the shape `[batch_size, 1, from_seq_length - cached_seq_length, to_seq_length]
884
+ extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
885
+ else:
886
+ extended_attention_mask = tf.reshape(
887
+ attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
888
+ )
889
+
890
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
891
+ # masked positions, this operation will create a tensor which is 0.0 for
892
+ # positions we want to attend and -10000.0 for masked positions.
893
+ # Since we are adding it to the raw scores before the softmax, this is
894
+ # effectively the same as removing these entirely.
895
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
896
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
897
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
898
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
899
+
900
+ # Copied from `modeling_tf_t5.py` with -1e9 -> -10000
901
+ if self.is_decoder and encoder_attention_mask is not None:
902
+ # If a 2D ou 3D attention mask is provided for the cross-attention
903
+ # we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
904
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
905
+ encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
906
+ num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
907
+ if num_dims_encoder_attention_mask == 3:
908
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
909
+ if num_dims_encoder_attention_mask == 2:
910
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
911
+
912
+ # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
913
+ # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
914
+ # encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
915
+ # tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
916
+
917
+ encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
918
+ else:
919
+ encoder_extended_attention_mask = None
920
+
921
+ # Prepare head mask if needed
922
+ # 1.0 in head_mask indicate we keep the head
923
+ # attention_probs has shape bsz x n_heads x N x N
924
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
925
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
926
+ if head_mask is not None:
927
+ raise NotImplementedError
928
+ else:
929
+ head_mask = [None] * self.config.num_hidden_layers
930
+
931
+ encoder_outputs = self.encoder(
932
+ hidden_states=embedding_output,
933
+ attention_mask=extended_attention_mask,
934
+ head_mask=head_mask,
935
+ encoder_hidden_states=encoder_hidden_states,
936
+ encoder_attention_mask=encoder_extended_attention_mask,
937
+ past_key_values=past_key_values,
938
+ use_cache=use_cache,
939
+ output_attentions=output_attentions,
940
+ output_hidden_states=output_hidden_states,
941
+ return_dict=return_dict,
942
+ training=training,
943
+ )
944
+
945
+ sequence_output = encoder_outputs[0]
946
+ pooled_output = self.pooler(hidden_states=sequence_output) if self.pooler is not None else None
947
+
948
+ if not return_dict:
949
+ return (
950
+ sequence_output,
951
+ pooled_output,
952
+ ) + encoder_outputs[1:]
953
+
954
+ return TFBaseModelOutputWithPoolingAndCrossAttentions(
955
+ last_hidden_state=sequence_output,
956
+ pooler_output=pooled_output,
957
+ past_key_values=encoder_outputs.past_key_values,
958
+ hidden_states=encoder_outputs.hidden_states,
959
+ attentions=encoder_outputs.attentions,
960
+ cross_attentions=encoder_outputs.cross_attentions,
961
+ )
962
+
963
+ def build(self, input_shape=None):
964
+ if self.built:
965
+ return
966
+ self.built = True
967
+ if getattr(self, "encoder", None) is not None:
968
+ with tf.name_scope(self.encoder.name):
969
+ self.encoder.build(None)
970
+ if getattr(self, "pooler", None) is not None:
971
+ with tf.name_scope(self.pooler.name):
972
+ self.pooler.build(None)
973
+ if getattr(self, "embeddings", None) is not None:
974
+ with tf.name_scope(self.embeddings.name):
975
+ self.embeddings.build(None)
976
+
977
+
978
+ class TFCamembertPreTrainedModel(TFPreTrainedModel):
979
+ """
980
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
981
+ models.
982
+ """
983
+
984
+ config_class = CamembertConfig
985
+ base_model_prefix = "roberta"
986
+
987
+
988
+ @add_start_docstrings(
989
+ "The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.",
990
+ CAMEMBERT_START_DOCSTRING,
991
+ )
992
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaModel with Roberta->Camembert, ROBERTA->CAMEMBERT
993
+ class TFCamembertModel(TFCamembertPreTrainedModel):
994
+ def __init__(self, config, *inputs, **kwargs):
995
+ super().__init__(config, *inputs, **kwargs)
996
+ self.roberta = TFCamembertMainLayer(config, name="roberta")
997
+
998
+ @unpack_inputs
999
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1000
+ @add_code_sample_docstrings(
1001
+ checkpoint=_CHECKPOINT_FOR_DOC,
1002
+ output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,
1003
+ config_class=_CONFIG_FOR_DOC,
1004
+ )
1005
+ def call(
1006
+ self,
1007
+ input_ids: TFModelInputType | None = None,
1008
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1009
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1010
+ position_ids: np.ndarray | tf.Tensor | None = None,
1011
+ head_mask: np.ndarray | tf.Tensor | None = None,
1012
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1013
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
1014
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1015
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1016
+ use_cache: Optional[bool] = None,
1017
+ output_attentions: Optional[bool] = None,
1018
+ output_hidden_states: Optional[bool] = None,
1019
+ return_dict: Optional[bool] = None,
1020
+ training: Optional[bool] = False,
1021
+ ) -> Union[Tuple, TFBaseModelOutputWithPoolingAndCrossAttentions]:
1022
+ r"""
1023
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1024
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1025
+ the model is configured as a decoder.
1026
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1027
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1028
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1029
+
1030
+ - 1 for tokens that are **not masked**,
1031
+ - 0 for tokens that are **masked**.
1032
+
1033
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
1034
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1035
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1036
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1037
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1038
+ use_cache (`bool`, *optional*, defaults to `True`):
1039
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1040
+ `past_key_values`). Set to `False` during training, `True` during generation
1041
+ """
1042
+ outputs = self.roberta(
1043
+ input_ids=input_ids,
1044
+ attention_mask=attention_mask,
1045
+ token_type_ids=token_type_ids,
1046
+ position_ids=position_ids,
1047
+ head_mask=head_mask,
1048
+ inputs_embeds=inputs_embeds,
1049
+ encoder_hidden_states=encoder_hidden_states,
1050
+ encoder_attention_mask=encoder_attention_mask,
1051
+ past_key_values=past_key_values,
1052
+ use_cache=use_cache,
1053
+ output_attentions=output_attentions,
1054
+ output_hidden_states=output_hidden_states,
1055
+ return_dict=return_dict,
1056
+ training=training,
1057
+ )
1058
+
1059
+ return outputs
1060
+
1061
+ def build(self, input_shape=None):
1062
+ if self.built:
1063
+ return
1064
+ self.built = True
1065
+ if getattr(self, "roberta", None) is not None:
1066
+ with tf.name_scope(self.roberta.name):
1067
+ self.roberta.build(None)
1068
+
1069
+
1070
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaLMHead with Roberta->Camembert
1071
+ class TFCamembertLMHead(tf.keras.layers.Layer):
1072
+ """Camembert Head for masked language modeling."""
1073
+
1074
+ def __init__(self, config, input_embeddings, **kwargs):
1075
+ super().__init__(**kwargs)
1076
+
1077
+ self.config = config
1078
+ self.hidden_size = config.hidden_size
1079
+ self.dense = tf.keras.layers.Dense(
1080
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
1081
+ )
1082
+ self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
1083
+ self.act = get_tf_activation("gelu")
1084
+
1085
+ # The output weights are the same as the input embeddings, but there is
1086
+ # an output-only bias for each token.
1087
+ self.decoder = input_embeddings
1088
+
1089
+ def build(self, input_shape=None):
1090
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
1091
+
1092
+ if self.built:
1093
+ return
1094
+ self.built = True
1095
+ if getattr(self, "dense", None) is not None:
1096
+ with tf.name_scope(self.dense.name):
1097
+ self.dense.build([None, None, self.config.hidden_size])
1098
+ if getattr(self, "layer_norm", None) is not None:
1099
+ with tf.name_scope(self.layer_norm.name):
1100
+ self.layer_norm.build([None, None, self.config.hidden_size])
1101
+
1102
+ def get_output_embeddings(self):
1103
+ return self.decoder
1104
+
1105
+ def set_output_embeddings(self, value):
1106
+ self.decoder.weight = value
1107
+ self.decoder.vocab_size = shape_list(value)[0]
1108
+
1109
+ def get_bias(self):
1110
+ return {"bias": self.bias}
1111
+
1112
+ def set_bias(self, value):
1113
+ self.bias = value["bias"]
1114
+ self.config.vocab_size = shape_list(value["bias"])[0]
1115
+
1116
+ def call(self, hidden_states):
1117
+ hidden_states = self.dense(hidden_states)
1118
+ hidden_states = self.act(hidden_states)
1119
+ hidden_states = self.layer_norm(hidden_states)
1120
+
1121
+ # project back to size of vocabulary with bias
1122
+ seq_length = shape_list(tensor=hidden_states)[1]
1123
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
1124
+ hidden_states = tf.matmul(a=hidden_states, b=self.decoder.weight, transpose_b=True)
1125
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
1126
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
1127
+
1128
+ return hidden_states
1129
+
1130
+
1131
+ @add_start_docstrings(
1132
+ """CamemBERT Model with a `language modeling` head on top.""",
1133
+ CAMEMBERT_START_DOCSTRING,
1134
+ )
1135
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT
1136
+ class TFCamembertForMaskedLM(TFCamembertPreTrainedModel, TFMaskedLanguageModelingLoss):
1137
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1138
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head.decoder.weight"]
1139
+
1140
+ def __init__(self, config, *inputs, **kwargs):
1141
+ super().__init__(config, *inputs, **kwargs)
1142
+
1143
+ self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
1144
+ self.lm_head = TFCamembertLMHead(config, self.roberta.embeddings, name="lm_head")
1145
+
1146
+ def get_lm_head(self):
1147
+ return self.lm_head
1148
+
1149
+ def get_prefix_bias_name(self):
1150
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1151
+ return self.name + "/" + self.lm_head.name
1152
+
1153
+ @unpack_inputs
1154
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1155
+ @add_code_sample_docstrings(
1156
+ checkpoint=_CHECKPOINT_FOR_DOC,
1157
+ output_type=TFMaskedLMOutput,
1158
+ config_class=_CONFIG_FOR_DOC,
1159
+ mask="<mask>",
1160
+ expected_output="' Paris'",
1161
+ expected_loss=0.1,
1162
+ )
1163
+ def call(
1164
+ self,
1165
+ input_ids: TFModelInputType | None = None,
1166
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1167
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1168
+ position_ids: np.ndarray | tf.Tensor | None = None,
1169
+ head_mask: np.ndarray | tf.Tensor | None = None,
1170
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1171
+ output_attentions: Optional[bool] = None,
1172
+ output_hidden_states: Optional[bool] = None,
1173
+ return_dict: Optional[bool] = None,
1174
+ labels: np.ndarray | tf.Tensor | None = None,
1175
+ training: Optional[bool] = False,
1176
+ ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
1177
+ r"""
1178
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1179
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1180
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1181
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1182
+ """
1183
+ outputs = self.roberta(
1184
+ input_ids,
1185
+ attention_mask=attention_mask,
1186
+ token_type_ids=token_type_ids,
1187
+ position_ids=position_ids,
1188
+ head_mask=head_mask,
1189
+ inputs_embeds=inputs_embeds,
1190
+ output_attentions=output_attentions,
1191
+ output_hidden_states=output_hidden_states,
1192
+ return_dict=return_dict,
1193
+ training=training,
1194
+ )
1195
+
1196
+ sequence_output = outputs[0]
1197
+ prediction_scores = self.lm_head(sequence_output)
1198
+
1199
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
1200
+
1201
+ if not return_dict:
1202
+ output = (prediction_scores,) + outputs[2:]
1203
+ return ((loss,) + output) if loss is not None else output
1204
+
1205
+ return TFMaskedLMOutput(
1206
+ loss=loss,
1207
+ logits=prediction_scores,
1208
+ hidden_states=outputs.hidden_states,
1209
+ attentions=outputs.attentions,
1210
+ )
1211
+
1212
+ def build(self, input_shape=None):
1213
+ if self.built:
1214
+ return
1215
+ self.built = True
1216
+ if getattr(self, "roberta", None) is not None:
1217
+ with tf.name_scope(self.roberta.name):
1218
+ self.roberta.build(None)
1219
+ if getattr(self, "lm_head", None) is not None:
1220
+ with tf.name_scope(self.lm_head.name):
1221
+ self.lm_head.build(None)
1222
+
1223
+
1224
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaClassificationHead
1225
+ class TFCamembertClassificationHead(tf.keras.layers.Layer):
1226
+ """Head for sentence-level classification tasks."""
1227
+
1228
+ def __init__(self, config, **kwargs):
1229
+ super().__init__(**kwargs)
1230
+ self.dense = tf.keras.layers.Dense(
1231
+ config.hidden_size,
1232
+ kernel_initializer=get_initializer(config.initializer_range),
1233
+ activation="tanh",
1234
+ name="dense",
1235
+ )
1236
+ classifier_dropout = (
1237
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1238
+ )
1239
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1240
+ self.out_proj = tf.keras.layers.Dense(
1241
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
1242
+ )
1243
+ self.config = config
1244
+
1245
+ def call(self, features, training=False):
1246
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
1247
+ x = self.dropout(x, training=training)
1248
+ x = self.dense(x)
1249
+ x = self.dropout(x, training=training)
1250
+ x = self.out_proj(x)
1251
+ return x
1252
+
1253
+ def build(self, input_shape=None):
1254
+ if self.built:
1255
+ return
1256
+ self.built = True
1257
+ if getattr(self, "dense", None) is not None:
1258
+ with tf.name_scope(self.dense.name):
1259
+ self.dense.build([None, None, self.config.hidden_size])
1260
+ if getattr(self, "out_proj", None) is not None:
1261
+ with tf.name_scope(self.out_proj.name):
1262
+ self.out_proj.build([None, None, self.config.hidden_size])
1263
+
1264
+
1265
+ @add_start_docstrings(
1266
+ """
1267
+ CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
1268
+ pooled output) e.g. for GLUE tasks.
1269
+ """,
1270
+ CAMEMBERT_START_DOCSTRING,
1271
+ )
1272
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForSequenceClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
1273
+ class TFCamembertForSequenceClassification(TFCamembertPreTrainedModel, TFSequenceClassificationLoss):
1274
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1275
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
1276
+
1277
+ def __init__(self, config, *inputs, **kwargs):
1278
+ super().__init__(config, *inputs, **kwargs)
1279
+ self.num_labels = config.num_labels
1280
+
1281
+ self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
1282
+ self.classifier = TFCamembertClassificationHead(config, name="classifier")
1283
+
1284
+ @unpack_inputs
1285
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1286
+ @add_code_sample_docstrings(
1287
+ checkpoint="cardiffnlp/twitter-roberta-base-emotion",
1288
+ output_type=TFSequenceClassifierOutput,
1289
+ config_class=_CONFIG_FOR_DOC,
1290
+ expected_output="'optimism'",
1291
+ expected_loss=0.08,
1292
+ )
1293
+ def call(
1294
+ self,
1295
+ input_ids: TFModelInputType | None = None,
1296
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1297
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1298
+ position_ids: np.ndarray | tf.Tensor | None = None,
1299
+ head_mask: np.ndarray | tf.Tensor | None = None,
1300
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1301
+ output_attentions: Optional[bool] = None,
1302
+ output_hidden_states: Optional[bool] = None,
1303
+ return_dict: Optional[bool] = None,
1304
+ labels: np.ndarray | tf.Tensor | None = None,
1305
+ training: Optional[bool] = False,
1306
+ ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
1307
+ r"""
1308
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1309
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1310
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1311
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1312
+ """
1313
+ outputs = self.roberta(
1314
+ input_ids,
1315
+ attention_mask=attention_mask,
1316
+ token_type_ids=token_type_ids,
1317
+ position_ids=position_ids,
1318
+ head_mask=head_mask,
1319
+ inputs_embeds=inputs_embeds,
1320
+ output_attentions=output_attentions,
1321
+ output_hidden_states=output_hidden_states,
1322
+ return_dict=return_dict,
1323
+ training=training,
1324
+ )
1325
+ sequence_output = outputs[0]
1326
+ logits = self.classifier(sequence_output, training=training)
1327
+
1328
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1329
+
1330
+ if not return_dict:
1331
+ output = (logits,) + outputs[2:]
1332
+ return ((loss,) + output) if loss is not None else output
1333
+
1334
+ return TFSequenceClassifierOutput(
1335
+ loss=loss,
1336
+ logits=logits,
1337
+ hidden_states=outputs.hidden_states,
1338
+ attentions=outputs.attentions,
1339
+ )
1340
+
1341
+ def build(self, input_shape=None):
1342
+ if self.built:
1343
+ return
1344
+ self.built = True
1345
+ if getattr(self, "roberta", None) is not None:
1346
+ with tf.name_scope(self.roberta.name):
1347
+ self.roberta.build(None)
1348
+ if getattr(self, "classifier", None) is not None:
1349
+ with tf.name_scope(self.classifier.name):
1350
+ self.classifier.build(None)
1351
+
1352
+
1353
+ @add_start_docstrings(
1354
+ """
1355
+ CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
1356
+ for Named-Entity-Recognition (NER) tasks.
1357
+ """,
1358
+ CAMEMBERT_START_DOCSTRING,
1359
+ )
1360
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForTokenClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
1361
+ class TFCamembertForTokenClassification(TFCamembertPreTrainedModel, TFTokenClassificationLoss):
1362
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1363
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
1364
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1365
+
1366
+ def __init__(self, config, *inputs, **kwargs):
1367
+ super().__init__(config, *inputs, **kwargs)
1368
+ self.num_labels = config.num_labels
1369
+
1370
+ self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
1371
+ classifier_dropout = (
1372
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1373
+ )
1374
+ self.dropout = tf.keras.layers.Dropout(classifier_dropout)
1375
+ self.classifier = tf.keras.layers.Dense(
1376
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1377
+ )
1378
+ self.config = config
1379
+
1380
+ @unpack_inputs
1381
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1382
+ @add_code_sample_docstrings(
1383
+ checkpoint="ydshieh/roberta-large-ner-english",
1384
+ output_type=TFTokenClassifierOutput,
1385
+ config_class=_CONFIG_FOR_DOC,
1386
+ expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']",
1387
+ expected_loss=0.01,
1388
+ )
1389
+ def call(
1390
+ self,
1391
+ input_ids: TFModelInputType | None = None,
1392
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1393
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1394
+ position_ids: np.ndarray | tf.Tensor | None = None,
1395
+ head_mask: np.ndarray | tf.Tensor | None = None,
1396
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1397
+ output_attentions: Optional[bool] = None,
1398
+ output_hidden_states: Optional[bool] = None,
1399
+ return_dict: Optional[bool] = None,
1400
+ labels: np.ndarray | tf.Tensor | None = None,
1401
+ training: Optional[bool] = False,
1402
+ ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
1403
+ r"""
1404
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1405
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1406
+ """
1407
+ outputs = self.roberta(
1408
+ input_ids,
1409
+ attention_mask=attention_mask,
1410
+ token_type_ids=token_type_ids,
1411
+ position_ids=position_ids,
1412
+ head_mask=head_mask,
1413
+ inputs_embeds=inputs_embeds,
1414
+ output_attentions=output_attentions,
1415
+ output_hidden_states=output_hidden_states,
1416
+ return_dict=return_dict,
1417
+ training=training,
1418
+ )
1419
+ sequence_output = outputs[0]
1420
+
1421
+ sequence_output = self.dropout(sequence_output, training=training)
1422
+ logits = self.classifier(sequence_output)
1423
+
1424
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1425
+
1426
+ if not return_dict:
1427
+ output = (logits,) + outputs[2:]
1428
+ return ((loss,) + output) if loss is not None else output
1429
+
1430
+ return TFTokenClassifierOutput(
1431
+ loss=loss,
1432
+ logits=logits,
1433
+ hidden_states=outputs.hidden_states,
1434
+ attentions=outputs.attentions,
1435
+ )
1436
+
1437
+ def build(self, input_shape=None):
1438
+ if self.built:
1439
+ return
1440
+ self.built = True
1441
+ if getattr(self, "roberta", None) is not None:
1442
+ with tf.name_scope(self.roberta.name):
1443
+ self.roberta.build(None)
1444
+ if getattr(self, "classifier", None) is not None:
1445
+ with tf.name_scope(self.classifier.name):
1446
+ self.classifier.build([None, None, self.config.hidden_size])
1447
+
1448
+
1449
+ @add_start_docstrings(
1450
+ """
1451
+ CamemBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1452
+ softmax) e.g. for RocStories/SWAG tasks.
1453
+ """,
1454
+ CAMEMBERT_START_DOCSTRING,
1455
+ )
1456
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForMultipleChoice with Roberta->Camembert, ROBERTA->CAMEMBERT
1457
+ class TFCamembertForMultipleChoice(TFCamembertPreTrainedModel, TFMultipleChoiceLoss):
1458
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1459
+ _keys_to_ignore_on_load_unexpected = [r"lm_head"]
1460
+ _keys_to_ignore_on_load_missing = [r"dropout"]
1461
+
1462
+ def __init__(self, config, *inputs, **kwargs):
1463
+ super().__init__(config, *inputs, **kwargs)
1464
+
1465
+ self.roberta = TFCamembertMainLayer(config, name="roberta")
1466
+ self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)
1467
+ self.classifier = tf.keras.layers.Dense(
1468
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1469
+ )
1470
+ self.config = config
1471
+
1472
+ @unpack_inputs
1473
+ @add_start_docstrings_to_model_forward(
1474
+ CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1475
+ )
1476
+ @add_code_sample_docstrings(
1477
+ checkpoint=_CHECKPOINT_FOR_DOC,
1478
+ output_type=TFMultipleChoiceModelOutput,
1479
+ config_class=_CONFIG_FOR_DOC,
1480
+ )
1481
+ def call(
1482
+ self,
1483
+ input_ids: TFModelInputType | None = None,
1484
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1485
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1486
+ position_ids: np.ndarray | tf.Tensor | None = None,
1487
+ head_mask: np.ndarray | tf.Tensor | None = None,
1488
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1489
+ output_attentions: Optional[bool] = None,
1490
+ output_hidden_states: Optional[bool] = None,
1491
+ return_dict: Optional[bool] = None,
1492
+ labels: np.ndarray | tf.Tensor | None = None,
1493
+ training: Optional[bool] = False,
1494
+ ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
1495
+ r"""
1496
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1497
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1498
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1499
+ """
1500
+
1501
+ if input_ids is not None:
1502
+ num_choices = shape_list(input_ids)[1]
1503
+ seq_length = shape_list(input_ids)[2]
1504
+ else:
1505
+ num_choices = shape_list(inputs_embeds)[1]
1506
+ seq_length = shape_list(inputs_embeds)[2]
1507
+
1508
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1509
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1510
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
1511
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
1512
+ outputs = self.roberta(
1513
+ flat_input_ids,
1514
+ flat_attention_mask,
1515
+ flat_token_type_ids,
1516
+ flat_position_ids,
1517
+ head_mask,
1518
+ inputs_embeds,
1519
+ output_attentions,
1520
+ output_hidden_states,
1521
+ return_dict=return_dict,
1522
+ training=training,
1523
+ )
1524
+ pooled_output = outputs[1]
1525
+ pooled_output = self.dropout(pooled_output, training=training)
1526
+ logits = self.classifier(pooled_output)
1527
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1528
+
1529
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1530
+
1531
+ if not return_dict:
1532
+ output = (reshaped_logits,) + outputs[2:]
1533
+ return ((loss,) + output) if loss is not None else output
1534
+
1535
+ return TFMultipleChoiceModelOutput(
1536
+ loss=loss,
1537
+ logits=reshaped_logits,
1538
+ hidden_states=outputs.hidden_states,
1539
+ attentions=outputs.attentions,
1540
+ )
1541
+
1542
+ def build(self, input_shape=None):
1543
+ if self.built:
1544
+ return
1545
+ self.built = True
1546
+ if getattr(self, "roberta", None) is not None:
1547
+ with tf.name_scope(self.roberta.name):
1548
+ self.roberta.build(None)
1549
+ if getattr(self, "classifier", None) is not None:
1550
+ with tf.name_scope(self.classifier.name):
1551
+ self.classifier.build([None, None, self.config.hidden_size])
1552
+
1553
+
1554
+ @add_start_docstrings(
1555
+ """
1556
+ CamemBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1557
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1558
+ """,
1559
+ CAMEMBERT_START_DOCSTRING,
1560
+ )
1561
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForQuestionAnswering with Roberta->Camembert, ROBERTA->CAMEMBERT
1562
+ class TFCamembertForQuestionAnswering(TFCamembertPreTrainedModel, TFQuestionAnsweringLoss):
1563
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1564
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
1565
+
1566
+ def __init__(self, config, *inputs, **kwargs):
1567
+ super().__init__(config, *inputs, **kwargs)
1568
+ self.num_labels = config.num_labels
1569
+
1570
+ self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
1571
+ self.qa_outputs = tf.keras.layers.Dense(
1572
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1573
+ )
1574
+ self.config = config
1575
+
1576
+ @unpack_inputs
1577
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1578
+ @add_code_sample_docstrings(
1579
+ checkpoint="ydshieh/roberta-base-squad2",
1580
+ output_type=TFQuestionAnsweringModelOutput,
1581
+ config_class=_CONFIG_FOR_DOC,
1582
+ expected_output="' puppet'",
1583
+ expected_loss=0.86,
1584
+ )
1585
+ def call(
1586
+ self,
1587
+ input_ids: TFModelInputType | None = None,
1588
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1589
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1590
+ position_ids: np.ndarray | tf.Tensor | None = None,
1591
+ head_mask: np.ndarray | tf.Tensor | None = None,
1592
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1593
+ output_attentions: Optional[bool] = None,
1594
+ output_hidden_states: Optional[bool] = None,
1595
+ return_dict: Optional[bool] = None,
1596
+ start_positions: np.ndarray | tf.Tensor | None = None,
1597
+ end_positions: np.ndarray | tf.Tensor | None = None,
1598
+ training: Optional[bool] = False,
1599
+ ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
1600
+ r"""
1601
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1602
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1603
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1604
+ are not taken into account for computing the loss.
1605
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1606
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1607
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1608
+ are not taken into account for computing the loss.
1609
+ """
1610
+ outputs = self.roberta(
1611
+ input_ids,
1612
+ attention_mask=attention_mask,
1613
+ token_type_ids=token_type_ids,
1614
+ position_ids=position_ids,
1615
+ head_mask=head_mask,
1616
+ inputs_embeds=inputs_embeds,
1617
+ output_attentions=output_attentions,
1618
+ output_hidden_states=output_hidden_states,
1619
+ return_dict=return_dict,
1620
+ training=training,
1621
+ )
1622
+ sequence_output = outputs[0]
1623
+
1624
+ logits = self.qa_outputs(sequence_output)
1625
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1626
+ start_logits = tf.squeeze(start_logits, axis=-1)
1627
+ end_logits = tf.squeeze(end_logits, axis=-1)
1628
+
1629
+ loss = None
1630
+ if start_positions is not None and end_positions is not None:
1631
+ labels = {"start_position": start_positions}
1632
+ labels["end_position"] = end_positions
1633
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1634
+
1635
+ if not return_dict:
1636
+ output = (start_logits, end_logits) + outputs[2:]
1637
+ return ((loss,) + output) if loss is not None else output
1638
+
1639
+ return TFQuestionAnsweringModelOutput(
1640
+ loss=loss,
1641
+ start_logits=start_logits,
1642
+ end_logits=end_logits,
1643
+ hidden_states=outputs.hidden_states,
1644
+ attentions=outputs.attentions,
1645
+ )
1646
+
1647
+ def build(self, input_shape=None):
1648
+ if self.built:
1649
+ return
1650
+ self.built = True
1651
+ if getattr(self, "roberta", None) is not None:
1652
+ with tf.name_scope(self.roberta.name):
1653
+ self.roberta.build(None)
1654
+ if getattr(self, "qa_outputs", None) is not None:
1655
+ with tf.name_scope(self.qa_outputs.name):
1656
+ self.qa_outputs.build([None, None, self.config.hidden_size])
1657
+
1658
+
1659
+ @add_start_docstrings(
1660
+ """CamemBERT Model with a `language modeling` head on top for CLM fine-tuning.""", CAMEMBERT_START_DOCSTRING
1661
+ )
1662
+ # Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForCausalLM with Roberta->Camembert, ROBERTA->CAMEMBERT
1663
+ class TFCamembertForCausalLM(TFCamembertPreTrainedModel, TFCausalLanguageModelingLoss):
1664
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
1665
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head.decoder.weight"]
1666
+
1667
+ def __init__(self, config: CamembertConfig, *inputs, **kwargs):
1668
+ super().__init__(config, *inputs, **kwargs)
1669
+
1670
+ if not config.is_decoder:
1671
+ logger.warning("If you want to use `TFCamembertLMHeadModel` as a standalone, add `is_decoder=True.`")
1672
+
1673
+ self.roberta = TFCamembertMainLayer(config, add_pooling_layer=False, name="roberta")
1674
+ self.lm_head = TFCamembertLMHead(config, input_embeddings=self.roberta.embeddings, name="lm_head")
1675
+
1676
+ def get_lm_head(self):
1677
+ return self.lm_head
1678
+
1679
+ def get_prefix_bias_name(self):
1680
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1681
+ return self.name + "/" + self.lm_head.name
1682
+
1683
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertLMHeadModel.prepare_inputs_for_generation
1684
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
1685
+ input_shape = input_ids.shape
1686
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1687
+ if attention_mask is None:
1688
+ attention_mask = tf.ones(input_shape)
1689
+
1690
+ # cut decoder_input_ids if past is used
1691
+ if past_key_values is not None:
1692
+ input_ids = input_ids[:, -1:]
1693
+
1694
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
1695
+
1696
+ @unpack_inputs
1697
+ @add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1698
+ @add_code_sample_docstrings(
1699
+ checkpoint=_CHECKPOINT_FOR_DOC,
1700
+ output_type=TFCausalLMOutputWithCrossAttentions,
1701
+ config_class=_CONFIG_FOR_DOC,
1702
+ )
1703
+ def call(
1704
+ self,
1705
+ input_ids: TFModelInputType | None = None,
1706
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1707
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1708
+ position_ids: np.ndarray | tf.Tensor | None = None,
1709
+ head_mask: np.ndarray | tf.Tensor | None = None,
1710
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1711
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
1712
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
1713
+ past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
1714
+ use_cache: Optional[bool] = None,
1715
+ output_attentions: Optional[bool] = None,
1716
+ output_hidden_states: Optional[bool] = None,
1717
+ return_dict: Optional[bool] = None,
1718
+ labels: np.ndarray | tf.Tensor | None = None,
1719
+ training: Optional[bool] = False,
1720
+ ) -> Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]:
1721
+ r"""
1722
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1723
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
1724
+ the model is configured as a decoder.
1725
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1726
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
1727
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1728
+
1729
+ - 1 for tokens that are **not masked**,
1730
+ - 0 for tokens that are **masked**.
1731
+
1732
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
1733
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
1734
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1735
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1736
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1737
+ use_cache (`bool`, *optional*, defaults to `True`):
1738
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1739
+ `past_key_values`). Set to `False` during training, `True` during generation
1740
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
1741
+ Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
1742
+ config.vocab_size - 1]`.
1743
+ """
1744
+ outputs = self.roberta(
1745
+ input_ids=input_ids,
1746
+ attention_mask=attention_mask,
1747
+ token_type_ids=token_type_ids,
1748
+ position_ids=position_ids,
1749
+ head_mask=head_mask,
1750
+ inputs_embeds=inputs_embeds,
1751
+ encoder_hidden_states=encoder_hidden_states,
1752
+ encoder_attention_mask=encoder_attention_mask,
1753
+ past_key_values=past_key_values,
1754
+ use_cache=use_cache,
1755
+ output_attentions=output_attentions,
1756
+ output_hidden_states=output_hidden_states,
1757
+ return_dict=return_dict,
1758
+ training=training,
1759
+ )
1760
+
1761
+ sequence_output = outputs[0]
1762
+ logits = self.lm_head(hidden_states=sequence_output, training=training)
1763
+ loss = None
1764
+
1765
+ if labels is not None:
1766
+ # shift labels to the left and cut last logit token
1767
+ shifted_logits = logits[:, :-1]
1768
+ labels = labels[:, 1:]
1769
+ loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)
1770
+
1771
+ if not return_dict:
1772
+ output = (logits,) + outputs[2:]
1773
+ return ((loss,) + output) if loss is not None else output
1774
+
1775
+ return TFCausalLMOutputWithCrossAttentions(
1776
+ loss=loss,
1777
+ logits=logits,
1778
+ past_key_values=outputs.past_key_values,
1779
+ hidden_states=outputs.hidden_states,
1780
+ attentions=outputs.attentions,
1781
+ cross_attentions=outputs.cross_attentions,
1782
+ )
1783
+
1784
+ def build(self, input_shape=None):
1785
+ if self.built:
1786
+ return
1787
+ self.built = True
1788
+ if getattr(self, "roberta", None) is not None:
1789
+ with tf.name_scope(self.roberta.name):
1790
+ self.roberta.build(None)
1791
+ if getattr(self, "lm_head", None) is not None:
1792
+ with tf.name_scope(self.lm_head.name):
1793
+ self.lm_head.build(None)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License
15
+ """ Tokenization classes for Camembert model."""
16
+
17
+
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ import sentencepiece as spm
23
+
24
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
31
+
32
+ PRETRAINED_VOCAB_FILES_MAP = {
33
+ "vocab_file": {
34
+ "camembert-base": "https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model",
35
+ }
36
+ }
37
+
38
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
39
+ "camembert-base": 512,
40
+ }
41
+
42
+ SPIECE_UNDERLINE = "▁"
43
+
44
+
45
+ class CamembertTokenizer(PreTrainedTokenizer):
46
+ """
47
+ Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Construct a CamemBERT tokenizer. Based on
48
+ [SentencePiece](https://github.com/google/sentencepiece).
49
+
50
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
51
+ this superclass for more information regarding those methods.
52
+
53
+ Args:
54
+ vocab_file (`str`):
55
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
56
+ contains the vocabulary necessary to instantiate a tokenizer.
57
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
58
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
59
+
60
+ <Tip>
61
+
62
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
63
+ sequence. The token used is the `cls_token`.
64
+
65
+ </Tip>
66
+
67
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
68
+ The end of sequence token.
69
+
70
+ <Tip>
71
+
72
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
73
+ The token used is the `sep_token`.
74
+
75
+ </Tip>
76
+
77
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
78
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
79
+ sequence classification or for a text and a question for question answering. It is also used as the last
80
+ token of a sequence built with special tokens.
81
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
82
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
83
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
84
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
85
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
86
+ token instead.
87
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
88
+ The token used for padding, for example when batching sequences of different lengths.
89
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
90
+ The token used for masking values. This is the token used when training this model with masked language
91
+ modeling. This is the token which the model will try to predict.
92
+ additional_special_tokens (`List[str]`, *optional*, defaults to `['<s>NOTUSED', '</s>NOTUSED', '<unk>NOTUSED']`):
93
+ Additional special tokens used by the tokenizer.
94
+ sp_model_kwargs (`dict`, *optional*):
95
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
96
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
97
+ to set:
98
+
99
+ - `enable_sampling`: Enable subword regularization.
100
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
101
+
102
+ - `nbest_size = {0,1}`: No sampling is performed.
103
+ - `nbest_size > 1`: samples from the nbest_size results.
104
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
105
+ using forward-filtering-and-backward-sampling algorithm.
106
+
107
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
108
+ BPE-dropout.
109
+
110
+ Attributes:
111
+ sp_model (`SentencePieceProcessor`):
112
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
113
+ """
114
+
115
+ vocab_files_names = VOCAB_FILES_NAMES
116
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
117
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
118
+ model_input_names = ["input_ids", "attention_mask"]
119
+
120
+ def __init__(
121
+ self,
122
+ vocab_file,
123
+ bos_token="<s>",
124
+ eos_token="</s>",
125
+ sep_token="</s>",
126
+ cls_token="<s>",
127
+ unk_token="<unk>",
128
+ pad_token="<pad>",
129
+ mask_token="<mask>",
130
+ additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED", "<unk>NOTUSED"],
131
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
132
+ **kwargs,
133
+ ) -> None:
134
+ # Mask token behave like a normal word, i.e. include the space before it
135
+ mask_token = (
136
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False, special=True)
137
+ if isinstance(mask_token, str)
138
+ else mask_token
139
+ )
140
+
141
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
142
+
143
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
144
+ self.sp_model.Load(str(vocab_file))
145
+ self.vocab_file = vocab_file
146
+
147
+ # HACK: These tokens were added by the author for an obscure reason as they were already part of the
148
+ # sentencepiece vocabulary (this is the case for <s> and </s> and <unk>).
149
+ # In this case it is recommended to properly set the tokens by hand.
150
+ self._added_tokens_decoder = {
151
+ 0: AddedToken("<s>NOTUSED", special=True),
152
+ 1: AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token,
153
+ 2: AddedToken("</s>NOTUSED", special=True),
154
+ 3: AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token,
155
+ 4: AddedToken("<unk>NOTUSED", special=True),
156
+ }
157
+
158
+ self.fairseq_offset = 4 # 3 tokens are newly added, but the offset starts from 4
159
+
160
+ # legacy: camemebert is a particular case were we have to make sure `"<unk>NOTUSED"` is here
161
+ if "added_tokens_decoder" in kwargs:
162
+ # this is the only class that requires this unfortunately.....
163
+ # the reason is that the fast version has a whole.
164
+ kwargs["added_tokens_decoder"].update(self._added_tokens_decoder)
165
+
166
+ super().__init__(
167
+ bos_token=bos_token,
168
+ eos_token=eos_token,
169
+ unk_token=unk_token,
170
+ sep_token=sep_token,
171
+ cls_token=cls_token,
172
+ pad_token=pad_token,
173
+ mask_token=mask_token,
174
+ additional_special_tokens=additional_special_tokens,
175
+ sp_model_kwargs=self.sp_model_kwargs,
176
+ **kwargs,
177
+ )
178
+
179
+ @property
180
+ def vocab_size(self):
181
+ # The length of the vocabulary without added tokens is len(self.sp_model) but the added tokens are added at the beginning.
182
+ return len(self.sp_model)
183
+
184
+ def get_vocab(self):
185
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.fairseq_offset)}
186
+ vocab.update(self.added_tokens_encoder)
187
+ return vocab
188
+
189
+ def _tokenize(self, text: str) -> List[str]:
190
+ return self.sp_model.encode(text, out_type=str)
191
+
192
+ def _convert_token_to_id(self, token):
193
+ """Converts a token (str) in an id using the vocab."""
194
+ # specifi to camembert, both 3 and 4 point to the unk token.
195
+ if self.sp_model.PieceToId(token) == 0:
196
+ # Convert sentence piece unk token to fairseq unk token index
197
+ return self.unk_token_id
198
+ return self.fairseq_offset + self.sp_model.PieceToId(token)
199
+
200
+ def _convert_id_to_token(self, index):
201
+ """Converts an index (integer) in a token (str) using the vocab."""
202
+ return self.sp_model.IdToPiece(index - self.fairseq_offset)
203
+
204
+ def convert_tokens_to_string(self, tokens):
205
+ """Converts a sequence of tokens (string) in a single string."""
206
+ # TODO decode outputs do not match between fast and slow
207
+ current_sub_tokens = []
208
+ out_string = ""
209
+ prev_is_special = False
210
+ for token in tokens:
211
+ # make sure that special tokens are not decoded using sentencepiece model
212
+ if token in self.all_special_tokens:
213
+ if not prev_is_special:
214
+ out_string += " "
215
+ out_string += self.sp_model.decode(current_sub_tokens) + token
216
+ prev_is_special = True
217
+ current_sub_tokens = []
218
+ else:
219
+ current_sub_tokens.append(token)
220
+ prev_is_special = False
221
+ out_string += self.sp_model.decode(current_sub_tokens)
222
+ return out_string.strip()
223
+
224
+ def __getstate__(self):
225
+ state = self.__dict__.copy()
226
+ state["sp_model"] = None
227
+ return state
228
+
229
+ def __setstate__(self, d):
230
+ self.__dict__ = d
231
+
232
+ # for backward compatibility
233
+ if not hasattr(self, "sp_model_kwargs"):
234
+ self.sp_model_kwargs = {}
235
+
236
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
237
+ self.sp_model.Load(self.vocab_file)
238
+
239
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
240
+ if not os.path.isdir(save_directory):
241
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
242
+ return
243
+ out_vocab_file = os.path.join(
244
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
245
+ )
246
+
247
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
248
+ copyfile(self.vocab_file, out_vocab_file)
249
+ elif not os.path.isfile(self.vocab_file):
250
+ with open(out_vocab_file, "wb") as fi:
251
+ content_spiece_model = self.sp_model.serialized_model_proto()
252
+ fi.write(content_spiece_model)
253
+
254
+ return (out_vocab_file,)
255
+
256
+ def build_inputs_with_special_tokens(
257
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
258
+ ) -> List[int]:
259
+ """
260
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
261
+ adding special tokens. An CamemBERT sequence has the following format:
262
+
263
+ - single sequence: `<s> X </s>`
264
+ - pair of sequences: `<s> A </s></s> B </s>`
265
+
266
+ Args:
267
+ token_ids_0 (`List[int]`):
268
+ List of IDs to which the special tokens will be added.
269
+ token_ids_1 (`List[int]`, *optional*):
270
+ Optional second list of IDs for sequence pairs.
271
+
272
+ Returns:
273
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
274
+ """
275
+
276
+ if token_ids_1 is None:
277
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
278
+ cls = [self.cls_token_id]
279
+ sep = [self.sep_token_id]
280
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
281
+
282
+ def get_special_tokens_mask(
283
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
284
+ ) -> List[int]:
285
+ """
286
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
287
+ special tokens using the tokenizer `prepare_for_model` method.
288
+
289
+ Args:
290
+ token_ids_0 (`List[int]`):
291
+ List of IDs.
292
+ token_ids_1 (`List[int]`, *optional*):
293
+ Optional second list of IDs for sequence pairs.
294
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
295
+ Whether or not the token list is already formatted with special tokens for the model.
296
+
297
+ Returns:
298
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
299
+ """
300
+ if already_has_special_tokens:
301
+ return super().get_special_tokens_mask(
302
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
303
+ )
304
+
305
+ if token_ids_1 is None:
306
+ return [1] + ([0] * len(token_ids_0)) + [1]
307
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
308
+
309
+ def create_token_type_ids_from_sequences(
310
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
311
+ ) -> List[int]:
312
+ """
313
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. CamemBERT, like
314
+ RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
315
+
316
+ Args:
317
+ token_ids_0 (`List[int]`):
318
+ List of IDs.
319
+ token_ids_1 (`List[int]`, *optional*):
320
+ Optional second list of IDs for sequence pairs.
321
+
322
+ Returns:
323
+ `List[int]`: List of zeros.
324
+ """
325
+ sep = [self.sep_token_id]
326
+ cls = [self.cls_token_id]
327
+
328
+ if token_ids_1 is None:
329
+ return len(cls + token_ids_0 + sep) * [0]
330
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__init__.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_tf_available,
21
+ is_tokenizers_available,
22
+ is_torch_available,
23
+ )
24
+
25
+
26
+ _import_structure = {
27
+ "configuration_layoutlm": ["LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMConfig", "LayoutLMOnnxConfig"],
28
+ "tokenization_layoutlm": ["LayoutLMTokenizer"],
29
+ }
30
+
31
+ try:
32
+ if not is_tokenizers_available():
33
+ raise OptionalDependencyNotAvailable()
34
+ except OptionalDependencyNotAvailable:
35
+ pass
36
+ else:
37
+ _import_structure["tokenization_layoutlm_fast"] = ["LayoutLMTokenizerFast"]
38
+
39
+ try:
40
+ if not is_torch_available():
41
+ raise OptionalDependencyNotAvailable()
42
+ except OptionalDependencyNotAvailable:
43
+ pass
44
+ else:
45
+ _import_structure["modeling_layoutlm"] = [
46
+ "LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST",
47
+ "LayoutLMForMaskedLM",
48
+ "LayoutLMForSequenceClassification",
49
+ "LayoutLMForTokenClassification",
50
+ "LayoutLMForQuestionAnswering",
51
+ "LayoutLMModel",
52
+ "LayoutLMPreTrainedModel",
53
+ ]
54
+
55
+ try:
56
+ if not is_tf_available():
57
+ raise OptionalDependencyNotAvailable()
58
+ except OptionalDependencyNotAvailable:
59
+ pass
60
+ else:
61
+ _import_structure["modeling_tf_layoutlm"] = [
62
+ "TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST",
63
+ "TFLayoutLMForMaskedLM",
64
+ "TFLayoutLMForSequenceClassification",
65
+ "TFLayoutLMForTokenClassification",
66
+ "TFLayoutLMForQuestionAnswering",
67
+ "TFLayoutLMMainLayer",
68
+ "TFLayoutLMModel",
69
+ "TFLayoutLMPreTrainedModel",
70
+ ]
71
+
72
+
73
+ if TYPE_CHECKING:
74
+ from .configuration_layoutlm import LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMConfig, LayoutLMOnnxConfig
75
+ from .tokenization_layoutlm import LayoutLMTokenizer
76
+
77
+ try:
78
+ if not is_tokenizers_available():
79
+ raise OptionalDependencyNotAvailable()
80
+ except OptionalDependencyNotAvailable:
81
+ pass
82
+ else:
83
+ from .tokenization_layoutlm_fast import LayoutLMTokenizerFast
84
+
85
+ try:
86
+ if not is_torch_available():
87
+ raise OptionalDependencyNotAvailable()
88
+ except OptionalDependencyNotAvailable:
89
+ pass
90
+ else:
91
+ from .modeling_layoutlm import (
92
+ LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
93
+ LayoutLMForMaskedLM,
94
+ LayoutLMForQuestionAnswering,
95
+ LayoutLMForSequenceClassification,
96
+ LayoutLMForTokenClassification,
97
+ LayoutLMModel,
98
+ LayoutLMPreTrainedModel,
99
+ )
100
+ try:
101
+ if not is_tf_available():
102
+ raise OptionalDependencyNotAvailable()
103
+ except OptionalDependencyNotAvailable:
104
+ pass
105
+ else:
106
+ from .modeling_tf_layoutlm import (
107
+ TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
108
+ TFLayoutLMForMaskedLM,
109
+ TFLayoutLMForQuestionAnswering,
110
+ TFLayoutLMForSequenceClassification,
111
+ TFLayoutLMForTokenClassification,
112
+ TFLayoutLMMainLayer,
113
+ TFLayoutLMModel,
114
+ TFLayoutLMPreTrainedModel,
115
+ )
116
+
117
+ else:
118
+ import sys
119
+
120
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__pycache__/configuration_layoutlm.cpython-310.pyc ADDED
Binary file (8.63 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__pycache__/modeling_tf_layoutlm.cpython-310.pyc ADDED
Binary file (50 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/__pycache__/tokenization_layoutlm_fast.cpython-310.pyc ADDED
Binary file (7.51 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/configuration_layoutlm.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2010, The Microsoft Research Asia LayoutLM Team authors
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
+ """ LayoutLM model configuration"""
16
+ from collections import OrderedDict
17
+ from typing import Any, List, Mapping, Optional
18
+
19
+ from ... import PretrainedConfig, PreTrainedTokenizer
20
+ from ...onnx import OnnxConfig, PatchingSpec
21
+ from ...utils import TensorType, is_torch_available, logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27
+ "microsoft/layoutlm-base-uncased": (
28
+ "https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/config.json"
29
+ ),
30
+ "microsoft/layoutlm-large-uncased": (
31
+ "https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/config.json"
32
+ ),
33
+ }
34
+
35
+
36
+ class LayoutLMConfig(PretrainedConfig):
37
+ r"""
38
+ This is the configuration class to store the configuration of a [`LayoutLMModel`]. It is used to instantiate a
39
+ LayoutLM model according to the specified arguments, defining the model architecture. Instantiating a configuration
40
+ with the defaults will yield a similar configuration to that of the LayoutLM
41
+ [microsoft/layoutlm-base-uncased](https://huggingface.co/microsoft/layoutlm-base-uncased) architecture.
42
+
43
+ Configuration objects inherit from [`BertConfig`] and can be used to control the model outputs. Read the
44
+ documentation from [`BertConfig`] for more information.
45
+
46
+
47
+ Args:
48
+ vocab_size (`int`, *optional*, defaults to 30522):
49
+ Vocabulary size of the LayoutLM model. Defines the different tokens that can be represented by the
50
+ *inputs_ids* passed to the forward method of [`LayoutLMModel`].
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"`, `"silu"` and `"gelu_new"` are supported.
62
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
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.1):
65
+ The dropout ratio for the attention probabilities.
66
+ max_position_embeddings (`int`, *optional*, defaults to 512):
67
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
68
+ just in case (e.g., 512 or 1024 or 2048).
69
+ type_vocab_size (`int`, *optional*, defaults to 2):
70
+ The vocabulary size of the `token_type_ids` passed into [`LayoutLMModel`].
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
74
+ The epsilon used by the layer normalization layers.
75
+ pad_token_id (`int`, *optional*, defaults to 0):
76
+ The value used to pad input_ids.
77
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
78
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
79
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
80
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
81
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
82
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
83
+ use_cache (`bool`, *optional*, defaults to `True`):
84
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
85
+ relevant if `config.is_decoder=True`.
86
+ max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
87
+ The maximum value that the 2D position embedding might ever used. Typically set this to something large
88
+ just in case (e.g., 1024).
89
+
90
+ Examples:
91
+
92
+ ```python
93
+ >>> from transformers import LayoutLMConfig, LayoutLMModel
94
+
95
+ >>> # Initializing a LayoutLM configuration
96
+ >>> configuration = LayoutLMConfig()
97
+
98
+ >>> # Initializing a model (with random weights) from the configuration
99
+ >>> model = LayoutLMModel(configuration)
100
+
101
+ >>> # Accessing the model configuration
102
+ >>> configuration = model.config
103
+ ```"""
104
+
105
+ model_type = "layoutlm"
106
+
107
+ def __init__(
108
+ self,
109
+ vocab_size=30522,
110
+ hidden_size=768,
111
+ num_hidden_layers=12,
112
+ num_attention_heads=12,
113
+ intermediate_size=3072,
114
+ hidden_act="gelu",
115
+ hidden_dropout_prob=0.1,
116
+ attention_probs_dropout_prob=0.1,
117
+ max_position_embeddings=512,
118
+ type_vocab_size=2,
119
+ initializer_range=0.02,
120
+ layer_norm_eps=1e-12,
121
+ pad_token_id=0,
122
+ position_embedding_type="absolute",
123
+ use_cache=True,
124
+ max_2d_position_embeddings=1024,
125
+ **kwargs,
126
+ ):
127
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
128
+ self.vocab_size = vocab_size
129
+ self.hidden_size = hidden_size
130
+ self.num_hidden_layers = num_hidden_layers
131
+ self.num_attention_heads = num_attention_heads
132
+ self.hidden_act = hidden_act
133
+ self.intermediate_size = intermediate_size
134
+ self.hidden_dropout_prob = hidden_dropout_prob
135
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
136
+ self.max_position_embeddings = max_position_embeddings
137
+ self.type_vocab_size = type_vocab_size
138
+ self.initializer_range = initializer_range
139
+ self.layer_norm_eps = layer_norm_eps
140
+ self.position_embedding_type = position_embedding_type
141
+ self.use_cache = use_cache
142
+ self.max_2d_position_embeddings = max_2d_position_embeddings
143
+
144
+
145
+ class LayoutLMOnnxConfig(OnnxConfig):
146
+ def __init__(
147
+ self,
148
+ config: PretrainedConfig,
149
+ task: str = "default",
150
+ patching_specs: List[PatchingSpec] = None,
151
+ ):
152
+ super().__init__(config, task=task, patching_specs=patching_specs)
153
+ self.max_2d_positions = config.max_2d_position_embeddings - 1
154
+
155
+ @property
156
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
157
+ return OrderedDict(
158
+ [
159
+ ("input_ids", {0: "batch", 1: "sequence"}),
160
+ ("bbox", {0: "batch", 1: "sequence"}),
161
+ ("attention_mask", {0: "batch", 1: "sequence"}),
162
+ ("token_type_ids", {0: "batch", 1: "sequence"}),
163
+ ]
164
+ )
165
+
166
+ def generate_dummy_inputs(
167
+ self,
168
+ tokenizer: PreTrainedTokenizer,
169
+ batch_size: int = -1,
170
+ seq_length: int = -1,
171
+ is_pair: bool = False,
172
+ framework: Optional[TensorType] = None,
173
+ ) -> Mapping[str, Any]:
174
+ """
175
+ Generate inputs to provide to the ONNX exporter for the specific framework
176
+
177
+ Args:
178
+ tokenizer: The tokenizer associated with this model configuration
179
+ batch_size: The batch size (int) to export the model for (-1 means dynamic axis)
180
+ seq_length: The sequence length (int) to export the model for (-1 means dynamic axis)
181
+ is_pair: Indicate if the input is a pair (sentence 1, sentence 2)
182
+ framework: The framework (optional) the tokenizer will generate tensor for
183
+
184
+ Returns:
185
+ Mapping[str, Tensor] holding the kwargs to provide to the model's forward function
186
+ """
187
+
188
+ input_dict = super().generate_dummy_inputs(
189
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
190
+ )
191
+
192
+ # Generate a dummy bbox
193
+ box = [48, 84, 73, 128]
194
+
195
+ if not framework == TensorType.PYTORCH:
196
+ raise NotImplementedError("Exporting LayoutLM to ONNX is currently only supported for PyTorch.")
197
+
198
+ if not is_torch_available():
199
+ raise ValueError("Cannot generate dummy inputs without PyTorch installed.")
200
+ import torch
201
+
202
+ batch_size, seq_length = input_dict["input_ids"].shape
203
+ input_dict["bbox"] = torch.tensor([*[box] * seq_length]).tile(batch_size, 1, 1)
204
+ return input_dict
evalkit_tf437/lib/python3.10/site-packages/transformers/models/layoutlm/tokenization_layoutlm_fast.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Microsoft Research Asia LayoutLM Team Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Tokenization class for model LayoutLM."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import normalizers
21
+
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_layoutlm import LayoutLMTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {
32
+ "vocab_file": {
33
+ "microsoft/layoutlm-base-uncased": (
34
+ "https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/vocab.txt"
35
+ ),
36
+ "microsoft/layoutlm-large-uncased": (
37
+ "https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/vocab.txt"
38
+ ),
39
+ },
40
+ "tokenizer_file": {
41
+ "microsoft/layoutlm-base-uncased": (
42
+ "https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/tokenizer.json"
43
+ ),
44
+ "microsoft/layoutlm-large-uncased": (
45
+ "https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/tokenizer.json"
46
+ ),
47
+ },
48
+ }
49
+
50
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
51
+ "microsoft/layoutlm-base-uncased": 512,
52
+ "microsoft/layoutlm-large-uncased": 512,
53
+ }
54
+
55
+ PRETRAINED_INIT_CONFIGURATION = {
56
+ "microsoft/layoutlm-base-uncased": {"do_lower_case": True},
57
+ "microsoft/layoutlm-large-uncased": {"do_lower_case": True},
58
+ }
59
+
60
+
61
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with Bert->LayoutLM,BERT->LayoutLM
62
+ class LayoutLMTokenizerFast(PreTrainedTokenizerFast):
63
+ r"""
64
+ Construct a "fast" LayoutLM tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
65
+
66
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
67
+ refer to this superclass for more information regarding those methods.
68
+
69
+ Args:
70
+ vocab_file (`str`):
71
+ File containing the vocabulary.
72
+ do_lower_case (`bool`, *optional*, defaults to `True`):
73
+ Whether or not to lowercase the input when tokenizing.
74
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
75
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
76
+ token instead.
77
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
78
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
79
+ sequence classification or for a text and a question for question answering. It is also used as the last
80
+ token of a sequence built with special tokens.
81
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
82
+ The token used for padding, for example when batching sequences of different lengths.
83
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
84
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
85
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
86
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
87
+ The token used for masking values. This is the token used when training this model with masked language
88
+ modeling. This is the token which the model will try to predict.
89
+ clean_text (`bool`, *optional*, defaults to `True`):
90
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
91
+ whitespaces by the classic one.
92
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
93
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
94
+ issue](https://github.com/huggingface/transformers/issues/328)).
95
+ strip_accents (`bool`, *optional*):
96
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
97
+ value for `lowercase` (as in the original LayoutLM).
98
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
99
+ The prefix for subwords.
100
+ """
101
+
102
+ vocab_files_names = VOCAB_FILES_NAMES
103
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
104
+ pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
105
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
106
+ slow_tokenizer_class = LayoutLMTokenizer
107
+
108
+ def __init__(
109
+ self,
110
+ vocab_file=None,
111
+ tokenizer_file=None,
112
+ do_lower_case=True,
113
+ unk_token="[UNK]",
114
+ sep_token="[SEP]",
115
+ pad_token="[PAD]",
116
+ cls_token="[CLS]",
117
+ mask_token="[MASK]",
118
+ tokenize_chinese_chars=True,
119
+ strip_accents=None,
120
+ **kwargs,
121
+ ):
122
+ super().__init__(
123
+ vocab_file,
124
+ tokenizer_file=tokenizer_file,
125
+ do_lower_case=do_lower_case,
126
+ unk_token=unk_token,
127
+ sep_token=sep_token,
128
+ pad_token=pad_token,
129
+ cls_token=cls_token,
130
+ mask_token=mask_token,
131
+ tokenize_chinese_chars=tokenize_chinese_chars,
132
+ strip_accents=strip_accents,
133
+ **kwargs,
134
+ )
135
+
136
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
137
+ if (
138
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
139
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
140
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
141
+ ):
142
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
143
+ normalizer_state["lowercase"] = do_lower_case
144
+ normalizer_state["strip_accents"] = strip_accents
145
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
146
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
147
+
148
+ self.do_lower_case = do_lower_case
149
+
150
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
151
+ """
152
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
153
+ adding special tokens. A LayoutLM sequence has the following format:
154
+
155
+ - single sequence: `[CLS] X [SEP]`
156
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
157
+
158
+ Args:
159
+ token_ids_0 (`List[int]`):
160
+ List of IDs to which the special tokens will be added.
161
+ token_ids_1 (`List[int]`, *optional*):
162
+ Optional second list of IDs for sequence pairs.
163
+
164
+ Returns:
165
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
166
+ """
167
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
168
+
169
+ if token_ids_1 is not None:
170
+ output += token_ids_1 + [self.sep_token_id]
171
+
172
+ return output
173
+
174
+ def create_token_type_ids_from_sequences(
175
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
176
+ ) -> List[int]:
177
+ """
178
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A LayoutLM sequence
179
+ pair mask has the following format:
180
+
181
+ ```
182
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
183
+ | first sequence | second sequence |
184
+ ```
185
+
186
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
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 [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
196
+ """
197
+ sep = [self.sep_token_id]
198
+ cls = [self.cls_token_id]
199
+ if token_ids_1 is None:
200
+ return len(cls + token_ids_0 + sep) * [0]
201
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
202
+
203
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
204
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
205
+ return tuple(files)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__init__.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_tf_available,
21
+ is_tokenizers_available,
22
+ is_torch_available,
23
+ )
24
+
25
+
26
+ _import_structure = {
27
+ "configuration_longformer": [
28
+ "LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
29
+ "LongformerConfig",
30
+ "LongformerOnnxConfig",
31
+ ],
32
+ "tokenization_longformer": ["LongformerTokenizer"],
33
+ }
34
+
35
+ try:
36
+ if not is_tokenizers_available():
37
+ raise OptionalDependencyNotAvailable()
38
+ except OptionalDependencyNotAvailable:
39
+ pass
40
+ else:
41
+ _import_structure["tokenization_longformer_fast"] = ["LongformerTokenizerFast"]
42
+
43
+ try:
44
+ if not is_torch_available():
45
+ raise OptionalDependencyNotAvailable()
46
+ except OptionalDependencyNotAvailable:
47
+ pass
48
+ else:
49
+ _import_structure["modeling_longformer"] = [
50
+ "LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
51
+ "LongformerForMaskedLM",
52
+ "LongformerForMultipleChoice",
53
+ "LongformerForQuestionAnswering",
54
+ "LongformerForSequenceClassification",
55
+ "LongformerForTokenClassification",
56
+ "LongformerModel",
57
+ "LongformerPreTrainedModel",
58
+ "LongformerSelfAttention",
59
+ ]
60
+
61
+ try:
62
+ if not is_tf_available():
63
+ raise OptionalDependencyNotAvailable()
64
+ except OptionalDependencyNotAvailable:
65
+ pass
66
+ else:
67
+ _import_structure["modeling_tf_longformer"] = [
68
+ "TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
69
+ "TFLongformerForMaskedLM",
70
+ "TFLongformerForMultipleChoice",
71
+ "TFLongformerForQuestionAnswering",
72
+ "TFLongformerForSequenceClassification",
73
+ "TFLongformerForTokenClassification",
74
+ "TFLongformerModel",
75
+ "TFLongformerPreTrainedModel",
76
+ "TFLongformerSelfAttention",
77
+ ]
78
+
79
+
80
+ if TYPE_CHECKING:
81
+ from .configuration_longformer import (
82
+ LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
83
+ LongformerConfig,
84
+ LongformerOnnxConfig,
85
+ )
86
+ from .tokenization_longformer import LongformerTokenizer
87
+
88
+ try:
89
+ if not is_tokenizers_available():
90
+ raise OptionalDependencyNotAvailable()
91
+ except OptionalDependencyNotAvailable:
92
+ pass
93
+ else:
94
+ from .tokenization_longformer_fast import LongformerTokenizerFast
95
+
96
+ try:
97
+ if not is_torch_available():
98
+ raise OptionalDependencyNotAvailable()
99
+ except OptionalDependencyNotAvailable:
100
+ pass
101
+ else:
102
+ from .modeling_longformer import (
103
+ LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
104
+ LongformerForMaskedLM,
105
+ LongformerForMultipleChoice,
106
+ LongformerForQuestionAnswering,
107
+ LongformerForSequenceClassification,
108
+ LongformerForTokenClassification,
109
+ LongformerModel,
110
+ LongformerPreTrainedModel,
111
+ LongformerSelfAttention,
112
+ )
113
+
114
+ try:
115
+ if not is_tf_available():
116
+ raise OptionalDependencyNotAvailable()
117
+ except OptionalDependencyNotAvailable:
118
+ pass
119
+ else:
120
+ from .modeling_tf_longformer import (
121
+ TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
122
+ TFLongformerForMaskedLM,
123
+ TFLongformerForMultipleChoice,
124
+ TFLongformerForQuestionAnswering,
125
+ TFLongformerForSequenceClassification,
126
+ TFLongformerForTokenClassification,
127
+ TFLongformerModel,
128
+ TFLongformerPreTrainedModel,
129
+ TFLongformerSelfAttention,
130
+ )
131
+
132
+ else:
133
+ import sys
134
+
135
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.02 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/configuration_longformer.cpython-310.pyc ADDED
Binary file (8.88 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/convert_longformer_original_pytorch_lightning_to_pytorch.cpython-310.pyc ADDED
Binary file (2.27 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/modeling_longformer.cpython-310.pyc ADDED
Binary file (77.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/modeling_tf_longformer.cpython-310.pyc ADDED
Binary file (84.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/__pycache__/tokenization_longformer.cpython-310.pyc ADDED
Binary file (16.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/configuration_longformer.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Allen Institute for AI team and 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
+ """ Longformer configuration"""
16
+ from collections import OrderedDict
17
+ from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...onnx import OnnxConfig
21
+ from ...utils import TensorType, logging
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from ...onnx.config import PatchingSpec
26
+ from ...tokenization_utils_base import PreTrainedTokenizerBase
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+ LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
32
+ "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json",
33
+ "allenai/longformer-large-4096": "https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json",
34
+ "allenai/longformer-large-4096-finetuned-triviaqa": (
35
+ "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"
36
+ ),
37
+ "allenai/longformer-base-4096-extra.pos.embd.only": (
38
+ "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"
39
+ ),
40
+ "allenai/longformer-large-4096-extra.pos.embd.only": (
41
+ "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"
42
+ ),
43
+ }
44
+
45
+
46
+ class LongformerConfig(PretrainedConfig):
47
+ r"""
48
+ This is the configuration class to store the configuration of a [`LongformerModel`] or a [`TFLongformerModel`]. It
49
+ is used to instantiate a Longformer model according to the specified arguments, defining the model architecture.
50
+
51
+ This is the configuration class to store the configuration of a [`LongformerModel`]. It is used to instantiate an
52
+ Longformer model according to the specified arguments, defining the model architecture. Instantiating a
53
+ configuration with the defaults will yield a similar configuration to that of the LongFormer
54
+ [allenai/longformer-base-4096](https://huggingface.co/allenai/longformer-base-4096) architecture with a sequence
55
+ length 4,096.
56
+
57
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
58
+ documentation from [`PretrainedConfig`] for more information.
59
+
60
+ Args:
61
+ vocab_size (`int`, *optional*, defaults to 30522):
62
+ Vocabulary size of the Longformer model. Defines the number of different tokens that can be represented by
63
+ the `inputs_ids` passed when calling [`LongformerModel`] or [`TFLongformerModel`].
64
+ hidden_size (`int`, *optional*, defaults to 768):
65
+ Dimensionality of the encoder layers and the pooler layer.
66
+ num_hidden_layers (`int`, *optional*, defaults to 12):
67
+ Number of hidden layers in the Transformer encoder.
68
+ num_attention_heads (`int`, *optional*, defaults to 12):
69
+ Number of attention heads for each attention layer in the Transformer encoder.
70
+ intermediate_size (`int`, *optional*, defaults to 3072):
71
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
72
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
73
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
74
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
75
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
76
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
77
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
78
+ The dropout ratio for the attention probabilities.
79
+ max_position_embeddings (`int`, *optional*, defaults to 512):
80
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
81
+ just in case (e.g., 512 or 1024 or 2048).
82
+ type_vocab_size (`int`, *optional*, defaults to 2):
83
+ The vocabulary size of the `token_type_ids` passed when calling [`LongformerModel`] or
84
+ [`TFLongformerModel`].
85
+ initializer_range (`float`, *optional*, defaults to 0.02):
86
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
87
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
88
+ The epsilon used by the layer normalization layers.
89
+ attention_window (`int` or `List[int]`, *optional*, defaults to 512):
90
+ Size of an attention window around each token. If an `int`, use the same size for all layers. To specify a
91
+ different window size for each layer, use a `List[int]` where `len(attention_window) == num_hidden_layers`.
92
+
93
+ Example:
94
+
95
+ ```python
96
+ >>> from transformers import LongformerConfig, LongformerModel
97
+
98
+ >>> # Initializing a Longformer configuration
99
+ >>> configuration = LongformerConfig()
100
+
101
+ >>> # Initializing a model from the configuration
102
+ >>> model = LongformerModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+
108
+ model_type = "longformer"
109
+
110
+ def __init__(
111
+ self,
112
+ attention_window: Union[List[int], int] = 512,
113
+ sep_token_id: int = 2,
114
+ pad_token_id: int = 1,
115
+ bos_token_id: int = 0,
116
+ eos_token_id: int = 2,
117
+ vocab_size: int = 30522,
118
+ hidden_size: int = 768,
119
+ num_hidden_layers: int = 12,
120
+ num_attention_heads: int = 12,
121
+ intermediate_size: int = 3072,
122
+ hidden_act: str = "gelu",
123
+ hidden_dropout_prob: float = 0.1,
124
+ attention_probs_dropout_prob: float = 0.1,
125
+ max_position_embeddings: int = 512,
126
+ type_vocab_size: int = 2,
127
+ initializer_range: float = 0.02,
128
+ layer_norm_eps: float = 1e-12,
129
+ onnx_export: bool = False,
130
+ **kwargs,
131
+ ):
132
+ """Constructs LongformerConfig."""
133
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
134
+
135
+ self.attention_window = attention_window
136
+ self.sep_token_id = sep_token_id
137
+ self.bos_token_id = bos_token_id
138
+ self.eos_token_id = eos_token_id
139
+ self.vocab_size = vocab_size
140
+ self.hidden_size = hidden_size
141
+ self.num_hidden_layers = num_hidden_layers
142
+ self.num_attention_heads = num_attention_heads
143
+ self.hidden_act = hidden_act
144
+ self.intermediate_size = intermediate_size
145
+ self.hidden_dropout_prob = hidden_dropout_prob
146
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
147
+ self.max_position_embeddings = max_position_embeddings
148
+ self.type_vocab_size = type_vocab_size
149
+ self.initializer_range = initializer_range
150
+ self.layer_norm_eps = layer_norm_eps
151
+ self.onnx_export = onnx_export
152
+
153
+
154
+ class LongformerOnnxConfig(OnnxConfig):
155
+ def __init__(self, config: "PretrainedConfig", task: str = "default", patching_specs: "List[PatchingSpec]" = None):
156
+ super().__init__(config, task, patching_specs)
157
+ config.onnx_export = True
158
+
159
+ @property
160
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
161
+ if self.task == "multiple-choice":
162
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
163
+ else:
164
+ dynamic_axis = {0: "batch", 1: "sequence"}
165
+ return OrderedDict(
166
+ [
167
+ ("input_ids", dynamic_axis),
168
+ ("attention_mask", dynamic_axis),
169
+ ("global_attention_mask", dynamic_axis),
170
+ ]
171
+ )
172
+
173
+ @property
174
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
175
+ outputs = super().outputs
176
+ if self.task == "default":
177
+ outputs["pooler_output"] = {0: "batch"}
178
+ return outputs
179
+
180
+ @property
181
+ def atol_for_validation(self) -> float:
182
+ """
183
+ What absolute tolerance value to use during model conversion validation.
184
+
185
+ Returns:
186
+ Float absolute tolerance value.
187
+ """
188
+ return 1e-4
189
+
190
+ @property
191
+ def default_onnx_opset(self) -> int:
192
+ # needs to be >= 14 to support tril operator
193
+ return max(super().default_onnx_opset, 14)
194
+
195
+ def generate_dummy_inputs(
196
+ self,
197
+ tokenizer: "PreTrainedTokenizerBase",
198
+ batch_size: int = -1,
199
+ seq_length: int = -1,
200
+ is_pair: bool = False,
201
+ framework: Optional[TensorType] = None,
202
+ ) -> Mapping[str, Any]:
203
+ inputs = super().generate_dummy_inputs(
204
+ preprocessor=tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
205
+ )
206
+ import torch
207
+
208
+ # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
209
+ # makes the export fail randomly
210
+ inputs["global_attention_mask"] = torch.zeros_like(inputs["input_ids"])
211
+ # make every second token global
212
+ inputs["global_attention_mask"][:, ::2] = 1
213
+
214
+ return inputs
evalkit_tf437/lib/python3.10/site-packages/transformers/models/longformer/tokenization_longformer_fast.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Allen Institute for AI team and 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
+ """Fast Tokenization classes for Longformer."""
16
+ import json
17
+ from typing import List, Optional, Tuple
18
+
19
+ from tokenizers import pre_tokenizers, processors
20
+
21
+ from ...tokenization_utils_base import AddedToken, BatchEncoding
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_longformer import LongformerTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+ PRETRAINED_VOCAB_FILES_MAP = {
32
+ "vocab_file": {
33
+ "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json",
34
+ "allenai/longformer-large-4096": (
35
+ "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json"
36
+ ),
37
+ "allenai/longformer-large-4096-finetuned-triviaqa": (
38
+ "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json"
39
+ ),
40
+ "allenai/longformer-base-4096-extra.pos.embd.only": (
41
+ "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json"
42
+ ),
43
+ "allenai/longformer-large-4096-extra.pos.embd.only": (
44
+ "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json"
45
+ ),
46
+ },
47
+ "merges_file": {
48
+ "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt",
49
+ "allenai/longformer-large-4096": (
50
+ "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt"
51
+ ),
52
+ "allenai/longformer-large-4096-finetuned-triviaqa": (
53
+ "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt"
54
+ ),
55
+ "allenai/longformer-base-4096-extra.pos.embd.only": (
56
+ "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt"
57
+ ),
58
+ "allenai/longformer-large-4096-extra.pos.embd.only": (
59
+ "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt"
60
+ ),
61
+ },
62
+ "tokenizer_file": {
63
+ "allenai/longformer-base-4096": (
64
+ "https://huggingface.co/allenai/longformer-base-4096/resolve/main/tokenizer.json"
65
+ ),
66
+ "allenai/longformer-large-4096": (
67
+ "https://huggingface.co/allenai/longformer-large-4096/resolve/main/tokenizer.json"
68
+ ),
69
+ "allenai/longformer-large-4096-finetuned-triviaqa": (
70
+ "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/tokenizer.json"
71
+ ),
72
+ "allenai/longformer-base-4096-extra.pos.embd.only": (
73
+ "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/tokenizer.json"
74
+ ),
75
+ "allenai/longformer-large-4096-extra.pos.embd.only": (
76
+ "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/tokenizer.json"
77
+ ),
78
+ },
79
+ }
80
+
81
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
82
+ "allenai/longformer-base-4096": 4096,
83
+ "allenai/longformer-large-4096": 4096,
84
+ "allenai/longformer-large-4096-finetuned-triviaqa": 4096,
85
+ "allenai/longformer-base-4096-extra.pos.embd.only": 4096,
86
+ "allenai/longformer-large-4096-extra.pos.embd.only": 4096,
87
+ }
88
+
89
+
90
+ # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast with roberta-base->allenai/longformer-base-4096, RoBERTa->Longformer all-casing, Roberta->Longformer
91
+ class LongformerTokenizerFast(PreTrainedTokenizerFast):
92
+ """
93
+ Construct a "fast" Longformer tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2
94
+ tokenizer, using byte-level Byte-Pair-Encoding.
95
+
96
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
97
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
98
+
99
+ ```python
100
+ >>> from transformers import LongformerTokenizerFast
101
+
102
+ >>> tokenizer = LongformerTokenizerFast.from_pretrained("allenai/longformer-base-4096")
103
+ >>> tokenizer("Hello world")["input_ids"]
104
+ [0, 31414, 232, 2]
105
+
106
+ >>> tokenizer(" Hello world")["input_ids"]
107
+ [0, 20920, 232, 2]
108
+ ```
109
+
110
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
111
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
112
+
113
+ <Tip>
114
+
115
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
116
+
117
+ </Tip>
118
+
119
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
120
+ refer to this superclass for more information regarding those methods.
121
+
122
+ Args:
123
+ vocab_file (`str`):
124
+ Path to the vocabulary file.
125
+ merges_file (`str`):
126
+ Path to the merges file.
127
+ errors (`str`, *optional*, defaults to `"replace"`):
128
+ Paradigm to follow when decoding bytes to UTF-8. See
129
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
130
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
131
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
132
+
133
+ <Tip>
134
+
135
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
136
+ sequence. The token used is the `cls_token`.
137
+
138
+ </Tip>
139
+
140
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
141
+ The end of sequence token.
142
+
143
+ <Tip>
144
+
145
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
146
+ The token used is the `sep_token`.
147
+
148
+ </Tip>
149
+
150
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
151
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
152
+ sequence classification or for a text and a question for question answering. It is also used as the last
153
+ token of a sequence built with special tokens.
154
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
155
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
156
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
157
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
158
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
159
+ token instead.
160
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
161
+ The token used for padding, for example when batching sequences of different lengths.
162
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
163
+ The token used for masking values. This is the token used when training this model with masked language
164
+ modeling. This is the token which the model will try to predict.
165
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
166
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
167
+ other word. (Longformer tokenizer detect beginning of words by the preceding space).
168
+ trim_offsets (`bool`, *optional*, defaults to `True`):
169
+ Whether the post processing step should trim offsets to avoid including whitespaces.
170
+ """
171
+
172
+ vocab_files_names = VOCAB_FILES_NAMES
173
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
174
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
175
+ model_input_names = ["input_ids", "attention_mask"]
176
+ slow_tokenizer_class = LongformerTokenizer
177
+
178
+ def __init__(
179
+ self,
180
+ vocab_file=None,
181
+ merges_file=None,
182
+ tokenizer_file=None,
183
+ errors="replace",
184
+ bos_token="<s>",
185
+ eos_token="</s>",
186
+ sep_token="</s>",
187
+ cls_token="<s>",
188
+ unk_token="<unk>",
189
+ pad_token="<pad>",
190
+ mask_token="<mask>",
191
+ add_prefix_space=False,
192
+ trim_offsets=True,
193
+ **kwargs,
194
+ ):
195
+ mask_token = (
196
+ AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
197
+ if isinstance(mask_token, str)
198
+ else mask_token
199
+ )
200
+ super().__init__(
201
+ vocab_file,
202
+ merges_file,
203
+ tokenizer_file=tokenizer_file,
204
+ errors=errors,
205
+ bos_token=bos_token,
206
+ eos_token=eos_token,
207
+ sep_token=sep_token,
208
+ cls_token=cls_token,
209
+ unk_token=unk_token,
210
+ pad_token=pad_token,
211
+ mask_token=mask_token,
212
+ add_prefix_space=add_prefix_space,
213
+ trim_offsets=trim_offsets,
214
+ **kwargs,
215
+ )
216
+
217
+ pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
218
+ if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
219
+ pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
220
+ pre_tok_state["add_prefix_space"] = add_prefix_space
221
+ self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
222
+
223
+ self.add_prefix_space = add_prefix_space
224
+
225
+ tokenizer_component = "post_processor"
226
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
227
+ if tokenizer_component_instance:
228
+ state = json.loads(tokenizer_component_instance.__getstate__())
229
+
230
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
231
+ if "sep" in state:
232
+ state["sep"] = tuple(state["sep"])
233
+ if "cls" in state:
234
+ state["cls"] = tuple(state["cls"])
235
+
236
+ changes_to_apply = False
237
+
238
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
239
+ state["add_prefix_space"] = add_prefix_space
240
+ changes_to_apply = True
241
+
242
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
243
+ state["trim_offsets"] = trim_offsets
244
+ changes_to_apply = True
245
+
246
+ if changes_to_apply:
247
+ component_class = getattr(processors, state.pop("type"))
248
+ new_value = component_class(**state)
249
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
250
+
251
+ @property
252
+ def mask_token(self) -> str:
253
+ """
254
+ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
255
+ having been set.
256
+
257
+ Longformer tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
258
+ comprise the space before the *<mask>*.
259
+ """
260
+ if self._mask_token is None:
261
+ if self.verbose:
262
+ logger.error("Using mask_token, but it is not set yet.")
263
+ return None
264
+ return str(self._mask_token)
265
+
266
+ @mask_token.setter
267
+ def mask_token(self, value):
268
+ """
269
+ Overriding the default behavior of the mask token to have it eat the space before it.
270
+
271
+ This is needed to preserve backward compatibility with all the previously used models based on Longformer.
272
+ """
273
+ # Mask token behave like a normal word, i.e. include the space before it
274
+ # So we set lstrip to True
275
+ value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
276
+ self._mask_token = value
277
+
278
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
279
+ is_split_into_words = kwargs.get("is_split_into_words", False)
280
+ assert self.add_prefix_space or not is_split_into_words, (
281
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
282
+ "to use it with pretokenized inputs."
283
+ )
284
+
285
+ return super()._batch_encode_plus(*args, **kwargs)
286
+
287
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
288
+ is_split_into_words = kwargs.get("is_split_into_words", False)
289
+
290
+ assert self.add_prefix_space or not is_split_into_words, (
291
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
292
+ "to use it with pretokenized inputs."
293
+ )
294
+
295
+ return super()._encode_plus(*args, **kwargs)
296
+
297
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
298
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
299
+ return tuple(files)
300
+
301
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
302
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
303
+ if token_ids_1 is None:
304
+ return output
305
+
306
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
307
+
308
+ def create_token_type_ids_from_sequences(
309
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
310
+ ) -> List[int]:
311
+ """
312
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Longformer does not
313
+ make use of token type ids, therefore a list of zeros is returned.
314
+
315
+ Args:
316
+ token_ids_0 (`List[int]`):
317
+ List of IDs.
318
+ token_ids_1 (`List[int]`, *optional*):
319
+ Optional second list of IDs for sequence pairs.
320
+
321
+ Returns:
322
+ `List[int]`: List of zeros.
323
+ """
324
+ sep = [self.sep_token_id]
325
+ cls = [self.cls_token_id]
326
+
327
+ if token_ids_1 is None:
328
+ return len(cls + token_ids_0 + sep) * [0]
329
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
evalkit_tf437/lib/python3.10/site-packages/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import argparse
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from transformers import MBartConfig, MBartForConditionalGeneration
21
+
22
+
23
+ def remove_ignore_keys_(state_dict):
24
+ ignore_keys = [
25
+ "encoder.version",
26
+ "decoder.version",
27
+ "model.encoder.version",
28
+ "model.decoder.version",
29
+ "_float_tensor",
30
+ "decoder.output_projection.weight",
31
+ ]
32
+ for k in ignore_keys:
33
+ state_dict.pop(k, None)
34
+
35
+
36
+ def make_linear_from_emb(emb):
37
+ vocab_size, emb_size = emb.weight.shape
38
+ lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
39
+ lin_layer.weight.data = emb.weight.data
40
+ return lin_layer
41
+
42
+
43
+ def convert_fairseq_mbart_checkpoint_from_disk(
44
+ checkpoint_path, hf_config_path="facebook/mbart-large-en-ro", finetuned=False, mbart_50=False
45
+ ):
46
+ state_dict = torch.load(checkpoint_path, map_location="cpu")["model"]
47
+ remove_ignore_keys_(state_dict)
48
+ vocab_size = state_dict["encoder.embed_tokens.weight"].shape[0]
49
+
50
+ mbart_config = MBartConfig.from_pretrained(hf_config_path, vocab_size=vocab_size)
51
+ if mbart_50 and finetuned:
52
+ mbart_config.activation_function = "relu"
53
+
54
+ state_dict["shared.weight"] = state_dict["decoder.embed_tokens.weight"]
55
+ model = MBartForConditionalGeneration(mbart_config)
56
+ model.model.load_state_dict(state_dict)
57
+
58
+ if finetuned:
59
+ model.lm_head = make_linear_from_emb(model.model.shared)
60
+
61
+ return model
62
+
63
+
64
+ if __name__ == "__main__":
65
+ parser = argparse.ArgumentParser()
66
+ # Required parameters
67
+ parser.add_argument(
68
+ "fairseq_path", type=str, help="bart.large, bart.large.cnn or a path to a model.pt on local filesystem."
69
+ )
70
+ parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
71
+ parser.add_argument(
72
+ "--hf_config",
73
+ default="facebook/mbart-large-cc25",
74
+ type=str,
75
+ help="Which huggingface architecture to use: mbart-large",
76
+ )
77
+ parser.add_argument("--mbart_50", action="store_true", help="whether the model is mMART-50 checkpoint")
78
+ parser.add_argument("--finetuned", action="store_true", help="whether the model is a fine-tuned checkpoint")
79
+ args = parser.parse_args()
80
+ model = convert_fairseq_mbart_checkpoint_from_disk(
81
+ args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_50=args.mbart_50
82
+ )
83
+ model.save_pretrained(args.pytorch_dump_folder_path)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/mbart50/__init__.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available
17
+
18
+
19
+ _import_structure = {}
20
+
21
+ try:
22
+ if not is_sentencepiece_available():
23
+ raise OptionalDependencyNotAvailable()
24
+ except OptionalDependencyNotAvailable:
25
+ pass
26
+ else:
27
+ _import_structure["tokenization_mbart50"] = ["MBart50Tokenizer"]
28
+
29
+ try:
30
+ if not is_tokenizers_available():
31
+ raise OptionalDependencyNotAvailable()
32
+ except OptionalDependencyNotAvailable:
33
+ pass
34
+ else:
35
+ _import_structure["tokenization_mbart50_fast"] = ["MBart50TokenizerFast"]
36
+
37
+
38
+ if TYPE_CHECKING:
39
+ try:
40
+ if not is_sentencepiece_available():
41
+ raise OptionalDependencyNotAvailable()
42
+ except OptionalDependencyNotAvailable:
43
+ pass
44
+ else:
45
+ from .tokenization_mbart50 import MBart50Tokenizer
46
+
47
+ try:
48
+ if not is_tokenizers_available():
49
+ raise OptionalDependencyNotAvailable()
50
+ except OptionalDependencyNotAvailable:
51
+ pass
52
+ else:
53
+ from .tokenization_mbart50_fast import MBart50TokenizerFast
54
+
55
+ else:
56
+ import sys
57
+
58
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/mbart50/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (913 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/musicgen/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__init__.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_flax_available,
20
+ is_tf_available,
21
+ is_torch_available,
22
+ is_vision_available,
23
+ )
24
+
25
+
26
+ _import_structure = {"configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig", "ViTOnnxConfig"]}
27
+
28
+ try:
29
+ if not is_vision_available():
30
+ raise OptionalDependencyNotAvailable()
31
+ except OptionalDependencyNotAvailable:
32
+ pass
33
+ else:
34
+ _import_structure["feature_extraction_vit"] = ["ViTFeatureExtractor"]
35
+ _import_structure["image_processing_vit"] = ["ViTImageProcessor"]
36
+
37
+ try:
38
+ if not is_torch_available():
39
+ raise OptionalDependencyNotAvailable()
40
+ except OptionalDependencyNotAvailable:
41
+ pass
42
+ else:
43
+ _import_structure["modeling_vit"] = [
44
+ "VIT_PRETRAINED_MODEL_ARCHIVE_LIST",
45
+ "ViTForImageClassification",
46
+ "ViTForMaskedImageModeling",
47
+ "ViTModel",
48
+ "ViTPreTrainedModel",
49
+ ]
50
+
51
+ try:
52
+ if not is_tf_available():
53
+ raise OptionalDependencyNotAvailable()
54
+ except OptionalDependencyNotAvailable:
55
+ pass
56
+ else:
57
+ _import_structure["modeling_tf_vit"] = [
58
+ "TFViTForImageClassification",
59
+ "TFViTModel",
60
+ "TFViTPreTrainedModel",
61
+ ]
62
+
63
+ try:
64
+ if not is_flax_available():
65
+ raise OptionalDependencyNotAvailable()
66
+ except OptionalDependencyNotAvailable:
67
+ pass
68
+ else:
69
+ _import_structure["modeling_flax_vit"] = [
70
+ "FlaxViTForImageClassification",
71
+ "FlaxViTModel",
72
+ "FlaxViTPreTrainedModel",
73
+ ]
74
+
75
+ if TYPE_CHECKING:
76
+ from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig
77
+
78
+ try:
79
+ if not is_vision_available():
80
+ raise OptionalDependencyNotAvailable()
81
+ except OptionalDependencyNotAvailable:
82
+ pass
83
+ else:
84
+ from .feature_extraction_vit import ViTFeatureExtractor
85
+ from .image_processing_vit import ViTImageProcessor
86
+
87
+ try:
88
+ if not is_torch_available():
89
+ raise OptionalDependencyNotAvailable()
90
+ except OptionalDependencyNotAvailable:
91
+ pass
92
+ else:
93
+ from .modeling_vit import (
94
+ VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
95
+ ViTForImageClassification,
96
+ ViTForMaskedImageModeling,
97
+ ViTModel,
98
+ ViTPreTrainedModel,
99
+ )
100
+
101
+ try:
102
+ if not is_tf_available():
103
+ raise OptionalDependencyNotAvailable()
104
+ except OptionalDependencyNotAvailable:
105
+ pass
106
+ else:
107
+ from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel
108
+
109
+ try:
110
+ if not is_flax_available():
111
+ raise OptionalDependencyNotAvailable()
112
+ except OptionalDependencyNotAvailable:
113
+ pass
114
+ else:
115
+ from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel
116
+
117
+
118
+ else:
119
+ import sys
120
+
121
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.78 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__pycache__/feature_extraction_vit.cpython-310.pyc ADDED
Binary file (979 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/__pycache__/modeling_flax_vit.cpython-310.pyc ADDED
Binary file (19.8 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/configuration_vit.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI 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
+ """ ViT model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import 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
+ VIT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
30
+ "google/vit-base-patch16-224": "https://huggingface.co/vit-base-patch16-224/resolve/main/config.json",
31
+ # See all ViT models at https://huggingface.co/models?filter=vit
32
+ }
33
+
34
+
35
+ class ViTConfig(PretrainedConfig):
36
+ r"""
37
+ This is the configuration class to store the configuration of a [`ViTModel`]. It is used to instantiate an ViT
38
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
39
+ defaults will yield a similar configuration to that of the ViT
40
+ [google/vit-base-patch16-224](https://huggingface.co/google/vit-base-patch16-224) architecture.
41
+
42
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
43
+ documentation from [`PretrainedConfig`] for more information.
44
+
45
+
46
+ Args:
47
+ hidden_size (`int`, *optional*, defaults to 768):
48
+ Dimensionality of the encoder layers and the pooler layer.
49
+ num_hidden_layers (`int`, *optional*, defaults to 12):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 12):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ intermediate_size (`int`, *optional*, defaults to 3072):
54
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
56
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
57
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
58
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
59
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
60
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the attention probabilities.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
65
+ The epsilon used by the layer normalization layers.
66
+ image_size (`int`, *optional*, defaults to 224):
67
+ The size (resolution) of each image.
68
+ patch_size (`int`, *optional*, defaults to 16):
69
+ The size (resolution) of each patch.
70
+ num_channels (`int`, *optional*, defaults to 3):
71
+ The number of input channels.
72
+ qkv_bias (`bool`, *optional*, defaults to `True`):
73
+ Whether to add a bias to the queries, keys and values.
74
+ encoder_stride (`int`, *optional*, defaults to 16):
75
+ Factor to increase the spatial resolution by in the decoder head for masked image modeling.
76
+
77
+ Example:
78
+
79
+ ```python
80
+ >>> from transformers import ViTConfig, ViTModel
81
+
82
+ >>> # Initializing a ViT vit-base-patch16-224 style configuration
83
+ >>> configuration = ViTConfig()
84
+
85
+ >>> # Initializing a model (with random weights) from the vit-base-patch16-224 style configuration
86
+ >>> model = ViTModel(configuration)
87
+
88
+ >>> # Accessing the model configuration
89
+ >>> configuration = model.config
90
+ ```"""
91
+
92
+ model_type = "vit"
93
+
94
+ def __init__(
95
+ self,
96
+ hidden_size=768,
97
+ num_hidden_layers=12,
98
+ num_attention_heads=12,
99
+ intermediate_size=3072,
100
+ hidden_act="gelu",
101
+ hidden_dropout_prob=0.0,
102
+ attention_probs_dropout_prob=0.0,
103
+ initializer_range=0.02,
104
+ layer_norm_eps=1e-12,
105
+ image_size=224,
106
+ patch_size=16,
107
+ num_channels=3,
108
+ qkv_bias=True,
109
+ encoder_stride=16,
110
+ **kwargs,
111
+ ):
112
+ super().__init__(**kwargs)
113
+
114
+ self.hidden_size = hidden_size
115
+ self.num_hidden_layers = num_hidden_layers
116
+ self.num_attention_heads = num_attention_heads
117
+ self.intermediate_size = intermediate_size
118
+ self.hidden_act = hidden_act
119
+ self.hidden_dropout_prob = hidden_dropout_prob
120
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
121
+ self.initializer_range = initializer_range
122
+ self.layer_norm_eps = layer_norm_eps
123
+ self.image_size = image_size
124
+ self.patch_size = patch_size
125
+ self.num_channels = num_channels
126
+ self.qkv_bias = qkv_bias
127
+ self.encoder_stride = encoder_stride
128
+
129
+
130
+ class ViTOnnxConfig(OnnxConfig):
131
+ torch_onnx_minimum_version = version.parse("1.11")
132
+
133
+ @property
134
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
135
+ return OrderedDict(
136
+ [
137
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
138
+ ]
139
+ )
140
+
141
+ @property
142
+ def atol_for_validation(self) -> float:
143
+ return 1e-4
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/convert_dino_to_pytorch.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert ViT checkpoints trained with the DINO method."""
16
+
17
+
18
+ import argparse
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import requests
23
+ import torch
24
+ from huggingface_hub import hf_hub_download
25
+ from PIL import Image
26
+
27
+ from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
28
+ from transformers.utils import logging
29
+
30
+
31
+ logging.set_verbosity_info()
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ # here we list all keys to be renamed (original name on the left, our name on the right)
36
+ def create_rename_keys(config, base_model=False):
37
+ rename_keys = []
38
+ for i in range(config.num_hidden_layers):
39
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
40
+ rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight"))
41
+ rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias"))
42
+ rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight"))
43
+ rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias"))
44
+ rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight"))
45
+ rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias"))
46
+ rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight"))
47
+ rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias"))
48
+ rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight"))
49
+ rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias"))
50
+
51
+ # projection layer + position embeddings
52
+ rename_keys.extend(
53
+ [
54
+ ("cls_token", "vit.embeddings.cls_token"),
55
+ ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"),
56
+ ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"),
57
+ ("pos_embed", "vit.embeddings.position_embeddings"),
58
+ ]
59
+ )
60
+
61
+ if base_model:
62
+ # layernorm + pooler
63
+ rename_keys.extend(
64
+ [
65
+ ("norm.weight", "layernorm.weight"),
66
+ ("norm.bias", "layernorm.bias"),
67
+ ]
68
+ )
69
+
70
+ # if just the base model, we should remove "vit" from all keys that start with "vit"
71
+ rename_keys = [(pair[0], pair[1][4:]) if pair[1].startswith("vit") else pair for pair in rename_keys]
72
+ else:
73
+ # layernorm + classification head
74
+ rename_keys.extend(
75
+ [
76
+ ("norm.weight", "vit.layernorm.weight"),
77
+ ("norm.bias", "vit.layernorm.bias"),
78
+ ("head.weight", "classifier.weight"),
79
+ ("head.bias", "classifier.bias"),
80
+ ]
81
+ )
82
+
83
+ return rename_keys
84
+
85
+
86
+ # we split up the matrix of each encoder layer into queries, keys and values
87
+ def read_in_q_k_v(state_dict, config, base_model=False):
88
+ for i in range(config.num_hidden_layers):
89
+ if base_model:
90
+ prefix = ""
91
+ else:
92
+ prefix = "vit."
93
+ # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
94
+ in_proj_weight = state_dict.pop(f"blocks.{i}.attn.qkv.weight")
95
+ in_proj_bias = state_dict.pop(f"blocks.{i}.attn.qkv.bias")
96
+ # next, add query, keys and values (in that order) to the state dict
97
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
98
+ : config.hidden_size, :
99
+ ]
100
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size]
101
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
102
+ config.hidden_size : config.hidden_size * 2, :
103
+ ]
104
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
105
+ config.hidden_size : config.hidden_size * 2
106
+ ]
107
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
108
+ -config.hidden_size :, :
109
+ ]
110
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :]
111
+
112
+
113
+ def remove_classification_head_(state_dict):
114
+ ignore_keys = ["head.weight", "head.bias"]
115
+ for k in ignore_keys:
116
+ state_dict.pop(k, None)
117
+
118
+
119
+ def rename_key(dct, old, new):
120
+ val = dct.pop(old)
121
+ dct[new] = val
122
+
123
+
124
+ # We will verify our results on an image of cute cats
125
+ def prepare_img():
126
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
127
+ im = Image.open(requests.get(url, stream=True).raw)
128
+ return im
129
+
130
+
131
+ @torch.no_grad()
132
+ def convert_vit_checkpoint(model_name, pytorch_dump_folder_path, base_model=True):
133
+ """
134
+ Copy/paste/tweak model's weights to our ViT structure.
135
+ """
136
+
137
+ # define default ViT configuration
138
+ config = ViTConfig()
139
+ # patch_size
140
+ if model_name[-1] == "8":
141
+ config.patch_size = 8
142
+ # set labels if required
143
+ if not base_model:
144
+ config.num_labels = 1000
145
+ repo_id = "huggingface/label-files"
146
+ filename = "imagenet-1k-id2label.json"
147
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
148
+ id2label = {int(k): v for k, v in id2label.items()}
149
+ config.id2label = id2label
150
+ config.label2id = {v: k for k, v in id2label.items()}
151
+ # size of the architecture
152
+ if model_name in ["dino_vits8", "dino_vits16"]:
153
+ config.hidden_size = 384
154
+ config.intermediate_size = 1536
155
+ config.num_hidden_layers = 12
156
+ config.num_attention_heads = 6
157
+
158
+ # load original model from torch hub
159
+ original_model = torch.hub.load("facebookresearch/dino:main", model_name)
160
+ original_model.eval()
161
+
162
+ # load state_dict of original model, remove and rename some keys
163
+ state_dict = original_model.state_dict()
164
+ if base_model:
165
+ remove_classification_head_(state_dict)
166
+ rename_keys = create_rename_keys(config, base_model=base_model)
167
+ for src, dest in rename_keys:
168
+ rename_key(state_dict, src, dest)
169
+ read_in_q_k_v(state_dict, config, base_model)
170
+
171
+ # load HuggingFace model
172
+ if base_model:
173
+ model = ViTModel(config, add_pooling_layer=False).eval()
174
+ else:
175
+ model = ViTForImageClassification(config).eval()
176
+ model.load_state_dict(state_dict)
177
+
178
+ # Check outputs on an image, prepared by ViTImageProcessor
179
+ image_processor = ViTImageProcessor()
180
+ encoding = image_processor(images=prepare_img(), return_tensors="pt")
181
+ pixel_values = encoding["pixel_values"]
182
+ outputs = model(pixel_values)
183
+
184
+ if base_model:
185
+ final_hidden_state_cls_token = original_model(pixel_values)
186
+ assert torch.allclose(final_hidden_state_cls_token, outputs.last_hidden_state[:, 0, :], atol=1e-1)
187
+ else:
188
+ logits = original_model(pixel_values)
189
+ assert logits.shape == outputs.logits.shape
190
+ assert torch.allclose(logits, outputs.logits, atol=1e-3)
191
+
192
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
193
+ print(f"Saving model {model_name} to {pytorch_dump_folder_path}")
194
+ model.save_pretrained(pytorch_dump_folder_path)
195
+ print(f"Saving image processor to {pytorch_dump_folder_path}")
196
+ image_processor.save_pretrained(pytorch_dump_folder_path)
197
+
198
+
199
+ if __name__ == "__main__":
200
+ parser = argparse.ArgumentParser()
201
+ # Required parameters
202
+ parser.add_argument(
203
+ "--model_name",
204
+ default="dino_vitb16",
205
+ type=str,
206
+ help="Name of the model trained with DINO you'd like to convert.",
207
+ )
208
+ parser.add_argument(
209
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
210
+ )
211
+ parser.add_argument(
212
+ "--base_model",
213
+ action="store_true",
214
+ help="Whether to only convert the base model (no projection head weights).",
215
+ )
216
+
217
+ parser.set_defaults(base_model=True)
218
+ args = parser.parse_args()
219
+ convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/convert_vit_timm_to_pytorch.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert ViT and non-distilled DeiT checkpoints from the timm library."""
16
+
17
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ import requests
22
+ import timm
23
+ import torch
24
+ from PIL import Image
25
+ from timm.data import ImageNetInfo, infer_imagenet_subset
26
+
27
+ from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
28
+ from transformers.utils import logging
29
+
30
+
31
+ logging.set_verbosity_info()
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ # here we list all keys to be renamed (original name on the left, our name on the right)
36
+ def create_rename_keys(config, base_model=False):
37
+ rename_keys = []
38
+ for i in range(config.num_hidden_layers):
39
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
40
+ rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight"))
41
+ rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias"))
42
+ rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight"))
43
+ rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias"))
44
+ rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight"))
45
+ rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias"))
46
+ rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight"))
47
+ rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias"))
48
+ rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight"))
49
+ rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias"))
50
+
51
+ # projection layer + position embeddings
52
+ rename_keys.extend(
53
+ [
54
+ ("cls_token", "vit.embeddings.cls_token"),
55
+ ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"),
56
+ ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"),
57
+ ("pos_embed", "vit.embeddings.position_embeddings"),
58
+ ]
59
+ )
60
+
61
+ if base_model:
62
+ # layernorm
63
+ rename_keys.extend(
64
+ [
65
+ ("norm.weight", "layernorm.weight"),
66
+ ("norm.bias", "layernorm.bias"),
67
+ ]
68
+ )
69
+
70
+ # if just the base model, we should remove "vit" from all keys that start with "vit"
71
+ rename_keys = [(pair[0], pair[1][4:]) if pair[1].startswith("vit") else pair for pair in rename_keys]
72
+ else:
73
+ # layernorm + classification head
74
+ rename_keys.extend(
75
+ [
76
+ ("norm.weight", "vit.layernorm.weight"),
77
+ ("norm.bias", "vit.layernorm.bias"),
78
+ ("head.weight", "classifier.weight"),
79
+ ("head.bias", "classifier.bias"),
80
+ ]
81
+ )
82
+
83
+ return rename_keys
84
+
85
+
86
+ # we split up the matrix of each encoder layer into queries, keys and values
87
+ def read_in_q_k_v(state_dict, config, base_model=False):
88
+ for i in range(config.num_hidden_layers):
89
+ if base_model:
90
+ prefix = ""
91
+ else:
92
+ prefix = "vit."
93
+ # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
94
+ in_proj_weight = state_dict.pop(f"blocks.{i}.attn.qkv.weight")
95
+ in_proj_bias = state_dict.pop(f"blocks.{i}.attn.qkv.bias")
96
+ # next, add query, keys and values (in that order) to the state dict
97
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
98
+ : config.hidden_size, :
99
+ ]
100
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size]
101
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
102
+ config.hidden_size : config.hidden_size * 2, :
103
+ ]
104
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
105
+ config.hidden_size : config.hidden_size * 2
106
+ ]
107
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
108
+ -config.hidden_size :, :
109
+ ]
110
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :]
111
+
112
+
113
+ def remove_classification_head_(state_dict):
114
+ ignore_keys = ["head.weight", "head.bias"]
115
+ for k in ignore_keys:
116
+ state_dict.pop(k, None)
117
+
118
+
119
+ def rename_key(dct, old, new):
120
+ val = dct.pop(old)
121
+ dct[new] = val
122
+
123
+
124
+ # We will verify our results on an image of cute cats
125
+ def prepare_img():
126
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
127
+ im = Image.open(requests.get(url, stream=True).raw)
128
+ return im
129
+
130
+
131
+ @torch.no_grad()
132
+ def convert_vit_checkpoint(vit_name, pytorch_dump_folder_path):
133
+ """
134
+ Copy/paste/tweak model's weights to our ViT structure.
135
+ """
136
+
137
+ # define default ViT configuration
138
+ config = ViTConfig()
139
+ base_model = False
140
+
141
+ # load original model from timm
142
+ timm_model = timm.create_model(vit_name, pretrained=True)
143
+ timm_model.eval()
144
+
145
+ # detect unsupported ViT models in transformers
146
+ # fc_norm is present
147
+ if not isinstance(getattr(timm_model, "fc_norm", None), torch.nn.Identity):
148
+ raise ValueError(f"{vit_name} is not supported in transformers because of the presence of fc_norm.")
149
+
150
+ # use of global average pooling in combination (or without) class token
151
+ if getattr(timm_model, "global_pool", None) == "avg":
152
+ raise ValueError(f"{vit_name} is not supported in transformers because of use of global average pooling.")
153
+
154
+ # CLIP style vit with norm_pre layer present
155
+ if "clip" in vit_name and not isinstance(getattr(timm_model, "norm_pre", None), torch.nn.Identity):
156
+ raise ValueError(
157
+ f"{vit_name} is not supported in transformers because it's a CLIP style ViT with norm_pre layer."
158
+ )
159
+
160
+ # SigLIP style vit with attn_pool layer present
161
+ if "siglip" in vit_name and getattr(timm_model, "global_pool", None) == "map":
162
+ raise ValueError(
163
+ f"{vit_name} is not supported in transformers because it's a SigLIP style ViT with attn_pool."
164
+ )
165
+
166
+ # use of layer scale in ViT model blocks
167
+ if not isinstance(getattr(timm_model.blocks[0], "ls1", None), torch.nn.Identity) or not isinstance(
168
+ getattr(timm_model.blocks[0], "ls2", None), torch.nn.Identity
169
+ ):
170
+ raise ValueError(f"{vit_name} is not supported in transformers because it uses a layer scale in its blocks.")
171
+
172
+ # Hybrid ResNet-ViTs
173
+ if not isinstance(timm_model.patch_embed, timm.layers.PatchEmbed):
174
+ raise ValueError(f"{vit_name} is not supported in transformers because it is a hybrid ResNet-ViT.")
175
+
176
+ # get patch size and image size from the patch embedding submodule
177
+ config.patch_size = timm_model.patch_embed.patch_size[0]
178
+ config.image_size = timm_model.patch_embed.img_size[0]
179
+
180
+ # retrieve architecture-specific parameters from the timm model
181
+ config.hidden_size = timm_model.embed_dim
182
+ config.intermediate_size = timm_model.blocks[0].mlp.fc1.out_features
183
+ config.num_hidden_layers = len(timm_model.blocks)
184
+ config.num_attention_heads = timm_model.blocks[0].attn.num_heads
185
+
186
+ # check whether the model has a classification head or not
187
+ if timm_model.num_classes != 0:
188
+ config.num_labels = timm_model.num_classes
189
+ # infer ImageNet subset from timm model
190
+ imagenet_subset = infer_imagenet_subset(timm_model)
191
+ dataset_info = ImageNetInfo(imagenet_subset)
192
+ config.id2label = {i: dataset_info.index_to_label_name(i) for i in range(dataset_info.num_classes())}
193
+ config.label2id = {v: k for k, v in config.id2label.items()}
194
+ else:
195
+ print(f"{vit_name} is going to be converted as a feature extractor only.")
196
+ base_model = True
197
+
198
+ # load state_dict of original model
199
+ state_dict = timm_model.state_dict()
200
+
201
+ # remove and rename some keys in the state dict
202
+ if base_model:
203
+ remove_classification_head_(state_dict)
204
+ rename_keys = create_rename_keys(config, base_model)
205
+ for src, dest in rename_keys:
206
+ rename_key(state_dict, src, dest)
207
+ read_in_q_k_v(state_dict, config, base_model)
208
+
209
+ # load HuggingFace model
210
+ if base_model:
211
+ model = ViTModel(config, add_pooling_layer=False).eval()
212
+ else:
213
+ model = ViTForImageClassification(config).eval()
214
+ model.load_state_dict(state_dict)
215
+
216
+ # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor
217
+ if "deit" in vit_name:
218
+ image_processor = DeiTImageProcessor(size=config.image_size)
219
+ else:
220
+ image_processor = ViTImageProcessor(size=config.image_size)
221
+ encoding = image_processor(images=prepare_img(), return_tensors="pt")
222
+ pixel_values = encoding["pixel_values"]
223
+ outputs = model(pixel_values)
224
+
225
+ if base_model:
226
+ timm_pooled_output = timm_model.forward_features(pixel_values)
227
+ assert timm_pooled_output.shape == outputs.last_hidden_state.shape
228
+ assert torch.allclose(timm_pooled_output, outputs.last_hidden_state, atol=1e-1)
229
+ else:
230
+ timm_logits = timm_model(pixel_values)
231
+ assert timm_logits.shape == outputs.logits.shape
232
+ assert torch.allclose(timm_logits, outputs.logits, atol=1e-3)
233
+
234
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
235
+ print(f"Saving model {vit_name} to {pytorch_dump_folder_path}")
236
+ model.save_pretrained(pytorch_dump_folder_path)
237
+ print(f"Saving image processor to {pytorch_dump_folder_path}")
238
+ image_processor.save_pretrained(pytorch_dump_folder_path)
239
+
240
+
241
+ if __name__ == "__main__":
242
+ parser = argparse.ArgumentParser()
243
+ # Required parameters
244
+ parser.add_argument(
245
+ "--vit_name",
246
+ default="vit_base_patch16_224",
247
+ type=str,
248
+ help="Name of the ViT timm model you'd like to convert.",
249
+ )
250
+ parser.add_argument(
251
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
252
+ )
253
+
254
+ args = parser.parse_args()
255
+ convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/image_processing_vit.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ViT."""
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 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
+ )
35
+ from ...utils import TensorType, logging
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ class ViTImageProcessor(BaseImageProcessor):
42
+ r"""
43
+ Constructs a ViT image processor.
44
+
45
+ Args:
46
+ do_resize (`bool`, *optional*, defaults to `True`):
47
+ Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
48
+ size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
49
+ size (`dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
50
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
51
+ method.
52
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
53
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
54
+ `preprocess` method.
55
+ do_rescale (`bool`, *optional*, defaults to `True`):
56
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
57
+ parameter in the `preprocess` method.
58
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
59
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
60
+ `preprocess` method.
61
+ do_normalize (`bool`, *optional*, defaults to `True`):
62
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
63
+ method.
64
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
65
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
66
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
67
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
68
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
69
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
70
+ """
71
+
72
+ model_input_names = ["pixel_values"]
73
+
74
+ def __init__(
75
+ self,
76
+ do_resize: bool = True,
77
+ size: Optional[Dict[str, int]] = None,
78
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
79
+ do_rescale: bool = True,
80
+ rescale_factor: Union[int, float] = 1 / 255,
81
+ do_normalize: bool = True,
82
+ image_mean: Optional[Union[float, List[float]]] = None,
83
+ image_std: Optional[Union[float, List[float]]] = None,
84
+ **kwargs,
85
+ ) -> None:
86
+ super().__init__(**kwargs)
87
+ size = size if size is not None else {"height": 224, "width": 224}
88
+ size = get_size_dict(size)
89
+ self.do_resize = do_resize
90
+ self.do_rescale = do_rescale
91
+ self.do_normalize = do_normalize
92
+ self.size = size
93
+ self.resample = resample
94
+ self.rescale_factor = rescale_factor
95
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
96
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
97
+
98
+ def resize(
99
+ self,
100
+ image: np.ndarray,
101
+ size: Dict[str, int],
102
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
103
+ data_format: Optional[Union[str, ChannelDimension]] = None,
104
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
105
+ **kwargs,
106
+ ) -> np.ndarray:
107
+ """
108
+ Resize an image to `(size["height"], size["width"])`.
109
+
110
+ Args:
111
+ image (`np.ndarray`):
112
+ Image to resize.
113
+ size (`Dict[str, int]`):
114
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
115
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
116
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
117
+ data_format (`ChannelDimension` or `str`, *optional*):
118
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
119
+ image is used. Can be one of:
120
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
121
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
122
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
123
+ input_data_format (`ChannelDimension` or `str`, *optional*):
124
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
125
+ from the input image. Can be one of:
126
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
127
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
128
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
129
+
130
+ Returns:
131
+ `np.ndarray`: The resized image.
132
+ """
133
+ size = get_size_dict(size)
134
+ if "height" not in size or "width" not in size:
135
+ raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
136
+ output_size = (size["height"], size["width"])
137
+ return resize(
138
+ image,
139
+ size=output_size,
140
+ resample=resample,
141
+ data_format=data_format,
142
+ input_data_format=input_data_format,
143
+ **kwargs,
144
+ )
145
+
146
+ def preprocess(
147
+ self,
148
+ images: ImageInput,
149
+ do_resize: Optional[bool] = None,
150
+ size: Dict[str, int] = None,
151
+ resample: PILImageResampling = None,
152
+ do_rescale: Optional[bool] = None,
153
+ rescale_factor: Optional[float] = None,
154
+ do_normalize: Optional[bool] = None,
155
+ image_mean: Optional[Union[float, List[float]]] = None,
156
+ image_std: Optional[Union[float, List[float]]] = None,
157
+ return_tensors: Optional[Union[str, TensorType]] = None,
158
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
159
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
160
+ **kwargs,
161
+ ):
162
+ """
163
+ Preprocess an image or batch of images.
164
+
165
+ Args:
166
+ images (`ImageInput`):
167
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
168
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
169
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
170
+ Whether to resize the image.
171
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
172
+ Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
173
+ resizing.
174
+ resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
175
+ `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
176
+ an effect if `do_resize` is set to `True`.
177
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
178
+ Whether to rescale the image values between [0 - 1].
179
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
180
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
181
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
182
+ Whether to normalize the image.
183
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
184
+ Image mean to use if `do_normalize` is set to `True`.
185
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
186
+ Image standard deviation to use if `do_normalize` is set to `True`.
187
+ return_tensors (`str` or `TensorType`, *optional*):
188
+ The type of tensors to return. Can be one of:
189
+ - Unset: Return a list of `np.ndarray`.
190
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
191
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
192
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
193
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
194
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
195
+ The channel dimension format for the output image. Can be one of:
196
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
197
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
198
+ - Unset: Use the channel dimension format of the input image.
199
+ input_data_format (`ChannelDimension` or `str`, *optional*):
200
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
201
+ from the input image. Can be one of:
202
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
203
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
204
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
205
+ """
206
+ do_resize = do_resize if do_resize is not None else self.do_resize
207
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
208
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
209
+ resample = resample if resample is not None else self.resample
210
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
211
+ image_mean = image_mean if image_mean is not None else self.image_mean
212
+ image_std = image_std if image_std is not None else self.image_std
213
+
214
+ size = size if size is not None else self.size
215
+ size_dict = get_size_dict(size)
216
+
217
+ images = make_list_of_images(images)
218
+
219
+ if not valid_images(images):
220
+ raise ValueError(
221
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
222
+ "torch.Tensor, tf.Tensor or jax.ndarray."
223
+ )
224
+
225
+ if do_resize and size is None:
226
+ raise ValueError("Size must be specified if do_resize is True.")
227
+
228
+ if do_rescale and rescale_factor is None:
229
+ raise ValueError("Rescale factor must be specified if do_rescale is True.")
230
+
231
+ # All transformations expect numpy arrays.
232
+ images = [to_numpy_array(image) for image in images]
233
+
234
+ if is_scaled_image(images[0]) and do_rescale:
235
+ logger.warning_once(
236
+ "It looks like you are trying to rescale already rescaled images. If the input"
237
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
238
+ )
239
+
240
+ if input_data_format is None:
241
+ # We assume that all images have the same channel dimension format.
242
+ input_data_format = infer_channel_dimension_format(images[0])
243
+
244
+ if do_resize:
245
+ images = [
246
+ self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)
247
+ for image in images
248
+ ]
249
+
250
+ if do_rescale:
251
+ images = [
252
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
253
+ for image in images
254
+ ]
255
+
256
+ if do_normalize:
257
+ images = [
258
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
259
+ for image in images
260
+ ]
261
+
262
+ images = [
263
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
264
+ ]
265
+
266
+ data = {"pixel_values": images}
267
+ return BatchFeature(data=data, tensor_type=return_tensors)
evalkit_tf437/lib/python3.10/site-packages/transformers/models/vit/modeling_vit.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI, Ross Wightman, 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 ViT model."""
16
+
17
+
18
+ import collections.abc
19
+ import math
20
+ from typing import Dict, List, Optional, Set, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_outputs import (
29
+ BaseModelOutput,
30
+ BaseModelOutputWithPooling,
31
+ ImageClassifierOutput,
32
+ MaskedImageModelingOutput,
33
+ )
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
36
+ from ...utils import (
37
+ add_code_sample_docstrings,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from .configuration_vit import ViTConfig
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+ # General docstring
49
+ _CONFIG_FOR_DOC = "ViTConfig"
50
+
51
+ # Base docstring
52
+ _CHECKPOINT_FOR_DOC = "google/vit-base-patch16-224-in21k"
53
+ _EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
54
+
55
+ # Image classification docstring
56
+ _IMAGE_CLASS_CHECKPOINT = "google/vit-base-patch16-224"
57
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
58
+
59
+
60
+ VIT_PRETRAINED_MODEL_ARCHIVE_LIST = [
61
+ "google/vit-base-patch16-224",
62
+ # See all ViT models at https://huggingface.co/models?filter=vit
63
+ ]
64
+
65
+
66
+ class ViTEmbeddings(nn.Module):
67
+ """
68
+ Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
69
+ """
70
+
71
+ def __init__(self, config: ViTConfig, use_mask_token: bool = False) -> None:
72
+ super().__init__()
73
+
74
+ self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
75
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
76
+ self.patch_embeddings = ViTPatchEmbeddings(config)
77
+ num_patches = self.patch_embeddings.num_patches
78
+ self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
79
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
80
+ self.config = config
81
+
82
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
83
+ """
84
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
85
+ resolution images.
86
+
87
+ Source:
88
+ https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
89
+ """
90
+
91
+ num_patches = embeddings.shape[1] - 1
92
+ num_positions = self.position_embeddings.shape[1] - 1
93
+ if num_patches == num_positions and height == width:
94
+ return self.position_embeddings
95
+ class_pos_embed = self.position_embeddings[:, 0]
96
+ patch_pos_embed = self.position_embeddings[:, 1:]
97
+ dim = embeddings.shape[-1]
98
+ h0 = height // self.config.patch_size
99
+ w0 = width // self.config.patch_size
100
+ # we add a small number to avoid floating point error in the interpolation
101
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
102
+ h0, w0 = h0 + 0.1, w0 + 0.1
103
+ patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
104
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
105
+ patch_pos_embed = nn.functional.interpolate(
106
+ patch_pos_embed,
107
+ scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
108
+ mode="bicubic",
109
+ align_corners=False,
110
+ )
111
+ assert int(h0) == patch_pos_embed.shape[-2] and int(w0) == patch_pos_embed.shape[-1]
112
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
113
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
114
+
115
+ def forward(
116
+ self,
117
+ pixel_values: torch.Tensor,
118
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
119
+ interpolate_pos_encoding: bool = False,
120
+ ) -> torch.Tensor:
121
+ batch_size, num_channels, height, width = pixel_values.shape
122
+ embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
123
+
124
+ if bool_masked_pos is not None:
125
+ seq_length = embeddings.shape[1]
126
+ mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
127
+ # replace the masked visual tokens by mask_tokens
128
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
129
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
130
+
131
+ # add the [CLS] token to the embedded patch tokens
132
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
133
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
134
+
135
+ # add positional encoding to each token
136
+ if interpolate_pos_encoding:
137
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
138
+ else:
139
+ embeddings = embeddings + self.position_embeddings
140
+
141
+ embeddings = self.dropout(embeddings)
142
+
143
+ return embeddings
144
+
145
+
146
+ class ViTPatchEmbeddings(nn.Module):
147
+ """
148
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
149
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
150
+ Transformer.
151
+ """
152
+
153
+ def __init__(self, config):
154
+ super().__init__()
155
+ image_size, patch_size = config.image_size, config.patch_size
156
+ num_channels, hidden_size = config.num_channels, config.hidden_size
157
+
158
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
159
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
160
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
161
+ self.image_size = image_size
162
+ self.patch_size = patch_size
163
+ self.num_channels = num_channels
164
+ self.num_patches = num_patches
165
+
166
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
167
+
168
+ def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
169
+ batch_size, num_channels, height, width = pixel_values.shape
170
+ if num_channels != self.num_channels:
171
+ raise ValueError(
172
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
173
+ f" Expected {self.num_channels} but got {num_channels}."
174
+ )
175
+ if not interpolate_pos_encoding:
176
+ if height != self.image_size[0] or width != self.image_size[1]:
177
+ raise ValueError(
178
+ f"Input image size ({height}*{width}) doesn't match model"
179
+ f" ({self.image_size[0]}*{self.image_size[1]})."
180
+ )
181
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
182
+ return embeddings
183
+
184
+
185
+ class ViTSelfAttention(nn.Module):
186
+ def __init__(self, config: ViTConfig) -> None:
187
+ super().__init__()
188
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
189
+ raise ValueError(
190
+ f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
191
+ f"heads {config.num_attention_heads}."
192
+ )
193
+
194
+ self.num_attention_heads = config.num_attention_heads
195
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
196
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
197
+
198
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
199
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
200
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
201
+
202
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
203
+
204
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
205
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
206
+ x = x.view(new_x_shape)
207
+ return x.permute(0, 2, 1, 3)
208
+
209
+ def forward(
210
+ self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
211
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
212
+ mixed_query_layer = self.query(hidden_states)
213
+
214
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
215
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
216
+ query_layer = self.transpose_for_scores(mixed_query_layer)
217
+
218
+ # Take the dot product between "query" and "key" to get the raw attention scores.
219
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
220
+
221
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
222
+
223
+ # Normalize the attention scores to probabilities.
224
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
225
+
226
+ # This is actually dropping out entire tokens to attend to, which might
227
+ # seem a bit unusual, but is taken from the original Transformer paper.
228
+ attention_probs = self.dropout(attention_probs)
229
+
230
+ # Mask heads if we want to
231
+ if head_mask is not None:
232
+ attention_probs = attention_probs * head_mask
233
+
234
+ context_layer = torch.matmul(attention_probs, value_layer)
235
+
236
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
237
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
238
+ context_layer = context_layer.view(new_context_layer_shape)
239
+
240
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
241
+
242
+ return outputs
243
+
244
+
245
+ class ViTSelfOutput(nn.Module):
246
+ """
247
+ The residual connection is defined in ViTLayer instead of here (as is the case with other models), due to the
248
+ layernorm applied before each block.
249
+ """
250
+
251
+ def __init__(self, config: ViTConfig) -> None:
252
+ super().__init__()
253
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
254
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
255
+
256
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
257
+ hidden_states = self.dense(hidden_states)
258
+ hidden_states = self.dropout(hidden_states)
259
+
260
+ return hidden_states
261
+
262
+
263
+ class ViTAttention(nn.Module):
264
+ def __init__(self, config: ViTConfig) -> None:
265
+ super().__init__()
266
+ self.attention = ViTSelfAttention(config)
267
+ self.output = ViTSelfOutput(config)
268
+ self.pruned_heads = set()
269
+
270
+ def prune_heads(self, heads: Set[int]) -> None:
271
+ if len(heads) == 0:
272
+ return
273
+ heads, index = find_pruneable_heads_and_indices(
274
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
275
+ )
276
+
277
+ # Prune linear layers
278
+ self.attention.query = prune_linear_layer(self.attention.query, index)
279
+ self.attention.key = prune_linear_layer(self.attention.key, index)
280
+ self.attention.value = prune_linear_layer(self.attention.value, index)
281
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
282
+
283
+ # Update hyper params and store pruned heads
284
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
285
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
286
+ self.pruned_heads = self.pruned_heads.union(heads)
287
+
288
+ def forward(
289
+ self,
290
+ hidden_states: torch.Tensor,
291
+ head_mask: Optional[torch.Tensor] = None,
292
+ output_attentions: bool = False,
293
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
294
+ self_outputs = self.attention(hidden_states, head_mask, output_attentions)
295
+
296
+ attention_output = self.output(self_outputs[0], hidden_states)
297
+
298
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
299
+ return outputs
300
+
301
+
302
+ class ViTIntermediate(nn.Module):
303
+ def __init__(self, config: ViTConfig) -> None:
304
+ super().__init__()
305
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
306
+ if isinstance(config.hidden_act, str):
307
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
308
+ else:
309
+ self.intermediate_act_fn = config.hidden_act
310
+
311
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
312
+ hidden_states = self.dense(hidden_states)
313
+ hidden_states = self.intermediate_act_fn(hidden_states)
314
+
315
+ return hidden_states
316
+
317
+
318
+ class ViTOutput(nn.Module):
319
+ def __init__(self, config: ViTConfig) -> None:
320
+ super().__init__()
321
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
322
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
323
+
324
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
325
+ hidden_states = self.dense(hidden_states)
326
+ hidden_states = self.dropout(hidden_states)
327
+
328
+ hidden_states = hidden_states + input_tensor
329
+
330
+ return hidden_states
331
+
332
+
333
+ class ViTLayer(nn.Module):
334
+ """This corresponds to the Block class in the timm implementation."""
335
+
336
+ def __init__(self, config: ViTConfig) -> None:
337
+ super().__init__()
338
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
339
+ self.seq_len_dim = 1
340
+ self.attention = ViTAttention(config)
341
+ self.intermediate = ViTIntermediate(config)
342
+ self.output = ViTOutput(config)
343
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
344
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
345
+
346
+ def forward(
347
+ self,
348
+ hidden_states: torch.Tensor,
349
+ head_mask: Optional[torch.Tensor] = None,
350
+ output_attentions: bool = False,
351
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
352
+ self_attention_outputs = self.attention(
353
+ self.layernorm_before(hidden_states), # in ViT, layernorm is applied before self-attention
354
+ head_mask,
355
+ output_attentions=output_attentions,
356
+ )
357
+ attention_output = self_attention_outputs[0]
358
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
359
+
360
+ # first residual connection
361
+ hidden_states = attention_output + hidden_states
362
+
363
+ # in ViT, layernorm is also applied after self-attention
364
+ layer_output = self.layernorm_after(hidden_states)
365
+ layer_output = self.intermediate(layer_output)
366
+
367
+ # second residual connection is done here
368
+ layer_output = self.output(layer_output, hidden_states)
369
+
370
+ outputs = (layer_output,) + outputs
371
+
372
+ return outputs
373
+
374
+
375
+ class ViTEncoder(nn.Module):
376
+ def __init__(self, config: ViTConfig) -> None:
377
+ super().__init__()
378
+ self.config = config
379
+ self.layer = nn.ModuleList([ViTLayer(config) for _ in range(config.num_hidden_layers)])
380
+ self.gradient_checkpointing = False
381
+
382
+ def forward(
383
+ self,
384
+ hidden_states: torch.Tensor,
385
+ head_mask: Optional[torch.Tensor] = None,
386
+ output_attentions: bool = False,
387
+ output_hidden_states: bool = False,
388
+ return_dict: bool = True,
389
+ ) -> Union[tuple, BaseModelOutput]:
390
+ all_hidden_states = () if output_hidden_states else None
391
+ all_self_attentions = () if output_attentions else None
392
+
393
+ for i, layer_module in enumerate(self.layer):
394
+ if output_hidden_states:
395
+ all_hidden_states = all_hidden_states + (hidden_states,)
396
+
397
+ layer_head_mask = head_mask[i] if head_mask is not None else None
398
+
399
+ if self.gradient_checkpointing and self.training:
400
+ layer_outputs = self._gradient_checkpointing_func(
401
+ layer_module.__call__,
402
+ hidden_states,
403
+ layer_head_mask,
404
+ output_attentions,
405
+ )
406
+ else:
407
+ layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
408
+
409
+ hidden_states = layer_outputs[0]
410
+
411
+ if output_attentions:
412
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
413
+
414
+ if output_hidden_states:
415
+ all_hidden_states = all_hidden_states + (hidden_states,)
416
+
417
+ if not return_dict:
418
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
419
+ return BaseModelOutput(
420
+ last_hidden_state=hidden_states,
421
+ hidden_states=all_hidden_states,
422
+ attentions=all_self_attentions,
423
+ )
424
+
425
+
426
+ class ViTPreTrainedModel(PreTrainedModel):
427
+ """
428
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
429
+ models.
430
+ """
431
+
432
+ config_class = ViTConfig
433
+ base_model_prefix = "vit"
434
+ main_input_name = "pixel_values"
435
+ supports_gradient_checkpointing = True
436
+ _no_split_modules = ["ViTEmbeddings", "ViTLayer"]
437
+
438
+ def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
439
+ """Initialize the weights"""
440
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
441
+ # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
442
+ # `trunc_normal_cpu` not implemented in `half` issues
443
+ module.weight.data = nn.init.trunc_normal_(
444
+ module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
445
+ ).to(module.weight.dtype)
446
+ if module.bias is not None:
447
+ module.bias.data.zero_()
448
+ elif isinstance(module, nn.LayerNorm):
449
+ module.bias.data.zero_()
450
+ module.weight.data.fill_(1.0)
451
+ elif isinstance(module, ViTEmbeddings):
452
+ module.position_embeddings.data = nn.init.trunc_normal_(
453
+ module.position_embeddings.data.to(torch.float32),
454
+ mean=0.0,
455
+ std=self.config.initializer_range,
456
+ ).to(module.position_embeddings.dtype)
457
+
458
+ module.cls_token.data = nn.init.trunc_normal_(
459
+ module.cls_token.data.to(torch.float32),
460
+ mean=0.0,
461
+ std=self.config.initializer_range,
462
+ ).to(module.cls_token.dtype)
463
+
464
+
465
+ VIT_START_DOCSTRING = r"""
466
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
467
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
468
+ behavior.
469
+
470
+ Parameters:
471
+ config ([`ViTConfig`]): Model configuration class with all the parameters of the model.
472
+ Initializing with a config file does not load the weights associated with the model, only the
473
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
474
+ """
475
+
476
+ VIT_INPUTS_DOCSTRING = r"""
477
+ Args:
478
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
479
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ViTImageProcessor.__call__`]
480
+ for details.
481
+
482
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
483
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
484
+
485
+ - 1 indicates the head is **not masked**,
486
+ - 0 indicates the head is **masked**.
487
+
488
+ output_attentions (`bool`, *optional*):
489
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
490
+ tensors for more detail.
491
+ output_hidden_states (`bool`, *optional*):
492
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
493
+ more detail.
494
+ interpolate_pos_encoding (`bool`, *optional*):
495
+ Whether to interpolate the pre-trained position encodings.
496
+ return_dict (`bool`, *optional*):
497
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
498
+ """
499
+
500
+
501
+ @add_start_docstrings(
502
+ "The bare ViT Model transformer outputting raw hidden-states without any specific head on top.",
503
+ VIT_START_DOCSTRING,
504
+ )
505
+ class ViTModel(ViTPreTrainedModel):
506
+ def __init__(self, config: ViTConfig, add_pooling_layer: bool = True, use_mask_token: bool = False):
507
+ super().__init__(config)
508
+ self.config = config
509
+
510
+ self.embeddings = ViTEmbeddings(config, use_mask_token=use_mask_token)
511
+ self.encoder = ViTEncoder(config)
512
+
513
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
514
+ self.pooler = ViTPooler(config) if add_pooling_layer else None
515
+
516
+ # Initialize weights and apply final processing
517
+ self.post_init()
518
+
519
+ def get_input_embeddings(self) -> ViTPatchEmbeddings:
520
+ return self.embeddings.patch_embeddings
521
+
522
+ def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
523
+ """
524
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
525
+ class PreTrainedModel
526
+ """
527
+ for layer, heads in heads_to_prune.items():
528
+ self.encoder.layer[layer].attention.prune_heads(heads)
529
+
530
+ @add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
531
+ @add_code_sample_docstrings(
532
+ checkpoint=_CHECKPOINT_FOR_DOC,
533
+ output_type=BaseModelOutputWithPooling,
534
+ config_class=_CONFIG_FOR_DOC,
535
+ modality="vision",
536
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
537
+ )
538
+ def forward(
539
+ self,
540
+ pixel_values: Optional[torch.Tensor] = None,
541
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
542
+ head_mask: Optional[torch.Tensor] = None,
543
+ output_attentions: Optional[bool] = None,
544
+ output_hidden_states: Optional[bool] = None,
545
+ interpolate_pos_encoding: Optional[bool] = None,
546
+ return_dict: Optional[bool] = None,
547
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
548
+ r"""
549
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
550
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
551
+ """
552
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
553
+ output_hidden_states = (
554
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
555
+ )
556
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
557
+
558
+ if pixel_values is None:
559
+ raise ValueError("You have to specify pixel_values")
560
+
561
+ # Prepare head mask if needed
562
+ # 1.0 in head_mask indicate we keep the head
563
+ # attention_probs has shape bsz x n_heads x N x N
564
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
565
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
566
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
567
+
568
+ # TODO: maybe have a cleaner way to cast the input (from `ImageProcessor` side?)
569
+ expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
570
+ if pixel_values.dtype != expected_dtype:
571
+ pixel_values = pixel_values.to(expected_dtype)
572
+
573
+ embedding_output = self.embeddings(
574
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
575
+ )
576
+
577
+ encoder_outputs = self.encoder(
578
+ embedding_output,
579
+ head_mask=head_mask,
580
+ output_attentions=output_attentions,
581
+ output_hidden_states=output_hidden_states,
582
+ return_dict=return_dict,
583
+ )
584
+ sequence_output = encoder_outputs[0]
585
+ sequence_output = self.layernorm(sequence_output)
586
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
587
+
588
+ if not return_dict:
589
+ head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
590
+ return head_outputs + encoder_outputs[1:]
591
+
592
+ return BaseModelOutputWithPooling(
593
+ last_hidden_state=sequence_output,
594
+ pooler_output=pooled_output,
595
+ hidden_states=encoder_outputs.hidden_states,
596
+ attentions=encoder_outputs.attentions,
597
+ )
598
+
599
+
600
+ class ViTPooler(nn.Module):
601
+ def __init__(self, config: ViTConfig):
602
+ super().__init__()
603
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
604
+ self.activation = nn.Tanh()
605
+
606
+ def forward(self, hidden_states):
607
+ # We "pool" the model by simply taking the hidden state corresponding
608
+ # to the first token.
609
+ first_token_tensor = hidden_states[:, 0]
610
+ pooled_output = self.dense(first_token_tensor)
611
+ pooled_output = self.activation(pooled_output)
612
+ return pooled_output
613
+
614
+
615
+ @add_start_docstrings(
616
+ """ViT Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://arxiv.org/abs/2111.09886).
617
+
618
+ <Tip>
619
+
620
+ Note that we provide a script to pre-train this model on custom data in our [examples
621
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
622
+
623
+ </Tip>
624
+ """,
625
+ VIT_START_DOCSTRING,
626
+ )
627
+ class ViTForMaskedImageModeling(ViTPreTrainedModel):
628
+ def __init__(self, config: ViTConfig) -> None:
629
+ super().__init__(config)
630
+
631
+ self.vit = ViTModel(config, add_pooling_layer=False, use_mask_token=True)
632
+
633
+ self.decoder = nn.Sequential(
634
+ nn.Conv2d(
635
+ in_channels=config.hidden_size,
636
+ out_channels=config.encoder_stride**2 * config.num_channels,
637
+ kernel_size=1,
638
+ ),
639
+ nn.PixelShuffle(config.encoder_stride),
640
+ )
641
+
642
+ # Initialize weights and apply final processing
643
+ self.post_init()
644
+
645
+ @add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
646
+ @replace_return_docstrings(output_type=MaskedImageModelingOutput, config_class=_CONFIG_FOR_DOC)
647
+ def forward(
648
+ self,
649
+ pixel_values: Optional[torch.Tensor] = None,
650
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
651
+ head_mask: Optional[torch.Tensor] = None,
652
+ output_attentions: Optional[bool] = None,
653
+ output_hidden_states: Optional[bool] = None,
654
+ interpolate_pos_encoding: Optional[bool] = None,
655
+ return_dict: Optional[bool] = None,
656
+ ) -> Union[tuple, MaskedImageModelingOutput]:
657
+ r"""
658
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
659
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
660
+
661
+ Returns:
662
+
663
+ Examples:
664
+ ```python
665
+ >>> from transformers import AutoImageProcessor, ViTForMaskedImageModeling
666
+ >>> import torch
667
+ >>> from PIL import Image
668
+ >>> import requests
669
+
670
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
671
+ >>> image = Image.open(requests.get(url, stream=True).raw)
672
+
673
+ >>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
674
+ >>> model = ViTForMaskedImageModeling.from_pretrained("google/vit-base-patch16-224-in21k")
675
+
676
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
677
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
678
+ >>> # create random boolean mask of shape (batch_size, num_patches)
679
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
680
+
681
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
682
+ >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
683
+ >>> list(reconstructed_pixel_values.shape)
684
+ [1, 3, 224, 224]
685
+ ```"""
686
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
687
+
688
+ if bool_masked_pos is not None and (self.config.patch_size != self.config.encoder_stride):
689
+ raise ValueError(
690
+ "When `bool_masked_pos` is provided, `patch_size` must be equal to `encoder_stride` to ensure that "
691
+ "the reconstructed image has the same dimensions as the input. "
692
+ f"Got `patch_size` = {self.config.patch_size} and `encoder_stride` = {self.config.encoder_stride}."
693
+ )
694
+
695
+ outputs = self.vit(
696
+ pixel_values,
697
+ bool_masked_pos=bool_masked_pos,
698
+ head_mask=head_mask,
699
+ output_attentions=output_attentions,
700
+ output_hidden_states=output_hidden_states,
701
+ interpolate_pos_encoding=interpolate_pos_encoding,
702
+ return_dict=return_dict,
703
+ )
704
+
705
+ sequence_output = outputs[0]
706
+
707
+ # Reshape to (batch_size, num_channels, height, width)
708
+ sequence_output = sequence_output[:, 1:]
709
+ batch_size, sequence_length, num_channels = sequence_output.shape
710
+ height = width = math.floor(sequence_length**0.5)
711
+ sequence_output = sequence_output.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)
712
+
713
+ # Reconstruct pixel values
714
+ reconstructed_pixel_values = self.decoder(sequence_output)
715
+
716
+ masked_im_loss = None
717
+ if bool_masked_pos is not None:
718
+ size = self.config.image_size // self.config.patch_size
719
+ bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
720
+ mask = (
721
+ bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
722
+ .repeat_interleave(self.config.patch_size, 2)
723
+ .unsqueeze(1)
724
+ .contiguous()
725
+ )
726
+ reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
727
+ masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
728
+
729
+ if not return_dict:
730
+ output = (reconstructed_pixel_values,) + outputs[1:]
731
+ return ((masked_im_loss,) + output) if masked_im_loss is not None else output
732
+
733
+ return MaskedImageModelingOutput(
734
+ loss=masked_im_loss,
735
+ reconstruction=reconstructed_pixel_values,
736
+ hidden_states=outputs.hidden_states,
737
+ attentions=outputs.attentions,
738
+ )
739
+
740
+
741
+ @add_start_docstrings(
742
+ """
743
+ ViT Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
744
+ the [CLS] token) e.g. for ImageNet.
745
+
746
+ <Tip>
747
+
748
+ Note that it's possible to fine-tune ViT on higher resolution images than the ones it has been trained on, by
749
+ setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
750
+ position embeddings to the higher resolution.
751
+
752
+ </Tip>
753
+ """,
754
+ VIT_START_DOCSTRING,
755
+ )
756
+ class ViTForImageClassification(ViTPreTrainedModel):
757
+ def __init__(self, config: ViTConfig) -> None:
758
+ super().__init__(config)
759
+
760
+ self.num_labels = config.num_labels
761
+ self.vit = ViTModel(config, add_pooling_layer=False)
762
+
763
+ # Classifier head
764
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
765
+
766
+ # Initialize weights and apply final processing
767
+ self.post_init()
768
+
769
+ @add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
770
+ @add_code_sample_docstrings(
771
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
772
+ output_type=ImageClassifierOutput,
773
+ config_class=_CONFIG_FOR_DOC,
774
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
775
+ )
776
+ def forward(
777
+ self,
778
+ pixel_values: Optional[torch.Tensor] = None,
779
+ head_mask: Optional[torch.Tensor] = None,
780
+ labels: Optional[torch.Tensor] = None,
781
+ output_attentions: Optional[bool] = None,
782
+ output_hidden_states: Optional[bool] = None,
783
+ interpolate_pos_encoding: Optional[bool] = None,
784
+ return_dict: Optional[bool] = None,
785
+ ) -> Union[tuple, ImageClassifierOutput]:
786
+ r"""
787
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
788
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
789
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
790
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
791
+ """
792
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
793
+
794
+ outputs = self.vit(
795
+ pixel_values,
796
+ head_mask=head_mask,
797
+ output_attentions=output_attentions,
798
+ output_hidden_states=output_hidden_states,
799
+ interpolate_pos_encoding=interpolate_pos_encoding,
800
+ return_dict=return_dict,
801
+ )
802
+
803
+ sequence_output = outputs[0]
804
+
805
+ logits = self.classifier(sequence_output[:, 0, :])
806
+
807
+ loss = None
808
+ if labels is not None:
809
+ # move labels to correct device to enable model parallelism
810
+ labels = labels.to(logits.device)
811
+ if self.config.problem_type is None:
812
+ if self.num_labels == 1:
813
+ self.config.problem_type = "regression"
814
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
815
+ self.config.problem_type = "single_label_classification"
816
+ else:
817
+ self.config.problem_type = "multi_label_classification"
818
+
819
+ if self.config.problem_type == "regression":
820
+ loss_fct = MSELoss()
821
+ if self.num_labels == 1:
822
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
823
+ else:
824
+ loss = loss_fct(logits, labels)
825
+ elif self.config.problem_type == "single_label_classification":
826
+ loss_fct = CrossEntropyLoss()
827
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
828
+ elif self.config.problem_type == "multi_label_classification":
829
+ loss_fct = BCEWithLogitsLoss()
830
+ loss = loss_fct(logits, labels)
831
+
832
+ if not return_dict:
833
+ output = (logits,) + outputs[1:]
834
+ return ((loss,) + output) if loss is not None else output
835
+
836
+ return ImageClassifierOutput(
837
+ loss=loss,
838
+ logits=logits,
839
+ hidden_states=outputs.hidden_states,
840
+ attentions=outputs.attentions,
841
+ )
falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/RECORD ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158
3
+ colorama-0.4.6.dist-info/RECORD,,
4
+ colorama-0.4.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105
6
+ colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491
7
+ colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266
8
+ colorama/__pycache__/__init__.cpython-310.pyc,,
9
+ colorama/__pycache__/ansi.cpython-310.pyc,,
10
+ colorama/__pycache__/ansitowin32.cpython-310.pyc,,
11
+ colorama/__pycache__/initialise.cpython-310.pyc,,
12
+ colorama/__pycache__/win32.cpython-310.pyc,,
13
+ colorama/__pycache__/winterm.cpython-310.pyc,,
14
+ colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522
15
+ colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128
16
+ colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325
17
+ colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75
18
+ colorama/tests/__pycache__/__init__.cpython-310.pyc,,
19
+ colorama/tests/__pycache__/ansi_test.cpython-310.pyc,,
20
+ colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc,,
21
+ colorama/tests/__pycache__/initialise_test.cpython-310.pyc,,
22
+ colorama/tests/__pycache__/isatty_test.cpython-310.pyc,,
23
+ colorama/tests/__pycache__/utils.cpython-310.pyc,,
24
+ colorama/tests/__pycache__/winterm_test.cpython-310.pyc,,
25
+ colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839
26
+ colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678
27
+ colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741
28
+ colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866
29
+ colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079
30
+ colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709
31
+ colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181
32
+ colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134
falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/REQUESTED ADDED
File without changes
falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.11.1
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
falcon/lib/python3.10/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2010 Jonathan Hartley
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of the copyright holders, nor those of its contributors
15
+ may be used to endorse or promote products derived from this software without
16
+ specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
falcon/lib/python3.10/site-packages/dateutil/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import sys
3
+
4
+ try:
5
+ from ._version import version as __version__
6
+ except ImportError:
7
+ __version__ = 'unknown'
8
+
9
+ __all__ = ['easter', 'parser', 'relativedelta', 'rrule', 'tz',
10
+ 'utils', 'zoneinfo']
11
+
12
+ def __getattr__(name):
13
+ import importlib
14
+
15
+ if name in __all__:
16
+ return importlib.import_module("." + name, __name__)
17
+ raise AttributeError(
18
+ "module {!r} has not attribute {!r}".format(__name__, name)
19
+ )
20
+
21
+
22
+ def __dir__():
23
+ # __dir__ should include all the lazy-importable modules as well.
24
+ return [x for x in globals() if x not in sys.modules] + __all__
falcon/lib/python3.10/site-packages/dateutil/__pycache__/relativedelta.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
falcon/lib/python3.10/site-packages/dateutil/__pycache__/tzwin.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
falcon/lib/python3.10/site-packages/dateutil/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.24 kB). View file
 
falcon/lib/python3.10/site-packages/dateutil/_common.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Common code used in multiple modules.
3
+ """
4
+
5
+
6
+ class weekday(object):
7
+ __slots__ = ["weekday", "n"]
8
+
9
+ def __init__(self, weekday, n=None):
10
+ self.weekday = weekday
11
+ self.n = n
12
+
13
+ def __call__(self, n):
14
+ if n == self.n:
15
+ return self
16
+ else:
17
+ return self.__class__(self.weekday, n)
18
+
19
+ def __eq__(self, other):
20
+ try:
21
+ if self.weekday != other.weekday or self.n != other.n:
22
+ return False
23
+ except AttributeError:
24
+ return False
25
+ return True
26
+
27
+ def __hash__(self):
28
+ return hash((
29
+ self.weekday,
30
+ self.n,
31
+ ))
32
+
33
+ def __ne__(self, other):
34
+ return not (self == other)
35
+
36
+ def __repr__(self):
37
+ s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday]
38
+ if not self.n:
39
+ return s
40
+ else:
41
+ return "%s(%+d)" % (s, self.n)
42
+
43
+ # vim:ts=4:sw=4:et
falcon/lib/python3.10/site-packages/dateutil/_version.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ __version__ = version = '2.9.0.post0'
4
+ __version_tuple__ = version_tuple = (2, 9, 0)
falcon/lib/python3.10/site-packages/dateutil/easter.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ This module offers a generic Easter computing method for any given year, using
4
+ Western, Orthodox or Julian algorithms.
5
+ """
6
+
7
+ import datetime
8
+
9
+ __all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"]
10
+
11
+ EASTER_JULIAN = 1
12
+ EASTER_ORTHODOX = 2
13
+ EASTER_WESTERN = 3
14
+
15
+
16
+ def easter(year, method=EASTER_WESTERN):
17
+ """
18
+ This method was ported from the work done by GM Arts,
19
+ on top of the algorithm by Claus Tondering, which was
20
+ based in part on the algorithm of Ouding (1940), as
21
+ quoted in "Explanatory Supplement to the Astronomical
22
+ Almanac", P. Kenneth Seidelmann, editor.
23
+
24
+ This algorithm implements three different Easter
25
+ calculation methods:
26
+
27
+ 1. Original calculation in Julian calendar, valid in
28
+ dates after 326 AD
29
+ 2. Original method, with date converted to Gregorian
30
+ calendar, valid in years 1583 to 4099
31
+ 3. Revised method, in Gregorian calendar, valid in
32
+ years 1583 to 4099 as well
33
+
34
+ These methods are represented by the constants:
35
+
36
+ * ``EASTER_JULIAN = 1``
37
+ * ``EASTER_ORTHODOX = 2``
38
+ * ``EASTER_WESTERN = 3``
39
+
40
+ The default method is method 3.
41
+
42
+ More about the algorithm may be found at:
43
+
44
+ `GM Arts: Easter Algorithms <http://www.gmarts.org/index.php?go=415>`_
45
+
46
+ and
47
+
48
+ `The Calendar FAQ: Easter <https://www.tondering.dk/claus/cal/easter.php>`_
49
+
50
+ """
51
+
52
+ if not (1 <= method <= 3):
53
+ raise ValueError("invalid method")
54
+
55
+ # g - Golden year - 1
56
+ # c - Century
57
+ # h - (23 - Epact) mod 30
58
+ # i - Number of days from March 21 to Paschal Full Moon
59
+ # j - Weekday for PFM (0=Sunday, etc)
60
+ # p - Number of days from March 21 to Sunday on or before PFM
61
+ # (-6 to 28 methods 1 & 3, to 56 for method 2)
62
+ # e - Extra days to add for method 2 (converting Julian
63
+ # date to Gregorian date)
64
+
65
+ y = year
66
+ g = y % 19
67
+ e = 0
68
+ if method < 3:
69
+ # Old method
70
+ i = (19*g + 15) % 30
71
+ j = (y + y//4 + i) % 7
72
+ if method == 2:
73
+ # Extra dates to convert Julian to Gregorian date
74
+ e = 10
75
+ if y > 1600:
76
+ e = e + y//100 - 16 - (y//100 - 16)//4
77
+ else:
78
+ # New method
79
+ c = y//100
80
+ h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30
81
+ i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11))
82
+ j = (y + y//4 + i + 2 - c + c//4) % 7
83
+
84
+ # p can be from -6 to 56 corresponding to dates 22 March to 23 May
85
+ # (later dates apply to method 2, although 23 May never actually occurs)
86
+ p = i - j + e
87
+ d = 1 + (p + 27 + (p + 6)//40) % 31
88
+ m = 3 + (p + 26)//30
89
+ return datetime.date(int(y), int(m), int(d))
falcon/lib/python3.10/site-packages/dateutil/parser/__init__.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from ._parser import parse, parser, parserinfo, ParserError
3
+ from ._parser import DEFAULTPARSER, DEFAULTTZPARSER
4
+ from ._parser import UnknownTimezoneWarning
5
+
6
+ from ._parser import __doc__
7
+
8
+ from .isoparser import isoparser, isoparse
9
+
10
+ __all__ = ['parse', 'parser', 'parserinfo',
11
+ 'isoparse', 'isoparser',
12
+ 'ParserError',
13
+ 'UnknownTimezoneWarning']
14
+
15
+
16
+ ###
17
+ # Deprecate portions of the private interface so that downstream code that
18
+ # is improperly relying on it is given *some* notice.
19
+
20
+
21
+ def __deprecated_private_func(f):
22
+ from functools import wraps
23
+ import warnings
24
+
25
+ msg = ('{name} is a private function and may break without warning, '
26
+ 'it will be moved and or renamed in future versions.')
27
+ msg = msg.format(name=f.__name__)
28
+
29
+ @wraps(f)
30
+ def deprecated_func(*args, **kwargs):
31
+ warnings.warn(msg, DeprecationWarning)
32
+ return f(*args, **kwargs)
33
+
34
+ return deprecated_func
35
+
36
+ def __deprecate_private_class(c):
37
+ import warnings
38
+
39
+ msg = ('{name} is a private class and may break without warning, '
40
+ 'it will be moved and or renamed in future versions.')
41
+ msg = msg.format(name=c.__name__)
42
+
43
+ class private_class(c):
44
+ __doc__ = c.__doc__
45
+
46
+ def __init__(self, *args, **kwargs):
47
+ warnings.warn(msg, DeprecationWarning)
48
+ super(private_class, self).__init__(*args, **kwargs)
49
+
50
+ private_class.__name__ = c.__name__
51
+
52
+ return private_class
53
+
54
+
55
+ from ._parser import _timelex, _resultbase
56
+ from ._parser import _tzparser, _parsetz
57
+
58
+ _timelex = __deprecate_private_class(_timelex)
59
+ _tzparser = __deprecate_private_class(_tzparser)
60
+ _resultbase = __deprecate_private_class(_resultbase)
61
+ _parsetz = __deprecated_private_func(_parsetz)
falcon/lib/python3.10/site-packages/dateutil/parser/__pycache__/_parser.cpython-310.pyc ADDED
Binary file (40.5 kB). View file