Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/__init__.py +142 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/configuration_camembert.py +155 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/modeling_camembert.py +1571 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/modeling_tf_camembert.py +1793 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert.py +319 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert_fast.py +199 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__init__.py +183 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/configuration_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/convert_clip_original_pytorch_to_hf.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/feature_extraction_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/image_processing_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/modeling_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/modeling_flax_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/modeling_tf_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/processing_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/tokenization_clip.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/tokenization_clip_fast.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/configuration_clip.py +456 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/convert_clip_original_pytorch_to_hf.py +148 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/feature_extraction_clip.py +33 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/image_processing_clip.py +346 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/modeling_clip.py +1416 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/modeling_flax_clip.py +1295 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/modeling_tf_clip.py +1461 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/processing_clip.py +153 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/tokenization_clip.py +516 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/clip/tokenization_clip_fast.py +159 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__init__.py +127 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/configuration_deberta_v2.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/modeling_deberta_v2.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/modeling_tf_deberta_v2.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2_fast.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/configuration_deberta_v2.py +192 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/modeling_deberta_v2.py +1629 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/modeling_tf_deberta_v2.py +1874 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/tokenization_deberta_v2.py +521 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/tokenization_deberta_v2_fast.py +220 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/persimmon/__pycache__/configuration_persimmon.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/persimmon/__pycache__/convert_persimmon_weights_to_hf.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/persimmon/__pycache__/modeling_persimmon.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__init__.py +122 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/configuration_pop2piano.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/convert_pop2piano_weights_to_hf.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/feature_extraction_pop2piano.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/modeling_pop2piano.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/processing_pop2piano.cpython-310.pyc +0 -0
llmeval-env/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__)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/configuration_camembert.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
29 |
+
from ..deprecated._archive_maps import CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
|
30 |
+
|
31 |
+
|
32 |
+
class CamembertConfig(PretrainedConfig):
|
33 |
+
"""
|
34 |
+
This is the configuration class to store the configuration of a [`CamembertModel`] or a [`TFCamembertModel`]. It is
|
35 |
+
used to instantiate a Camembert model according to the specified arguments, defining the model architecture.
|
36 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the Camembert
|
37 |
+
[almanach/camembert-base](https://huggingface.co/almanach/camembert-base) architecture.
|
38 |
+
|
39 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
40 |
+
documentation from [`PretrainedConfig`] for more information.
|
41 |
+
|
42 |
+
|
43 |
+
Args:
|
44 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
45 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
46 |
+
`inputs_ids` passed when calling [`CamembertModel`] or [`TFCamembertModel`].
|
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" (often named feed-forward) layer in the Transformer encoder.
|
55 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
56 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
57 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
58 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
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.1):
|
61 |
+
The dropout ratio for the attention probabilities.
|
62 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
63 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
64 |
+
just in case (e.g., 512 or 1024 or 2048).
|
65 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
66 |
+
The vocabulary size of the `token_type_ids` passed when calling [`CamembertModel`] or [`TFCamembertModel`].
|
67 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
68 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
69 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
70 |
+
The epsilon used by the layer normalization layers.
|
71 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
72 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
73 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
74 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
75 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
76 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
77 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
78 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
79 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
80 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
81 |
+
relevant if `config.is_decoder=True`.
|
82 |
+
classifier_dropout (`float`, *optional*):
|
83 |
+
The dropout ratio for the classification head.
|
84 |
+
|
85 |
+
Example:
|
86 |
+
|
87 |
+
```python
|
88 |
+
>>> from transformers import CamembertConfig, CamembertModel
|
89 |
+
|
90 |
+
>>> # Initializing a Camembert almanach/camembert-base style configuration
|
91 |
+
>>> configuration = CamembertConfig()
|
92 |
+
|
93 |
+
>>> # Initializing a model (with random weights) from the almanach/camembert-base style configuration
|
94 |
+
>>> model = CamembertModel(configuration)
|
95 |
+
|
96 |
+
>>> # Accessing the model configuration
|
97 |
+
>>> configuration = model.config
|
98 |
+
```"""
|
99 |
+
|
100 |
+
model_type = "camembert"
|
101 |
+
|
102 |
+
def __init__(
|
103 |
+
self,
|
104 |
+
vocab_size=30522,
|
105 |
+
hidden_size=768,
|
106 |
+
num_hidden_layers=12,
|
107 |
+
num_attention_heads=12,
|
108 |
+
intermediate_size=3072,
|
109 |
+
hidden_act="gelu",
|
110 |
+
hidden_dropout_prob=0.1,
|
111 |
+
attention_probs_dropout_prob=0.1,
|
112 |
+
max_position_embeddings=512,
|
113 |
+
type_vocab_size=2,
|
114 |
+
initializer_range=0.02,
|
115 |
+
layer_norm_eps=1e-12,
|
116 |
+
pad_token_id=1,
|
117 |
+
bos_token_id=0,
|
118 |
+
eos_token_id=2,
|
119 |
+
position_embedding_type="absolute",
|
120 |
+
use_cache=True,
|
121 |
+
classifier_dropout=None,
|
122 |
+
**kwargs,
|
123 |
+
):
|
124 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
125 |
+
|
126 |
+
self.vocab_size = vocab_size
|
127 |
+
self.hidden_size = hidden_size
|
128 |
+
self.num_hidden_layers = num_hidden_layers
|
129 |
+
self.num_attention_heads = num_attention_heads
|
130 |
+
self.hidden_act = hidden_act
|
131 |
+
self.intermediate_size = intermediate_size
|
132 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
133 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
134 |
+
self.max_position_embeddings = max_position_embeddings
|
135 |
+
self.type_vocab_size = type_vocab_size
|
136 |
+
self.initializer_range = initializer_range
|
137 |
+
self.layer_norm_eps = layer_norm_eps
|
138 |
+
self.position_embedding_type = position_embedding_type
|
139 |
+
self.use_cache = use_cache
|
140 |
+
self.classifier_dropout = classifier_dropout
|
141 |
+
|
142 |
+
|
143 |
+
class CamembertOnnxConfig(OnnxConfig):
|
144 |
+
@property
|
145 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
146 |
+
if self.task == "multiple-choice":
|
147 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
148 |
+
else:
|
149 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
150 |
+
return OrderedDict(
|
151 |
+
[
|
152 |
+
("input_ids", dynamic_axis),
|
153 |
+
("attention_mask", dynamic_axis),
|
154 |
+
]
|
155 |
+
)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/modeling_camembert.py
ADDED
@@ -0,0 +1,1571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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served.
|
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 = "almanach/camembert-base"
|
52 |
+
_CONFIG_FOR_DOC = "CamembertConfig"
|
53 |
+
|
54 |
+
|
55 |
+
from ..deprecated._archive_maps import CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
56 |
+
|
57 |
+
|
58 |
+
CAMEMBERT_START_DOCSTRING = r"""
|
59 |
+
|
60 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
61 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
62 |
+
etc.)
|
63 |
+
|
64 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
65 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
66 |
+
and behavior.
|
67 |
+
|
68 |
+
Parameters:
|
69 |
+
config ([`CamembertConfig`]): Model configuration class with all the parameters of the
|
70 |
+
model. Initializing with a config file does not load the weights associated with the model, only the
|
71 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
72 |
+
"""
|
73 |
+
|
74 |
+
|
75 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->Camembert
|
76 |
+
class CamembertEmbeddings(nn.Module):
|
77 |
+
"""
|
78 |
+
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
|
79 |
+
"""
|
80 |
+
|
81 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
|
82 |
+
def __init__(self, config):
|
83 |
+
super().__init__()
|
84 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
85 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
86 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
87 |
+
|
88 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
89 |
+
# any TensorFlow checkpoint file
|
90 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
91 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
92 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
93 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
94 |
+
self.register_buffer(
|
95 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
96 |
+
)
|
97 |
+
self.register_buffer(
|
98 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
99 |
+
)
|
100 |
+
|
101 |
+
# End copy
|
102 |
+
self.padding_idx = config.pad_token_id
|
103 |
+
self.position_embeddings = nn.Embedding(
|
104 |
+
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
|
105 |
+
)
|
106 |
+
|
107 |
+
def forward(
|
108 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
109 |
+
):
|
110 |
+
if position_ids is None:
|
111 |
+
if input_ids is not None:
|
112 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
113 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
114 |
+
else:
|
115 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
116 |
+
|
117 |
+
if input_ids is not None:
|
118 |
+
input_shape = input_ids.size()
|
119 |
+
else:
|
120 |
+
input_shape = inputs_embeds.size()[:-1]
|
121 |
+
|
122 |
+
seq_length = input_shape[1]
|
123 |
+
|
124 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
125 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
126 |
+
# issue #5664
|
127 |
+
if token_type_ids is None:
|
128 |
+
if hasattr(self, "token_type_ids"):
|
129 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
130 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
131 |
+
token_type_ids = buffered_token_type_ids_expanded
|
132 |
+
else:
|
133 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
134 |
+
|
135 |
+
if inputs_embeds is None:
|
136 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
137 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
138 |
+
|
139 |
+
embeddings = inputs_embeds + token_type_embeddings
|
140 |
+
if self.position_embedding_type == "absolute":
|
141 |
+
position_embeddings = self.position_embeddings(position_ids)
|
142 |
+
embeddings += position_embeddings
|
143 |
+
embeddings = self.LayerNorm(embeddings)
|
144 |
+
embeddings = self.dropout(embeddings)
|
145 |
+
return embeddings
|
146 |
+
|
147 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
|
148 |
+
"""
|
149 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
150 |
+
|
151 |
+
Args:
|
152 |
+
inputs_embeds: torch.Tensor
|
153 |
+
|
154 |
+
Returns: torch.Tensor
|
155 |
+
"""
|
156 |
+
input_shape = inputs_embeds.size()[:-1]
|
157 |
+
sequence_length = input_shape[1]
|
158 |
+
|
159 |
+
position_ids = torch.arange(
|
160 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
161 |
+
)
|
162 |
+
return position_ids.unsqueeze(0).expand(input_shape)
|
163 |
+
|
164 |
+
|
165 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->Camembert
|
166 |
+
class CamembertSelfAttention(nn.Module):
|
167 |
+
def __init__(self, config, position_embedding_type=None):
|
168 |
+
super().__init__()
|
169 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
170 |
+
raise ValueError(
|
171 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
172 |
+
f"heads ({config.num_attention_heads})"
|
173 |
+
)
|
174 |
+
|
175 |
+
self.num_attention_heads = config.num_attention_heads
|
176 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
177 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
178 |
+
|
179 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
180 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
181 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
182 |
+
|
183 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
184 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
185 |
+
config, "position_embedding_type", "absolute"
|
186 |
+
)
|
187 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
188 |
+
self.max_position_embeddings = config.max_position_embeddings
|
189 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
190 |
+
|
191 |
+
self.is_decoder = config.is_decoder
|
192 |
+
|
193 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
194 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
195 |
+
x = x.view(new_x_shape)
|
196 |
+
return x.permute(0, 2, 1, 3)
|
197 |
+
|
198 |
+
def forward(
|
199 |
+
self,
|
200 |
+
hidden_states: torch.Tensor,
|
201 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
202 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
203 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
204 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
205 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
206 |
+
output_attentions: Optional[bool] = False,
|
207 |
+
) -> Tuple[torch.Tensor]:
|
208 |
+
mixed_query_layer = self.query(hidden_states)
|
209 |
+
|
210 |
+
# If this is instantiated as a cross-attention module, the keys
|
211 |
+
# and values come from an encoder; the attention mask needs to be
|
212 |
+
# such that the encoder's padding tokens are not attended to.
|
213 |
+
is_cross_attention = encoder_hidden_states is not None
|
214 |
+
|
215 |
+
if is_cross_attention and past_key_value is not None:
|
216 |
+
# reuse k,v, cross_attentions
|
217 |
+
key_layer = past_key_value[0]
|
218 |
+
value_layer = past_key_value[1]
|
219 |
+
attention_mask = encoder_attention_mask
|
220 |
+
elif is_cross_attention:
|
221 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
222 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
223 |
+
attention_mask = encoder_attention_mask
|
224 |
+
elif past_key_value is not None:
|
225 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
226 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
227 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
228 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
229 |
+
else:
|
230 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
231 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
232 |
+
|
233 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
234 |
+
|
235 |
+
use_cache = past_key_value is not None
|
236 |
+
if self.is_decoder:
|
237 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
238 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
239 |
+
# key/value_states (first "if" case)
|
240 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
241 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
242 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
243 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
244 |
+
past_key_value = (key_layer, value_layer)
|
245 |
+
|
246 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
247 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
248 |
+
|
249 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
250 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
251 |
+
if use_cache:
|
252 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
253 |
+
-1, 1
|
254 |
+
)
|
255 |
+
else:
|
256 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
257 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
258 |
+
distance = position_ids_l - position_ids_r
|
259 |
+
|
260 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
261 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
262 |
+
|
263 |
+
if self.position_embedding_type == "relative_key":
|
264 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
265 |
+
attention_scores = attention_scores + relative_position_scores
|
266 |
+
elif self.position_embedding_type == "relative_key_query":
|
267 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
268 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
269 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
270 |
+
|
271 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
272 |
+
if attention_mask is not None:
|
273 |
+
# Apply the attention mask is (precomputed for all layers in CamembertModel forward() function)
|
274 |
+
attention_scores = attention_scores + attention_mask
|
275 |
+
|
276 |
+
# Normalize the attention scores to probabilities.
|
277 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
278 |
+
|
279 |
+
# This is actually dropping out entire tokens to attend to, which might
|
280 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
281 |
+
attention_probs = self.dropout(attention_probs)
|
282 |
+
|
283 |
+
# Mask heads if we want to
|
284 |
+
if head_mask is not None:
|
285 |
+
attention_probs = attention_probs * head_mask
|
286 |
+
|
287 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
288 |
+
|
289 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
290 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
291 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
292 |
+
|
293 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
294 |
+
|
295 |
+
if self.is_decoder:
|
296 |
+
outputs = outputs + (past_key_value,)
|
297 |
+
return outputs
|
298 |
+
|
299 |
+
|
300 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput with Roberta->Camembert
|
301 |
+
class CamembertSelfOutput(nn.Module):
|
302 |
+
def __init__(self, config):
|
303 |
+
super().__init__()
|
304 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
305 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
306 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
307 |
+
|
308 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
309 |
+
hidden_states = self.dense(hidden_states)
|
310 |
+
hidden_states = self.dropout(hidden_states)
|
311 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
312 |
+
return hidden_states
|
313 |
+
|
314 |
+
|
315 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaAttention with Roberta->Camembert
|
316 |
+
class CamembertAttention(nn.Module):
|
317 |
+
def __init__(self, config, position_embedding_type=None):
|
318 |
+
super().__init__()
|
319 |
+
self.self = CamembertSelfAttention(config, position_embedding_type=position_embedding_type)
|
320 |
+
self.output = CamembertSelfOutput(config)
|
321 |
+
self.pruned_heads = set()
|
322 |
+
|
323 |
+
def prune_heads(self, heads):
|
324 |
+
if len(heads) == 0:
|
325 |
+
return
|
326 |
+
heads, index = find_pruneable_heads_and_indices(
|
327 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
328 |
+
)
|
329 |
+
|
330 |
+
# Prune linear layers
|
331 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
332 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
333 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
334 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
335 |
+
|
336 |
+
# Update hyper params and store pruned heads
|
337 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
338 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
339 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
340 |
+
|
341 |
+
def forward(
|
342 |
+
self,
|
343 |
+
hidden_states: torch.Tensor,
|
344 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
345 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
346 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
347 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
348 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
349 |
+
output_attentions: Optional[bool] = False,
|
350 |
+
) -> Tuple[torch.Tensor]:
|
351 |
+
self_outputs = self.self(
|
352 |
+
hidden_states,
|
353 |
+
attention_mask,
|
354 |
+
head_mask,
|
355 |
+
encoder_hidden_states,
|
356 |
+
encoder_attention_mask,
|
357 |
+
past_key_value,
|
358 |
+
output_attentions,
|
359 |
+
)
|
360 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
361 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
362 |
+
return outputs
|
363 |
+
|
364 |
+
|
365 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Roberta->Camembert
|
366 |
+
class CamembertIntermediate(nn.Module):
|
367 |
+
def __init__(self, config):
|
368 |
+
super().__init__()
|
369 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
370 |
+
if isinstance(config.hidden_act, str):
|
371 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
372 |
+
else:
|
373 |
+
self.intermediate_act_fn = config.hidden_act
|
374 |
+
|
375 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
376 |
+
hidden_states = self.dense(hidden_states)
|
377 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
378 |
+
return hidden_states
|
379 |
+
|
380 |
+
|
381 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Roberta->Camembert
|
382 |
+
class CamembertOutput(nn.Module):
|
383 |
+
def __init__(self, config):
|
384 |
+
super().__init__()
|
385 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
386 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
387 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
388 |
+
|
389 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
390 |
+
hidden_states = self.dense(hidden_states)
|
391 |
+
hidden_states = self.dropout(hidden_states)
|
392 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
393 |
+
return hidden_states
|
394 |
+
|
395 |
+
|
396 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaLayer with Roberta->Camembert
|
397 |
+
class CamembertLayer(nn.Module):
|
398 |
+
def __init__(self, config):
|
399 |
+
super().__init__()
|
400 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
401 |
+
self.seq_len_dim = 1
|
402 |
+
self.attention = CamembertAttention(config)
|
403 |
+
self.is_decoder = config.is_decoder
|
404 |
+
self.add_cross_attention = config.add_cross_attention
|
405 |
+
if self.add_cross_attention:
|
406 |
+
if not self.is_decoder:
|
407 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
408 |
+
self.crossattention = CamembertAttention(config, position_embedding_type="absolute")
|
409 |
+
self.intermediate = CamembertIntermediate(config)
|
410 |
+
self.output = CamembertOutput(config)
|
411 |
+
|
412 |
+
def forward(
|
413 |
+
self,
|
414 |
+
hidden_states: torch.Tensor,
|
415 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
416 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
417 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
418 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
419 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
420 |
+
output_attentions: Optional[bool] = False,
|
421 |
+
) -> Tuple[torch.Tensor]:
|
422 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
423 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
424 |
+
self_attention_outputs = self.attention(
|
425 |
+
hidden_states,
|
426 |
+
attention_mask,
|
427 |
+
head_mask,
|
428 |
+
output_attentions=output_attentions,
|
429 |
+
past_key_value=self_attn_past_key_value,
|
430 |
+
)
|
431 |
+
attention_output = self_attention_outputs[0]
|
432 |
+
|
433 |
+
# if decoder, the last output is tuple of self-attn cache
|
434 |
+
if self.is_decoder:
|
435 |
+
outputs = self_attention_outputs[1:-1]
|
436 |
+
present_key_value = self_attention_outputs[-1]
|
437 |
+
else:
|
438 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
439 |
+
|
440 |
+
cross_attn_present_key_value = None
|
441 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
442 |
+
if not hasattr(self, "crossattention"):
|
443 |
+
raise ValueError(
|
444 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
445 |
+
" by setting `config.add_cross_attention=True`"
|
446 |
+
)
|
447 |
+
|
448 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
449 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
450 |
+
cross_attention_outputs = self.crossattention(
|
451 |
+
attention_output,
|
452 |
+
attention_mask,
|
453 |
+
head_mask,
|
454 |
+
encoder_hidden_states,
|
455 |
+
encoder_attention_mask,
|
456 |
+
cross_attn_past_key_value,
|
457 |
+
output_attentions,
|
458 |
+
)
|
459 |
+
attention_output = cross_attention_outputs[0]
|
460 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
461 |
+
|
462 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
463 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
464 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
465 |
+
|
466 |
+
layer_output = apply_chunking_to_forward(
|
467 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
468 |
+
)
|
469 |
+
outputs = (layer_output,) + outputs
|
470 |
+
|
471 |
+
# if decoder, return the attn key/values as the last output
|
472 |
+
if self.is_decoder:
|
473 |
+
outputs = outputs + (present_key_value,)
|
474 |
+
|
475 |
+
return outputs
|
476 |
+
|
477 |
+
def feed_forward_chunk(self, attention_output):
|
478 |
+
intermediate_output = self.intermediate(attention_output)
|
479 |
+
layer_output = self.output(intermediate_output, attention_output)
|
480 |
+
return layer_output
|
481 |
+
|
482 |
+
|
483 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->Camembert
|
484 |
+
class CamembertEncoder(nn.Module):
|
485 |
+
def __init__(self, config):
|
486 |
+
super().__init__()
|
487 |
+
self.config = config
|
488 |
+
self.layer = nn.ModuleList([CamembertLayer(config) for _ in range(config.num_hidden_layers)])
|
489 |
+
self.gradient_checkpointing = False
|
490 |
+
|
491 |
+
def forward(
|
492 |
+
self,
|
493 |
+
hidden_states: torch.Tensor,
|
494 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
495 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
496 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
497 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
498 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
499 |
+
use_cache: Optional[bool] = None,
|
500 |
+
output_attentions: Optional[bool] = False,
|
501 |
+
output_hidden_states: Optional[bool] = False,
|
502 |
+
return_dict: Optional[bool] = True,
|
503 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
504 |
+
all_hidden_states = () if output_hidden_states else None
|
505 |
+
all_self_attentions = () if output_attentions else None
|
506 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
507 |
+
|
508 |
+
if self.gradient_checkpointing and self.training:
|
509 |
+
if use_cache:
|
510 |
+
logger.warning_once(
|
511 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
512 |
+
)
|
513 |
+
use_cache = False
|
514 |
+
|
515 |
+
next_decoder_cache = () if use_cache else None
|
516 |
+
for i, layer_module in enumerate(self.layer):
|
517 |
+
if output_hidden_states:
|
518 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
519 |
+
|
520 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
521 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
522 |
+
|
523 |
+
if self.gradient_checkpointing and self.training:
|
524 |
+
layer_outputs = self._gradient_checkpointing_func(
|
525 |
+
layer_module.__call__,
|
526 |
+
hidden_states,
|
527 |
+
attention_mask,
|
528 |
+
layer_head_mask,
|
529 |
+
encoder_hidden_states,
|
530 |
+
encoder_attention_mask,
|
531 |
+
past_key_value,
|
532 |
+
output_attentions,
|
533 |
+
)
|
534 |
+
else:
|
535 |
+
layer_outputs = layer_module(
|
536 |
+
hidden_states,
|
537 |
+
attention_mask,
|
538 |
+
layer_head_mask,
|
539 |
+
encoder_hidden_states,
|
540 |
+
encoder_attention_mask,
|
541 |
+
past_key_value,
|
542 |
+
output_attentions,
|
543 |
+
)
|
544 |
+
|
545 |
+
hidden_states = layer_outputs[0]
|
546 |
+
if use_cache:
|
547 |
+
next_decoder_cache += (layer_outputs[-1],)
|
548 |
+
if output_attentions:
|
549 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
550 |
+
if self.config.add_cross_attention:
|
551 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
552 |
+
|
553 |
+
if output_hidden_states:
|
554 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
555 |
+
|
556 |
+
if not return_dict:
|
557 |
+
return tuple(
|
558 |
+
v
|
559 |
+
for v in [
|
560 |
+
hidden_states,
|
561 |
+
next_decoder_cache,
|
562 |
+
all_hidden_states,
|
563 |
+
all_self_attentions,
|
564 |
+
all_cross_attentions,
|
565 |
+
]
|
566 |
+
if v is not None
|
567 |
+
)
|
568 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
569 |
+
last_hidden_state=hidden_states,
|
570 |
+
past_key_values=next_decoder_cache,
|
571 |
+
hidden_states=all_hidden_states,
|
572 |
+
attentions=all_self_attentions,
|
573 |
+
cross_attentions=all_cross_attentions,
|
574 |
+
)
|
575 |
+
|
576 |
+
|
577 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler
|
578 |
+
class CamembertPooler(nn.Module):
|
579 |
+
def __init__(self, config):
|
580 |
+
super().__init__()
|
581 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
582 |
+
self.activation = nn.Tanh()
|
583 |
+
|
584 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
585 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
586 |
+
# to the first token.
|
587 |
+
first_token_tensor = hidden_states[:, 0]
|
588 |
+
pooled_output = self.dense(first_token_tensor)
|
589 |
+
pooled_output = self.activation(pooled_output)
|
590 |
+
return pooled_output
|
591 |
+
|
592 |
+
|
593 |
+
class CamembertPreTrainedModel(PreTrainedModel):
|
594 |
+
"""
|
595 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
596 |
+
models.
|
597 |
+
"""
|
598 |
+
|
599 |
+
config_class = CamembertConfig
|
600 |
+
base_model_prefix = "roberta"
|
601 |
+
supports_gradient_checkpointing = True
|
602 |
+
|
603 |
+
# Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
|
604 |
+
def _init_weights(self, module):
|
605 |
+
"""Initialize the weights"""
|
606 |
+
if isinstance(module, nn.Linear):
|
607 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
608 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
609 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
610 |
+
if module.bias is not None:
|
611 |
+
module.bias.data.zero_()
|
612 |
+
elif isinstance(module, nn.Embedding):
|
613 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
614 |
+
if module.padding_idx is not None:
|
615 |
+
module.weight.data[module.padding_idx].zero_()
|
616 |
+
elif isinstance(module, nn.LayerNorm):
|
617 |
+
module.bias.data.zero_()
|
618 |
+
module.weight.data.fill_(1.0)
|
619 |
+
|
620 |
+
|
621 |
+
CAMEMBERT_INPUTS_DOCSTRING = r"""
|
622 |
+
Args:
|
623 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
624 |
+
Indices of input sequence tokens in the vocabulary.
|
625 |
+
|
626 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
627 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
628 |
+
|
629 |
+
[What are input IDs?](../glossary#input-ids)
|
630 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
631 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
632 |
+
|
633 |
+
- 1 for tokens that are **not masked**,
|
634 |
+
- 0 for tokens that are **masked**.
|
635 |
+
|
636 |
+
[What are attention masks?](../glossary#attention-mask)
|
637 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
638 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
639 |
+
1]`:
|
640 |
+
|
641 |
+
- 0 corresponds to a *sentence A* token,
|
642 |
+
- 1 corresponds to a *sentence B* token.
|
643 |
+
|
644 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
645 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
646 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
647 |
+
config.max_position_embeddings - 1]`.
|
648 |
+
|
649 |
+
[What are position IDs?](../glossary#position-ids)
|
650 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
651 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
652 |
+
|
653 |
+
- 1 indicates the head is **not masked**,
|
654 |
+
- 0 indicates the head is **masked**.
|
655 |
+
|
656 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
657 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
658 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
659 |
+
model's internal embedding lookup matrix.
|
660 |
+
output_attentions (`bool`, *optional*):
|
661 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
662 |
+
tensors for more detail.
|
663 |
+
output_hidden_states (`bool`, *optional*):
|
664 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
665 |
+
more detail.
|
666 |
+
return_dict (`bool`, *optional*):
|
667 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
668 |
+
"""
|
669 |
+
|
670 |
+
|
671 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->Camembert
|
672 |
+
class CamembertClassificationHead(nn.Module):
|
673 |
+
"""Head for sentence-level classification tasks."""
|
674 |
+
|
675 |
+
def __init__(self, config):
|
676 |
+
super().__init__()
|
677 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
678 |
+
classifier_dropout = (
|
679 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
680 |
+
)
|
681 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
682 |
+
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
|
683 |
+
|
684 |
+
def forward(self, features, **kwargs):
|
685 |
+
x = features[:, 0, :] # take <s> token (equiv. to [CLS])
|
686 |
+
x = self.dropout(x)
|
687 |
+
x = self.dense(x)
|
688 |
+
x = torch.tanh(x)
|
689 |
+
x = self.dropout(x)
|
690 |
+
x = self.out_proj(x)
|
691 |
+
return x
|
692 |
+
|
693 |
+
|
694 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead with Roberta->Camembert
|
695 |
+
class CamembertLMHead(nn.Module):
|
696 |
+
"""Camembert Head for masked language modeling."""
|
697 |
+
|
698 |
+
def __init__(self, config):
|
699 |
+
super().__init__()
|
700 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
701 |
+
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
702 |
+
|
703 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
|
704 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
705 |
+
self.decoder.bias = self.bias
|
706 |
+
|
707 |
+
def forward(self, features, **kwargs):
|
708 |
+
x = self.dense(features)
|
709 |
+
x = gelu(x)
|
710 |
+
x = self.layer_norm(x)
|
711 |
+
|
712 |
+
# project back to size of vocabulary with bias
|
713 |
+
x = self.decoder(x)
|
714 |
+
|
715 |
+
return x
|
716 |
+
|
717 |
+
def _tie_weights(self):
|
718 |
+
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
|
719 |
+
# For accelerate compatibility and to not break backward compatibility
|
720 |
+
if self.decoder.bias.device.type == "meta":
|
721 |
+
self.decoder.bias = self.bias
|
722 |
+
else:
|
723 |
+
self.bias = self.decoder.bias
|
724 |
+
|
725 |
+
|
726 |
+
@add_start_docstrings(
|
727 |
+
"The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.",
|
728 |
+
CAMEMBERT_START_DOCSTRING,
|
729 |
+
)
|
730 |
+
class CamembertModel(CamembertPreTrainedModel):
|
731 |
+
"""
|
732 |
+
|
733 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
734 |
+
cross-attention is added between the self-attention layers, following the architecture described in *Attention is
|
735 |
+
all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
|
736 |
+
Kaiser and Illia Polosukhin.
|
737 |
+
|
738 |
+
To behave as a decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to
|
739 |
+
`True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
740 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
741 |
+
|
742 |
+
.. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
|
743 |
+
|
744 |
+
"""
|
745 |
+
|
746 |
+
_no_split_modules = []
|
747 |
+
|
748 |
+
# Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Camembert
|
749 |
+
def __init__(self, config, add_pooling_layer=True):
|
750 |
+
super().__init__(config)
|
751 |
+
self.config = config
|
752 |
+
|
753 |
+
self.embeddings = CamembertEmbeddings(config)
|
754 |
+
self.encoder = CamembertEncoder(config)
|
755 |
+
|
756 |
+
self.pooler = CamembertPooler(config) if add_pooling_layer else None
|
757 |
+
|
758 |
+
# Initialize weights and apply final processing
|
759 |
+
self.post_init()
|
760 |
+
|
761 |
+
def get_input_embeddings(self):
|
762 |
+
return self.embeddings.word_embeddings
|
763 |
+
|
764 |
+
def set_input_embeddings(self, value):
|
765 |
+
self.embeddings.word_embeddings = value
|
766 |
+
|
767 |
+
def _prune_heads(self, heads_to_prune):
|
768 |
+
"""
|
769 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
770 |
+
class PreTrainedModel
|
771 |
+
"""
|
772 |
+
for layer, heads in heads_to_prune.items():
|
773 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
774 |
+
|
775 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
776 |
+
@add_code_sample_docstrings(
|
777 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
778 |
+
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
|
779 |
+
config_class=_CONFIG_FOR_DOC,
|
780 |
+
)
|
781 |
+
# Copied from transformers.models.bert.modeling_bert.BertModel.forward
|
782 |
+
def forward(
|
783 |
+
self,
|
784 |
+
input_ids: Optional[torch.Tensor] = None,
|
785 |
+
attention_mask: Optional[torch.Tensor] = None,
|
786 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
787 |
+
position_ids: Optional[torch.Tensor] = None,
|
788 |
+
head_mask: Optional[torch.Tensor] = None,
|
789 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
790 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
791 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
792 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
793 |
+
use_cache: Optional[bool] = None,
|
794 |
+
output_attentions: Optional[bool] = None,
|
795 |
+
output_hidden_states: Optional[bool] = None,
|
796 |
+
return_dict: Optional[bool] = None,
|
797 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
798 |
+
r"""
|
799 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
800 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
801 |
+
the model is configured as a decoder.
|
802 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
803 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
804 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
805 |
+
|
806 |
+
- 1 for tokens that are **not masked**,
|
807 |
+
- 0 for tokens that are **masked**.
|
808 |
+
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)`):
|
809 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
810 |
+
|
811 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
812 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
813 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
814 |
+
use_cache (`bool`, *optional*):
|
815 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
816 |
+
`past_key_values`).
|
817 |
+
"""
|
818 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
819 |
+
output_hidden_states = (
|
820 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
821 |
+
)
|
822 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
823 |
+
|
824 |
+
if self.config.is_decoder:
|
825 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
826 |
+
else:
|
827 |
+
use_cache = False
|
828 |
+
|
829 |
+
if input_ids is not None and inputs_embeds is not None:
|
830 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
831 |
+
elif input_ids is not None:
|
832 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
833 |
+
input_shape = input_ids.size()
|
834 |
+
elif inputs_embeds is not None:
|
835 |
+
input_shape = inputs_embeds.size()[:-1]
|
836 |
+
else:
|
837 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
838 |
+
|
839 |
+
batch_size, seq_length = input_shape
|
840 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
841 |
+
|
842 |
+
# past_key_values_length
|
843 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
844 |
+
|
845 |
+
if attention_mask is None:
|
846 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
847 |
+
|
848 |
+
if token_type_ids is None:
|
849 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
850 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
851 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
852 |
+
token_type_ids = buffered_token_type_ids_expanded
|
853 |
+
else:
|
854 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
855 |
+
|
856 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
857 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
858 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
859 |
+
|
860 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
861 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
862 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
863 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
864 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
865 |
+
if encoder_attention_mask is None:
|
866 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
867 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
868 |
+
else:
|
869 |
+
encoder_extended_attention_mask = None
|
870 |
+
|
871 |
+
# Prepare head mask if needed
|
872 |
+
# 1.0 in head_mask indicate we keep the head
|
873 |
+
# attention_probs has shape bsz x n_heads x N x N
|
874 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
875 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
876 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
877 |
+
|
878 |
+
embedding_output = self.embeddings(
|
879 |
+
input_ids=input_ids,
|
880 |
+
position_ids=position_ids,
|
881 |
+
token_type_ids=token_type_ids,
|
882 |
+
inputs_embeds=inputs_embeds,
|
883 |
+
past_key_values_length=past_key_values_length,
|
884 |
+
)
|
885 |
+
encoder_outputs = self.encoder(
|
886 |
+
embedding_output,
|
887 |
+
attention_mask=extended_attention_mask,
|
888 |
+
head_mask=head_mask,
|
889 |
+
encoder_hidden_states=encoder_hidden_states,
|
890 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
891 |
+
past_key_values=past_key_values,
|
892 |
+
use_cache=use_cache,
|
893 |
+
output_attentions=output_attentions,
|
894 |
+
output_hidden_states=output_hidden_states,
|
895 |
+
return_dict=return_dict,
|
896 |
+
)
|
897 |
+
sequence_output = encoder_outputs[0]
|
898 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
899 |
+
|
900 |
+
if not return_dict:
|
901 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
902 |
+
|
903 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
904 |
+
last_hidden_state=sequence_output,
|
905 |
+
pooler_output=pooled_output,
|
906 |
+
past_key_values=encoder_outputs.past_key_values,
|
907 |
+
hidden_states=encoder_outputs.hidden_states,
|
908 |
+
attentions=encoder_outputs.attentions,
|
909 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
910 |
+
)
|
911 |
+
|
912 |
+
|
913 |
+
@add_start_docstrings(
|
914 |
+
"""CamemBERT Model with a `language modeling` head on top.""",
|
915 |
+
CAMEMBERT_START_DOCSTRING,
|
916 |
+
)
|
917 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT
|
918 |
+
class CamembertForMaskedLM(CamembertPreTrainedModel):
|
919 |
+
_tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
|
920 |
+
|
921 |
+
def __init__(self, config):
|
922 |
+
super().__init__(config)
|
923 |
+
|
924 |
+
if config.is_decoder:
|
925 |
+
logger.warning(
|
926 |
+
"If you want to use `CamembertForMaskedLM` make sure `config.is_decoder=False` for "
|
927 |
+
"bi-directional self-attention."
|
928 |
+
)
|
929 |
+
|
930 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
931 |
+
self.lm_head = CamembertLMHead(config)
|
932 |
+
|
933 |
+
# Initialize weights and apply final processing
|
934 |
+
self.post_init()
|
935 |
+
|
936 |
+
def get_output_embeddings(self):
|
937 |
+
return self.lm_head.decoder
|
938 |
+
|
939 |
+
def set_output_embeddings(self, new_embeddings):
|
940 |
+
self.lm_head.decoder = new_embeddings
|
941 |
+
|
942 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
943 |
+
@add_code_sample_docstrings(
|
944 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
945 |
+
output_type=MaskedLMOutput,
|
946 |
+
config_class=_CONFIG_FOR_DOC,
|
947 |
+
mask="<mask>",
|
948 |
+
expected_output="' Paris'",
|
949 |
+
expected_loss=0.1,
|
950 |
+
)
|
951 |
+
def forward(
|
952 |
+
self,
|
953 |
+
input_ids: Optional[torch.LongTensor] = None,
|
954 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
955 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
956 |
+
position_ids: Optional[torch.LongTensor] = None,
|
957 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
958 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
959 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
960 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
961 |
+
labels: Optional[torch.LongTensor] = None,
|
962 |
+
output_attentions: Optional[bool] = None,
|
963 |
+
output_hidden_states: Optional[bool] = None,
|
964 |
+
return_dict: Optional[bool] = None,
|
965 |
+
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
|
966 |
+
r"""
|
967 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
968 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
969 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
970 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
971 |
+
kwargs (`Dict[str, any]`, optional, defaults to *{}*):
|
972 |
+
Used to hide legacy arguments that have been deprecated.
|
973 |
+
"""
|
974 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
975 |
+
|
976 |
+
outputs = self.roberta(
|
977 |
+
input_ids,
|
978 |
+
attention_mask=attention_mask,
|
979 |
+
token_type_ids=token_type_ids,
|
980 |
+
position_ids=position_ids,
|
981 |
+
head_mask=head_mask,
|
982 |
+
inputs_embeds=inputs_embeds,
|
983 |
+
encoder_hidden_states=encoder_hidden_states,
|
984 |
+
encoder_attention_mask=encoder_attention_mask,
|
985 |
+
output_attentions=output_attentions,
|
986 |
+
output_hidden_states=output_hidden_states,
|
987 |
+
return_dict=return_dict,
|
988 |
+
)
|
989 |
+
sequence_output = outputs[0]
|
990 |
+
prediction_scores = self.lm_head(sequence_output)
|
991 |
+
|
992 |
+
masked_lm_loss = None
|
993 |
+
if labels is not None:
|
994 |
+
# move labels to correct device to enable model parallelism
|
995 |
+
labels = labels.to(prediction_scores.device)
|
996 |
+
loss_fct = CrossEntropyLoss()
|
997 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
998 |
+
|
999 |
+
if not return_dict:
|
1000 |
+
output = (prediction_scores,) + outputs[2:]
|
1001 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
1002 |
+
|
1003 |
+
return MaskedLMOutput(
|
1004 |
+
loss=masked_lm_loss,
|
1005 |
+
logits=prediction_scores,
|
1006 |
+
hidden_states=outputs.hidden_states,
|
1007 |
+
attentions=outputs.attentions,
|
1008 |
+
)
|
1009 |
+
|
1010 |
+
|
1011 |
+
@add_start_docstrings(
|
1012 |
+
"""
|
1013 |
+
CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
1014 |
+
pooled output) e.g. for GLUE tasks.
|
1015 |
+
""",
|
1016 |
+
CAMEMBERT_START_DOCSTRING,
|
1017 |
+
)
|
1018 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
|
1019 |
+
class CamembertForSequenceClassification(CamembertPreTrainedModel):
|
1020 |
+
def __init__(self, config):
|
1021 |
+
super().__init__(config)
|
1022 |
+
self.num_labels = config.num_labels
|
1023 |
+
self.config = config
|
1024 |
+
|
1025 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
1026 |
+
self.classifier = CamembertClassificationHead(config)
|
1027 |
+
|
1028 |
+
# Initialize weights and apply final processing
|
1029 |
+
self.post_init()
|
1030 |
+
|
1031 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1032 |
+
@add_code_sample_docstrings(
|
1033 |
+
checkpoint="cardiffnlp/twitter-roberta-base-emotion",
|
1034 |
+
output_type=SequenceClassifierOutput,
|
1035 |
+
config_class=_CONFIG_FOR_DOC,
|
1036 |
+
expected_output="'optimism'",
|
1037 |
+
expected_loss=0.08,
|
1038 |
+
)
|
1039 |
+
def forward(
|
1040 |
+
self,
|
1041 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1042 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1043 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1044 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1045 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1046 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1047 |
+
labels: Optional[torch.LongTensor] = None,
|
1048 |
+
output_attentions: Optional[bool] = None,
|
1049 |
+
output_hidden_states: Optional[bool] = None,
|
1050 |
+
return_dict: Optional[bool] = None,
|
1051 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
|
1052 |
+
r"""
|
1053 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1054 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1055 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1056 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1057 |
+
"""
|
1058 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1059 |
+
|
1060 |
+
outputs = self.roberta(
|
1061 |
+
input_ids,
|
1062 |
+
attention_mask=attention_mask,
|
1063 |
+
token_type_ids=token_type_ids,
|
1064 |
+
position_ids=position_ids,
|
1065 |
+
head_mask=head_mask,
|
1066 |
+
inputs_embeds=inputs_embeds,
|
1067 |
+
output_attentions=output_attentions,
|
1068 |
+
output_hidden_states=output_hidden_states,
|
1069 |
+
return_dict=return_dict,
|
1070 |
+
)
|
1071 |
+
sequence_output = outputs[0]
|
1072 |
+
logits = self.classifier(sequence_output)
|
1073 |
+
|
1074 |
+
loss = None
|
1075 |
+
if labels is not None:
|
1076 |
+
# move labels to correct device to enable model parallelism
|
1077 |
+
labels = labels.to(logits.device)
|
1078 |
+
if self.config.problem_type is None:
|
1079 |
+
if self.num_labels == 1:
|
1080 |
+
self.config.problem_type = "regression"
|
1081 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1082 |
+
self.config.problem_type = "single_label_classification"
|
1083 |
+
else:
|
1084 |
+
self.config.problem_type = "multi_label_classification"
|
1085 |
+
|
1086 |
+
if self.config.problem_type == "regression":
|
1087 |
+
loss_fct = MSELoss()
|
1088 |
+
if self.num_labels == 1:
|
1089 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
1090 |
+
else:
|
1091 |
+
loss = loss_fct(logits, labels)
|
1092 |
+
elif self.config.problem_type == "single_label_classification":
|
1093 |
+
loss_fct = CrossEntropyLoss()
|
1094 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1095 |
+
elif self.config.problem_type == "multi_label_classification":
|
1096 |
+
loss_fct = BCEWithLogitsLoss()
|
1097 |
+
loss = loss_fct(logits, labels)
|
1098 |
+
|
1099 |
+
if not return_dict:
|
1100 |
+
output = (logits,) + outputs[2:]
|
1101 |
+
return ((loss,) + output) if loss is not None else output
|
1102 |
+
|
1103 |
+
return SequenceClassifierOutput(
|
1104 |
+
loss=loss,
|
1105 |
+
logits=logits,
|
1106 |
+
hidden_states=outputs.hidden_states,
|
1107 |
+
attentions=outputs.attentions,
|
1108 |
+
)
|
1109 |
+
|
1110 |
+
|
1111 |
+
@add_start_docstrings(
|
1112 |
+
"""
|
1113 |
+
CamemBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
1114 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
1115 |
+
""",
|
1116 |
+
CAMEMBERT_START_DOCSTRING,
|
1117 |
+
)
|
1118 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForMultipleChoice with Roberta->Camembert, ROBERTA->CAMEMBERT
|
1119 |
+
class CamembertForMultipleChoice(CamembertPreTrainedModel):
|
1120 |
+
def __init__(self, config):
|
1121 |
+
super().__init__(config)
|
1122 |
+
|
1123 |
+
self.roberta = CamembertModel(config)
|
1124 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
1125 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
1126 |
+
|
1127 |
+
# Initialize weights and apply final processing
|
1128 |
+
self.post_init()
|
1129 |
+
|
1130 |
+
@add_start_docstrings_to_model_forward(
|
1131 |
+
CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
1132 |
+
)
|
1133 |
+
@add_code_sample_docstrings(
|
1134 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1135 |
+
output_type=MultipleChoiceModelOutput,
|
1136 |
+
config_class=_CONFIG_FOR_DOC,
|
1137 |
+
)
|
1138 |
+
def forward(
|
1139 |
+
self,
|
1140 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1141 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1142 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1143 |
+
labels: Optional[torch.LongTensor] = None,
|
1144 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1145 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1146 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1147 |
+
output_attentions: Optional[bool] = None,
|
1148 |
+
output_hidden_states: Optional[bool] = None,
|
1149 |
+
return_dict: Optional[bool] = None,
|
1150 |
+
) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
|
1151 |
+
r"""
|
1152 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1153 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
1154 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
1155 |
+
`input_ids` above)
|
1156 |
+
"""
|
1157 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1158 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
1159 |
+
|
1160 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
1161 |
+
flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
1162 |
+
flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
1163 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
1164 |
+
flat_inputs_embeds = (
|
1165 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
1166 |
+
if inputs_embeds is not None
|
1167 |
+
else None
|
1168 |
+
)
|
1169 |
+
|
1170 |
+
outputs = self.roberta(
|
1171 |
+
flat_input_ids,
|
1172 |
+
position_ids=flat_position_ids,
|
1173 |
+
token_type_ids=flat_token_type_ids,
|
1174 |
+
attention_mask=flat_attention_mask,
|
1175 |
+
head_mask=head_mask,
|
1176 |
+
inputs_embeds=flat_inputs_embeds,
|
1177 |
+
output_attentions=output_attentions,
|
1178 |
+
output_hidden_states=output_hidden_states,
|
1179 |
+
return_dict=return_dict,
|
1180 |
+
)
|
1181 |
+
pooled_output = outputs[1]
|
1182 |
+
|
1183 |
+
pooled_output = self.dropout(pooled_output)
|
1184 |
+
logits = self.classifier(pooled_output)
|
1185 |
+
reshaped_logits = logits.view(-1, num_choices)
|
1186 |
+
|
1187 |
+
loss = None
|
1188 |
+
if labels is not None:
|
1189 |
+
# move labels to correct device to enable model parallelism
|
1190 |
+
labels = labels.to(reshaped_logits.device)
|
1191 |
+
loss_fct = CrossEntropyLoss()
|
1192 |
+
loss = loss_fct(reshaped_logits, labels)
|
1193 |
+
|
1194 |
+
if not return_dict:
|
1195 |
+
output = (reshaped_logits,) + outputs[2:]
|
1196 |
+
return ((loss,) + output) if loss is not None else output
|
1197 |
+
|
1198 |
+
return MultipleChoiceModelOutput(
|
1199 |
+
loss=loss,
|
1200 |
+
logits=reshaped_logits,
|
1201 |
+
hidden_states=outputs.hidden_states,
|
1202 |
+
attentions=outputs.attentions,
|
1203 |
+
)
|
1204 |
+
|
1205 |
+
|
1206 |
+
@add_start_docstrings(
|
1207 |
+
"""
|
1208 |
+
CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
|
1209 |
+
for Named-Entity-Recognition (NER) tasks.
|
1210 |
+
""",
|
1211 |
+
CAMEMBERT_START_DOCSTRING,
|
1212 |
+
)
|
1213 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification with Roberta->Camembert, ROBERTA->CAMEMBERT
|
1214 |
+
class CamembertForTokenClassification(CamembertPreTrainedModel):
|
1215 |
+
def __init__(self, config):
|
1216 |
+
super().__init__(config)
|
1217 |
+
self.num_labels = config.num_labels
|
1218 |
+
|
1219 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
1220 |
+
classifier_dropout = (
|
1221 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
1222 |
+
)
|
1223 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1224 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1225 |
+
|
1226 |
+
# Initialize weights and apply final processing
|
1227 |
+
self.post_init()
|
1228 |
+
|
1229 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1230 |
+
@add_code_sample_docstrings(
|
1231 |
+
checkpoint="Jean-Baptiste/roberta-large-ner-english",
|
1232 |
+
output_type=TokenClassifierOutput,
|
1233 |
+
config_class=_CONFIG_FOR_DOC,
|
1234 |
+
expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']",
|
1235 |
+
expected_loss=0.01,
|
1236 |
+
)
|
1237 |
+
def forward(
|
1238 |
+
self,
|
1239 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1240 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1241 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1242 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1243 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1244 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1245 |
+
labels: Optional[torch.LongTensor] = None,
|
1246 |
+
output_attentions: Optional[bool] = None,
|
1247 |
+
output_hidden_states: Optional[bool] = None,
|
1248 |
+
return_dict: Optional[bool] = None,
|
1249 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
1250 |
+
r"""
|
1251 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1252 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
1253 |
+
"""
|
1254 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1255 |
+
|
1256 |
+
outputs = self.roberta(
|
1257 |
+
input_ids,
|
1258 |
+
attention_mask=attention_mask,
|
1259 |
+
token_type_ids=token_type_ids,
|
1260 |
+
position_ids=position_ids,
|
1261 |
+
head_mask=head_mask,
|
1262 |
+
inputs_embeds=inputs_embeds,
|
1263 |
+
output_attentions=output_attentions,
|
1264 |
+
output_hidden_states=output_hidden_states,
|
1265 |
+
return_dict=return_dict,
|
1266 |
+
)
|
1267 |
+
|
1268 |
+
sequence_output = outputs[0]
|
1269 |
+
|
1270 |
+
sequence_output = self.dropout(sequence_output)
|
1271 |
+
logits = self.classifier(sequence_output)
|
1272 |
+
|
1273 |
+
loss = None
|
1274 |
+
if labels is not None:
|
1275 |
+
# move labels to correct device to enable model parallelism
|
1276 |
+
labels = labels.to(logits.device)
|
1277 |
+
loss_fct = CrossEntropyLoss()
|
1278 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1279 |
+
|
1280 |
+
if not return_dict:
|
1281 |
+
output = (logits,) + outputs[2:]
|
1282 |
+
return ((loss,) + output) if loss is not None else output
|
1283 |
+
|
1284 |
+
return TokenClassifierOutput(
|
1285 |
+
loss=loss,
|
1286 |
+
logits=logits,
|
1287 |
+
hidden_states=outputs.hidden_states,
|
1288 |
+
attentions=outputs.attentions,
|
1289 |
+
)
|
1290 |
+
|
1291 |
+
|
1292 |
+
@add_start_docstrings(
|
1293 |
+
"""
|
1294 |
+
CamemBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
1295 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`
|
1296 |
+
""",
|
1297 |
+
CAMEMBERT_START_DOCSTRING,
|
1298 |
+
)
|
1299 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering with Roberta->Camembert, ROBERTA->CAMEMBERT
|
1300 |
+
class CamembertForQuestionAnswering(CamembertPreTrainedModel):
|
1301 |
+
def __init__(self, config):
|
1302 |
+
super().__init__(config)
|
1303 |
+
self.num_labels = config.num_labels
|
1304 |
+
|
1305 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
1306 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
1307 |
+
|
1308 |
+
# Initialize weights and apply final processing
|
1309 |
+
self.post_init()
|
1310 |
+
|
1311 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1312 |
+
@add_code_sample_docstrings(
|
1313 |
+
checkpoint="deepset/roberta-base-squad2",
|
1314 |
+
output_type=QuestionAnsweringModelOutput,
|
1315 |
+
config_class=_CONFIG_FOR_DOC,
|
1316 |
+
expected_output="' puppet'",
|
1317 |
+
expected_loss=0.86,
|
1318 |
+
)
|
1319 |
+
def forward(
|
1320 |
+
self,
|
1321 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1322 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1323 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1324 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1325 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1326 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1327 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1328 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1329 |
+
output_attentions: Optional[bool] = None,
|
1330 |
+
output_hidden_states: Optional[bool] = None,
|
1331 |
+
return_dict: Optional[bool] = None,
|
1332 |
+
) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
|
1333 |
+
r"""
|
1334 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1335 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1336 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1337 |
+
are not taken into account for computing the loss.
|
1338 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1339 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1340 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1341 |
+
are not taken into account for computing the loss.
|
1342 |
+
"""
|
1343 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1344 |
+
|
1345 |
+
outputs = self.roberta(
|
1346 |
+
input_ids,
|
1347 |
+
attention_mask=attention_mask,
|
1348 |
+
token_type_ids=token_type_ids,
|
1349 |
+
position_ids=position_ids,
|
1350 |
+
head_mask=head_mask,
|
1351 |
+
inputs_embeds=inputs_embeds,
|
1352 |
+
output_attentions=output_attentions,
|
1353 |
+
output_hidden_states=output_hidden_states,
|
1354 |
+
return_dict=return_dict,
|
1355 |
+
)
|
1356 |
+
|
1357 |
+
sequence_output = outputs[0]
|
1358 |
+
|
1359 |
+
logits = self.qa_outputs(sequence_output)
|
1360 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1361 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1362 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1363 |
+
|
1364 |
+
total_loss = None
|
1365 |
+
if start_positions is not None and end_positions is not None:
|
1366 |
+
# If we are on multi-GPU, split add a dimension
|
1367 |
+
if len(start_positions.size()) > 1:
|
1368 |
+
start_positions = start_positions.squeeze(-1)
|
1369 |
+
if len(end_positions.size()) > 1:
|
1370 |
+
end_positions = end_positions.squeeze(-1)
|
1371 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1372 |
+
ignored_index = start_logits.size(1)
|
1373 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1374 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1375 |
+
|
1376 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1377 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1378 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1379 |
+
total_loss = (start_loss + end_loss) / 2
|
1380 |
+
|
1381 |
+
if not return_dict:
|
1382 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1383 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1384 |
+
|
1385 |
+
return QuestionAnsweringModelOutput(
|
1386 |
+
loss=total_loss,
|
1387 |
+
start_logits=start_logits,
|
1388 |
+
end_logits=end_logits,
|
1389 |
+
hidden_states=outputs.hidden_states,
|
1390 |
+
attentions=outputs.attentions,
|
1391 |
+
)
|
1392 |
+
|
1393 |
+
|
1394 |
+
@add_start_docstrings(
|
1395 |
+
"""CamemBERT Model with a `language modeling` head on top for CLM fine-tuning.""", CAMEMBERT_START_DOCSTRING
|
1396 |
+
)
|
1397 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM with Roberta->Camembert, ROBERTA->CAMEMBERT, FacebookAI/roberta-base->almanach/camembert-base
|
1398 |
+
class CamembertForCausalLM(CamembertPreTrainedModel):
|
1399 |
+
_tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
|
1400 |
+
|
1401 |
+
def __init__(self, config):
|
1402 |
+
super().__init__(config)
|
1403 |
+
|
1404 |
+
if not config.is_decoder:
|
1405 |
+
logger.warning("If you want to use `CamembertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
1406 |
+
|
1407 |
+
self.roberta = CamembertModel(config, add_pooling_layer=False)
|
1408 |
+
self.lm_head = CamembertLMHead(config)
|
1409 |
+
|
1410 |
+
# Initialize weights and apply final processing
|
1411 |
+
self.post_init()
|
1412 |
+
|
1413 |
+
def get_output_embeddings(self):
|
1414 |
+
return self.lm_head.decoder
|
1415 |
+
|
1416 |
+
def set_output_embeddings(self, new_embeddings):
|
1417 |
+
self.lm_head.decoder = new_embeddings
|
1418 |
+
|
1419 |
+
@add_start_docstrings_to_model_forward(CAMEMBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1420 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
1421 |
+
def forward(
|
1422 |
+
self,
|
1423 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1424 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1425 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1426 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1427 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1428 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1429 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
1430 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
1431 |
+
labels: Optional[torch.LongTensor] = None,
|
1432 |
+
past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,
|
1433 |
+
use_cache: Optional[bool] = None,
|
1434 |
+
output_attentions: Optional[bool] = None,
|
1435 |
+
output_hidden_states: Optional[bool] = None,
|
1436 |
+
return_dict: Optional[bool] = None,
|
1437 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
1438 |
+
r"""
|
1439 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1440 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1441 |
+
the model is configured as a decoder.
|
1442 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1443 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1444 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
1445 |
+
|
1446 |
+
- 1 for tokens that are **not masked**,
|
1447 |
+
- 0 for tokens that are **masked**.
|
1448 |
+
|
1449 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1450 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
1451 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
1452 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1453 |
+
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)`):
|
1454 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1455 |
+
|
1456 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
1457 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
1458 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
1459 |
+
use_cache (`bool`, *optional*):
|
1460 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1461 |
+
`past_key_values`).
|
1462 |
+
|
1463 |
+
Returns:
|
1464 |
+
|
1465 |
+
Example:
|
1466 |
+
|
1467 |
+
```python
|
1468 |
+
>>> from transformers import AutoTokenizer, CamembertForCausalLM, AutoConfig
|
1469 |
+
>>> import torch
|
1470 |
+
|
1471 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("almanach/camembert-base")
|
1472 |
+
>>> config = AutoConfig.from_pretrained("almanach/camembert-base")
|
1473 |
+
>>> config.is_decoder = True
|
1474 |
+
>>> model = CamembertForCausalLM.from_pretrained("almanach/camembert-base", config=config)
|
1475 |
+
|
1476 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
1477 |
+
>>> outputs = model(**inputs)
|
1478 |
+
|
1479 |
+
>>> prediction_logits = outputs.logits
|
1480 |
+
```"""
|
1481 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1482 |
+
if labels is not None:
|
1483 |
+
use_cache = False
|
1484 |
+
|
1485 |
+
outputs = self.roberta(
|
1486 |
+
input_ids,
|
1487 |
+
attention_mask=attention_mask,
|
1488 |
+
token_type_ids=token_type_ids,
|
1489 |
+
position_ids=position_ids,
|
1490 |
+
head_mask=head_mask,
|
1491 |
+
inputs_embeds=inputs_embeds,
|
1492 |
+
encoder_hidden_states=encoder_hidden_states,
|
1493 |
+
encoder_attention_mask=encoder_attention_mask,
|
1494 |
+
past_key_values=past_key_values,
|
1495 |
+
use_cache=use_cache,
|
1496 |
+
output_attentions=output_attentions,
|
1497 |
+
output_hidden_states=output_hidden_states,
|
1498 |
+
return_dict=return_dict,
|
1499 |
+
)
|
1500 |
+
|
1501 |
+
sequence_output = outputs[0]
|
1502 |
+
prediction_scores = self.lm_head(sequence_output)
|
1503 |
+
|
1504 |
+
lm_loss = None
|
1505 |
+
if labels is not None:
|
1506 |
+
# move labels to correct device to enable model parallelism
|
1507 |
+
labels = labels.to(prediction_scores.device)
|
1508 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
1509 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
1510 |
+
labels = labels[:, 1:].contiguous()
|
1511 |
+
loss_fct = CrossEntropyLoss()
|
1512 |
+
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1513 |
+
|
1514 |
+
if not return_dict:
|
1515 |
+
output = (prediction_scores,) + outputs[2:]
|
1516 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
1517 |
+
|
1518 |
+
return CausalLMOutputWithCrossAttentions(
|
1519 |
+
loss=lm_loss,
|
1520 |
+
logits=prediction_scores,
|
1521 |
+
past_key_values=outputs.past_key_values,
|
1522 |
+
hidden_states=outputs.hidden_states,
|
1523 |
+
attentions=outputs.attentions,
|
1524 |
+
cross_attentions=outputs.cross_attentions,
|
1525 |
+
)
|
1526 |
+
|
1527 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
1528 |
+
input_shape = input_ids.shape
|
1529 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
1530 |
+
if attention_mask is None:
|
1531 |
+
attention_mask = input_ids.new_ones(input_shape)
|
1532 |
+
|
1533 |
+
# cut decoder_input_ids if past_key_values is used
|
1534 |
+
if past_key_values is not None:
|
1535 |
+
past_length = past_key_values[0][0].shape[2]
|
1536 |
+
|
1537 |
+
# Some generation methods already pass only the last input ID
|
1538 |
+
if input_ids.shape[1] > past_length:
|
1539 |
+
remove_prefix_length = past_length
|
1540 |
+
else:
|
1541 |
+
# Default to old behavior: keep only final ID
|
1542 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
1543 |
+
|
1544 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
1545 |
+
|
1546 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
|
1547 |
+
|
1548 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
1549 |
+
reordered_past = ()
|
1550 |
+
for layer_past in past_key_values:
|
1551 |
+
reordered_past += (
|
1552 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1553 |
+
)
|
1554 |
+
return reordered_past
|
1555 |
+
|
1556 |
+
|
1557 |
+
# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
|
1558 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
1559 |
+
"""
|
1560 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
1561 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
1562 |
+
|
1563 |
+
Args:
|
1564 |
+
x: torch.Tensor x:
|
1565 |
+
|
1566 |
+
Returns: torch.Tensor
|
1567 |
+
"""
|
1568 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
1569 |
+
mask = input_ids.ne(padding_idx).int()
|
1570 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
1571 |
+
return incremental_indices.long() + padding_idx
|
llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/modeling_tf_camembert.py
ADDED
@@ -0,0 +1,1793 @@
|
|
|
|
|
|
|
|
|
|
|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f-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,
|
50 |
+
keras_serializable,
|
51 |
+
unpack_inputs,
|
52 |
+
)
|
53 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
54 |
+
from ...utils import (
|
55 |
+
add_code_sample_docstrings,
|
56 |
+
add_start_docstrings,
|
57 |
+
add_start_docstrings_to_model_forward,
|
58 |
+
logging,
|
59 |
+
)
|
60 |
+
from .configuration_camembert import CamembertConfig
|
61 |
+
|
62 |
+
|
63 |
+
logger = logging.get_logger(__name__)
|
64 |
+
|
65 |
+
_CHECKPOINT_FOR_DOC = "almanach/camembert-base"
|
66 |
+
_CONFIG_FOR_DOC = "CamembertConfig"
|
67 |
+
|
68 |
+
|
69 |
+
from ..deprecated._archive_maps import TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
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 [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(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 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
185 |
+
self.dropout = 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(keras.layers.Layer):
|
278 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
279 |
+
super().__init__(**kwargs)
|
280 |
+
|
281 |
+
self.dense = 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(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 = keras.layers.Dense(
|
323 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
|
324 |
+
)
|
325 |
+
self.key = keras.layers.Dense(
|
326 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
|
327 |
+
)
|
328 |
+
self.value = keras.layers.Dense(
|
329 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
|
330 |
+
)
|
331 |
+
self.dropout = 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(keras.layers.Layer):
|
441 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
442 |
+
super().__init__(**kwargs)
|
443 |
+
|
444 |
+
self.dense = keras.layers.Dense(
|
445 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
446 |
+
)
|
447 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
448 |
+
self.dropout = 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(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(keras.layers.Layer):
|
524 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
525 |
+
super().__init__(**kwargs)
|
526 |
+
|
527 |
+
self.dense = 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(keras.layers.Layer):
|
554 |
+
def __init__(self, config: CamembertConfig, **kwargs):
|
555 |
+
super().__init__(**kwargs)
|
556 |
+
|
557 |
+
self.dense = keras.layers.Dense(
|
558 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
559 |
+
)
|
560 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
561 |
+
self.dropout = 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(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(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(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) -> 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(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 = keras.layers.Dense(
|
1080 |
+
config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
1081 |
+
)
|
1082 |
+
self.layer_norm = 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(keras.layers.Layer):
|
1226 |
+
"""Head for sentence-level classification tasks."""
|
1227 |
+
|
1228 |
+
def __init__(self, config, **kwargs):
|
1229 |
+
super().__init__(**kwargs)
|
1230 |
+
self.dense = 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 = keras.layers.Dropout(classifier_dropout)
|
1240 |
+
self.out_proj = 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 = keras.layers.Dropout(classifier_dropout)
|
1375 |
+
self.classifier = 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 = keras.layers.Dropout(config.hidden_dropout_prob)
|
1467 |
+
self.classifier = 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 = 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)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert.py
ADDED
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
33 |
+
SPIECE_UNDERLINE = "▁"
|
34 |
+
|
35 |
+
|
36 |
+
class CamembertTokenizer(PreTrainedTokenizer):
|
37 |
+
"""
|
38 |
+
Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Construct a CamemBERT tokenizer. Based on
|
39 |
+
[SentencePiece](https://github.com/google/sentencepiece).
|
40 |
+
|
41 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
42 |
+
this superclass for more information regarding those methods.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
vocab_file (`str`):
|
46 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
47 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
48 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
49 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
50 |
+
|
51 |
+
<Tip>
|
52 |
+
|
53 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
54 |
+
sequence. The token used is the `cls_token`.
|
55 |
+
|
56 |
+
</Tip>
|
57 |
+
|
58 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
59 |
+
The end of sequence token.
|
60 |
+
|
61 |
+
<Tip>
|
62 |
+
|
63 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
64 |
+
The token used is the `sep_token`.
|
65 |
+
|
66 |
+
</Tip>
|
67 |
+
|
68 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
69 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
70 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
71 |
+
token of a sequence built with special tokens.
|
72 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
73 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
74 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
75 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
76 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
77 |
+
token instead.
|
78 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
79 |
+
The token used for padding, for example when batching sequences of different lengths.
|
80 |
+
mask_token (`str`, *optional*, defaults to `"<mask>"`):
|
81 |
+
The token used for masking values. This is the token used when training this model with masked language
|
82 |
+
modeling. This is the token which the model will try to predict.
|
83 |
+
additional_special_tokens (`List[str]`, *optional*, defaults to `['<s>NOTUSED', '</s>NOTUSED', '<unk>NOTUSED']`):
|
84 |
+
Additional special tokens used by the tokenizer.
|
85 |
+
sp_model_kwargs (`dict`, *optional*):
|
86 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
87 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
88 |
+
to set:
|
89 |
+
|
90 |
+
- `enable_sampling`: Enable subword regularization.
|
91 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
92 |
+
|
93 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
94 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
95 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
96 |
+
using forward-filtering-and-backward-sampling algorithm.
|
97 |
+
|
98 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
99 |
+
BPE-dropout.
|
100 |
+
|
101 |
+
Attributes:
|
102 |
+
sp_model (`SentencePieceProcessor`):
|
103 |
+
The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
|
104 |
+
"""
|
105 |
+
|
106 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
107 |
+
model_input_names = ["input_ids", "attention_mask"]
|
108 |
+
|
109 |
+
def __init__(
|
110 |
+
self,
|
111 |
+
vocab_file,
|
112 |
+
bos_token="<s>",
|
113 |
+
eos_token="</s>",
|
114 |
+
sep_token="</s>",
|
115 |
+
cls_token="<s>",
|
116 |
+
unk_token="<unk>",
|
117 |
+
pad_token="<pad>",
|
118 |
+
mask_token="<mask>",
|
119 |
+
additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED", "<unk>NOTUSED"],
|
120 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
121 |
+
**kwargs,
|
122 |
+
) -> None:
|
123 |
+
# Mask token behave like a normal word, i.e. include the space before it
|
124 |
+
mask_token = (
|
125 |
+
AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False, special=True)
|
126 |
+
if isinstance(mask_token, str)
|
127 |
+
else mask_token
|
128 |
+
)
|
129 |
+
|
130 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
131 |
+
|
132 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
133 |
+
self.sp_model.Load(str(vocab_file))
|
134 |
+
self.vocab_file = vocab_file
|
135 |
+
|
136 |
+
# HACK: These tokens were added by the author for an obscure reason as they were already part of the
|
137 |
+
# sentencepiece vocabulary (this is the case for <s> and </s> and <unk>).
|
138 |
+
# In this case it is recommended to properly set the tokens by hand.
|
139 |
+
self._added_tokens_decoder = {
|
140 |
+
0: AddedToken("<s>NOTUSED", special=True),
|
141 |
+
1: AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token,
|
142 |
+
2: AddedToken("</s>NOTUSED", special=True),
|
143 |
+
3: AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token,
|
144 |
+
4: AddedToken("<unk>NOTUSED", special=True),
|
145 |
+
}
|
146 |
+
|
147 |
+
self.fairseq_offset = 4 # 3 tokens are newly added, but the offset starts from 4
|
148 |
+
|
149 |
+
# legacy: camemebert is a particular case were we have to make sure `"<unk>NOTUSED"` is here
|
150 |
+
if "added_tokens_decoder" in kwargs:
|
151 |
+
# this is the only class that requires this unfortunately.....
|
152 |
+
# the reason is that the fast version has a whole.
|
153 |
+
kwargs["added_tokens_decoder"].update(self._added_tokens_decoder)
|
154 |
+
|
155 |
+
super().__init__(
|
156 |
+
bos_token=bos_token,
|
157 |
+
eos_token=eos_token,
|
158 |
+
unk_token=unk_token,
|
159 |
+
sep_token=sep_token,
|
160 |
+
cls_token=cls_token,
|
161 |
+
pad_token=pad_token,
|
162 |
+
mask_token=mask_token,
|
163 |
+
additional_special_tokens=additional_special_tokens,
|
164 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
165 |
+
**kwargs,
|
166 |
+
)
|
167 |
+
|
168 |
+
@property
|
169 |
+
def vocab_size(self):
|
170 |
+
# The length of the vocabulary without added tokens is len(self.sp_model) but the added tokens are added at the beginning.
|
171 |
+
return len(self.sp_model)
|
172 |
+
|
173 |
+
def get_vocab(self):
|
174 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.fairseq_offset)}
|
175 |
+
vocab.update(self.added_tokens_encoder)
|
176 |
+
return vocab
|
177 |
+
|
178 |
+
def _tokenize(self, text: str) -> List[str]:
|
179 |
+
return self.sp_model.encode(text, out_type=str)
|
180 |
+
|
181 |
+
def _convert_token_to_id(self, token):
|
182 |
+
"""Converts a token (str) in an id using the vocab."""
|
183 |
+
# specifi to camembert, both 3 and 4 point to the unk token.
|
184 |
+
if self.sp_model.PieceToId(token) == 0:
|
185 |
+
# Convert sentence piece unk token to fairseq unk token index
|
186 |
+
return self.unk_token_id
|
187 |
+
return self.fairseq_offset + self.sp_model.PieceToId(token)
|
188 |
+
|
189 |
+
def _convert_id_to_token(self, index):
|
190 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
191 |
+
return self.sp_model.IdToPiece(index - self.fairseq_offset)
|
192 |
+
|
193 |
+
def convert_tokens_to_string(self, tokens):
|
194 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
195 |
+
# TODO decode outputs do not match between fast and slow
|
196 |
+
current_sub_tokens = []
|
197 |
+
out_string = ""
|
198 |
+
prev_is_special = False
|
199 |
+
for token in tokens:
|
200 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
201 |
+
if token in self.all_special_tokens:
|
202 |
+
if not prev_is_special:
|
203 |
+
out_string += " "
|
204 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
205 |
+
prev_is_special = True
|
206 |
+
current_sub_tokens = []
|
207 |
+
else:
|
208 |
+
current_sub_tokens.append(token)
|
209 |
+
prev_is_special = False
|
210 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
211 |
+
return out_string.strip()
|
212 |
+
|
213 |
+
def __getstate__(self):
|
214 |
+
state = self.__dict__.copy()
|
215 |
+
state["sp_model"] = None
|
216 |
+
return state
|
217 |
+
|
218 |
+
def __setstate__(self, d):
|
219 |
+
self.__dict__ = d
|
220 |
+
|
221 |
+
# for backward compatibility
|
222 |
+
if not hasattr(self, "sp_model_kwargs"):
|
223 |
+
self.sp_model_kwargs = {}
|
224 |
+
|
225 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
226 |
+
self.sp_model.Load(self.vocab_file)
|
227 |
+
|
228 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
229 |
+
if not os.path.isdir(save_directory):
|
230 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
231 |
+
return
|
232 |
+
out_vocab_file = os.path.join(
|
233 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
234 |
+
)
|
235 |
+
|
236 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
237 |
+
copyfile(self.vocab_file, out_vocab_file)
|
238 |
+
elif not os.path.isfile(self.vocab_file):
|
239 |
+
with open(out_vocab_file, "wb") as fi:
|
240 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
241 |
+
fi.write(content_spiece_model)
|
242 |
+
|
243 |
+
return (out_vocab_file,)
|
244 |
+
|
245 |
+
def build_inputs_with_special_tokens(
|
246 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
247 |
+
) -> List[int]:
|
248 |
+
"""
|
249 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
250 |
+
adding special tokens. An CamemBERT sequence has the following format:
|
251 |
+
|
252 |
+
- single sequence: `<s> X </s>`
|
253 |
+
- pair of sequences: `<s> A </s></s> B </s>`
|
254 |
+
|
255 |
+
Args:
|
256 |
+
token_ids_0 (`List[int]`):
|
257 |
+
List of IDs to which the special tokens will be added.
|
258 |
+
token_ids_1 (`List[int]`, *optional*):
|
259 |
+
Optional second list of IDs for sequence pairs.
|
260 |
+
|
261 |
+
Returns:
|
262 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
263 |
+
"""
|
264 |
+
|
265 |
+
if token_ids_1 is None:
|
266 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
267 |
+
cls = [self.cls_token_id]
|
268 |
+
sep = [self.sep_token_id]
|
269 |
+
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
|
270 |
+
|
271 |
+
def get_special_tokens_mask(
|
272 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
273 |
+
) -> List[int]:
|
274 |
+
"""
|
275 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
276 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
277 |
+
|
278 |
+
Args:
|
279 |
+
token_ids_0 (`List[int]`):
|
280 |
+
List of IDs.
|
281 |
+
token_ids_1 (`List[int]`, *optional*):
|
282 |
+
Optional second list of IDs for sequence pairs.
|
283 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
284 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
285 |
+
|
286 |
+
Returns:
|
287 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
288 |
+
"""
|
289 |
+
if already_has_special_tokens:
|
290 |
+
return super().get_special_tokens_mask(
|
291 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
292 |
+
)
|
293 |
+
|
294 |
+
if token_ids_1 is None:
|
295 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
296 |
+
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
|
297 |
+
|
298 |
+
def create_token_type_ids_from_sequences(
|
299 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
300 |
+
) -> List[int]:
|
301 |
+
"""
|
302 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. CamemBERT, like
|
303 |
+
RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
|
304 |
+
|
305 |
+
Args:
|
306 |
+
token_ids_0 (`List[int]`):
|
307 |
+
List of IDs.
|
308 |
+
token_ids_1 (`List[int]`, *optional*):
|
309 |
+
Optional second list of IDs for sequence pairs.
|
310 |
+
|
311 |
+
Returns:
|
312 |
+
`List[int]`: List of zeros.
|
313 |
+
"""
|
314 |
+
sep = [self.sep_token_id]
|
315 |
+
cls = [self.cls_token_id]
|
316 |
+
|
317 |
+
if token_ids_1 is None:
|
318 |
+
return len(cls + token_ids_0 + sep) * [0]
|
319 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
llmeval-env/lib/python3.10/site-packages/transformers/models/camembert/tokenization_camembert_fast.py
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
""" Fast tokenization classes for Camembert model."""
|
16 |
+
|
17 |
+
|
18 |
+
import os
|
19 |
+
from shutil import copyfile
|
20 |
+
from typing import List, Optional, Tuple
|
21 |
+
|
22 |
+
from ...tokenization_utils import AddedToken
|
23 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
24 |
+
from ...utils import is_sentencepiece_available, logging
|
25 |
+
|
26 |
+
|
27 |
+
if is_sentencepiece_available():
|
28 |
+
from .tokenization_camembert import CamembertTokenizer
|
29 |
+
else:
|
30 |
+
CamembertTokenizer = None
|
31 |
+
|
32 |
+
|
33 |
+
logger = logging.get_logger(__name__)
|
34 |
+
|
35 |
+
VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
|
36 |
+
|
37 |
+
|
38 |
+
SPIECE_UNDERLINE = "▁"
|
39 |
+
|
40 |
+
|
41 |
+
class CamembertTokenizerFast(PreTrainedTokenizerFast):
|
42 |
+
"""
|
43 |
+
Construct a "fast" CamemBERT tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
|
44 |
+
[`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
|
45 |
+
[BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
|
46 |
+
|
47 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
48 |
+
refer to this superclass for more information regarding those methods.
|
49 |
+
|
50 |
+
Args:
|
51 |
+
vocab_file (`str`):
|
52 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
53 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
54 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
55 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
56 |
+
|
57 |
+
<Tip>
|
58 |
+
|
59 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
60 |
+
sequence. The token used is the `cls_token`.
|
61 |
+
|
62 |
+
</Tip>
|
63 |
+
|
64 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
65 |
+
The end of sequence token.
|
66 |
+
|
67 |
+
<Tip>
|
68 |
+
|
69 |
+
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
|
70 |
+
The token used is the `sep_token`.
|
71 |
+
|
72 |
+
</Tip>
|
73 |
+
|
74 |
+
sep_token (`str`, *optional*, defaults to `"</s>"`):
|
75 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
76 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
77 |
+
token of a sequence built with special tokens.
|
78 |
+
cls_token (`str`, *optional*, defaults to `"<s>"`):
|
79 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
80 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
81 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
82 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
83 |
+
token instead.
|
84 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
85 |
+
The token used for padding, for example when batching sequences of different lengths.
|
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 |
+
additional_special_tokens (`List[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
|
90 |
+
Additional special tokens used by the tokenizer.
|
91 |
+
"""
|
92 |
+
|
93 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
94 |
+
model_input_names = ["input_ids", "attention_mask"]
|
95 |
+
slow_tokenizer_class = CamembertTokenizer
|
96 |
+
|
97 |
+
def __init__(
|
98 |
+
self,
|
99 |
+
vocab_file=None,
|
100 |
+
tokenizer_file=None,
|
101 |
+
bos_token="<s>",
|
102 |
+
eos_token="</s>",
|
103 |
+
sep_token="</s>",
|
104 |
+
cls_token="<s>",
|
105 |
+
unk_token="<unk>",
|
106 |
+
pad_token="<pad>",
|
107 |
+
mask_token="<mask>",
|
108 |
+
additional_special_tokens=["<s>NOTUSED", "</s>NOTUSED", "<unk>NOTUSED"],
|
109 |
+
**kwargs,
|
110 |
+
):
|
111 |
+
# Mask token behave like a normal word, i.e. include the space before it. Will have normalized = False
|
112 |
+
mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
|
113 |
+
super().__init__(
|
114 |
+
vocab_file,
|
115 |
+
tokenizer_file=tokenizer_file,
|
116 |
+
bos_token=bos_token,
|
117 |
+
eos_token=eos_token,
|
118 |
+
sep_token=sep_token,
|
119 |
+
cls_token=cls_token,
|
120 |
+
unk_token=unk_token,
|
121 |
+
pad_token=pad_token,
|
122 |
+
mask_token=mask_token,
|
123 |
+
additional_special_tokens=additional_special_tokens,
|
124 |
+
**kwargs,
|
125 |
+
)
|
126 |
+
|
127 |
+
self.vocab_file = vocab_file
|
128 |
+
|
129 |
+
@property
|
130 |
+
def can_save_slow_tokenizer(self) -> bool:
|
131 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
132 |
+
|
133 |
+
def build_inputs_with_special_tokens(
|
134 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
135 |
+
) -> List[int]:
|
136 |
+
"""
|
137 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
138 |
+
adding special tokens. An CamemBERT sequence has the following format:
|
139 |
+
|
140 |
+
- single sequence: `<s> X </s>`
|
141 |
+
- pair of sequences: `<s> A </s></s> B </s>`
|
142 |
+
|
143 |
+
Args:
|
144 |
+
token_ids_0 (`List[int]`):
|
145 |
+
List of IDs to which the special tokens will be added.
|
146 |
+
token_ids_1 (`List[int]`, *optional*):
|
147 |
+
Optional second list of IDs for sequence pairs.
|
148 |
+
|
149 |
+
Returns:
|
150 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
151 |
+
"""
|
152 |
+
|
153 |
+
if token_ids_1 is None:
|
154 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
155 |
+
cls = [self.cls_token_id]
|
156 |
+
sep = [self.sep_token_id]
|
157 |
+
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
|
158 |
+
|
159 |
+
def create_token_type_ids_from_sequences(
|
160 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
161 |
+
) -> List[int]:
|
162 |
+
"""
|
163 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. CamemBERT, like
|
164 |
+
RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
|
165 |
+
|
166 |
+
Args:
|
167 |
+
token_ids_0 (`List[int]`):
|
168 |
+
List of IDs.
|
169 |
+
token_ids_1 (`List[int]`, *optional*):
|
170 |
+
Optional second list of IDs for sequence pairs.
|
171 |
+
|
172 |
+
Returns:
|
173 |
+
`List[int]`: List of zeros.
|
174 |
+
"""
|
175 |
+
sep = [self.sep_token_id]
|
176 |
+
cls = [self.cls_token_id]
|
177 |
+
|
178 |
+
if token_ids_1 is None:
|
179 |
+
return len(cls + token_ids_0 + sep) * [0]
|
180 |
+
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
|
181 |
+
|
182 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
183 |
+
if not self.can_save_slow_tokenizer:
|
184 |
+
raise ValueError(
|
185 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
186 |
+
"tokenizer."
|
187 |
+
)
|
188 |
+
|
189 |
+
if not os.path.isdir(save_directory):
|
190 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
191 |
+
return
|
192 |
+
out_vocab_file = os.path.join(
|
193 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
194 |
+
)
|
195 |
+
|
196 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
197 |
+
copyfile(self.vocab_file, out_vocab_file)
|
198 |
+
|
199 |
+
return (out_vocab_file,)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__init__.py
ADDED
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_tokenizers_available,
|
22 |
+
is_torch_available,
|
23 |
+
is_vision_available,
|
24 |
+
)
|
25 |
+
|
26 |
+
|
27 |
+
_import_structure = {
|
28 |
+
"configuration_clip": [
|
29 |
+
"CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
|
30 |
+
"CLIPConfig",
|
31 |
+
"CLIPOnnxConfig",
|
32 |
+
"CLIPTextConfig",
|
33 |
+
"CLIPVisionConfig",
|
34 |
+
],
|
35 |
+
"processing_clip": ["CLIPProcessor"],
|
36 |
+
"tokenization_clip": ["CLIPTokenizer"],
|
37 |
+
}
|
38 |
+
|
39 |
+
try:
|
40 |
+
if not is_tokenizers_available():
|
41 |
+
raise OptionalDependencyNotAvailable()
|
42 |
+
except OptionalDependencyNotAvailable:
|
43 |
+
pass
|
44 |
+
else:
|
45 |
+
_import_structure["tokenization_clip_fast"] = ["CLIPTokenizerFast"]
|
46 |
+
|
47 |
+
try:
|
48 |
+
if not is_vision_available():
|
49 |
+
raise OptionalDependencyNotAvailable()
|
50 |
+
except OptionalDependencyNotAvailable:
|
51 |
+
pass
|
52 |
+
else:
|
53 |
+
_import_structure["feature_extraction_clip"] = ["CLIPFeatureExtractor"]
|
54 |
+
_import_structure["image_processing_clip"] = ["CLIPImageProcessor"]
|
55 |
+
|
56 |
+
try:
|
57 |
+
if not is_torch_available():
|
58 |
+
raise OptionalDependencyNotAvailable()
|
59 |
+
except OptionalDependencyNotAvailable:
|
60 |
+
pass
|
61 |
+
else:
|
62 |
+
_import_structure["modeling_clip"] = [
|
63 |
+
"CLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
|
64 |
+
"CLIPModel",
|
65 |
+
"CLIPPreTrainedModel",
|
66 |
+
"CLIPTextModel",
|
67 |
+
"CLIPTextModelWithProjection",
|
68 |
+
"CLIPVisionModel",
|
69 |
+
"CLIPVisionModelWithProjection",
|
70 |
+
"CLIPForImageClassification",
|
71 |
+
]
|
72 |
+
|
73 |
+
try:
|
74 |
+
if not is_tf_available():
|
75 |
+
raise OptionalDependencyNotAvailable()
|
76 |
+
except OptionalDependencyNotAvailable:
|
77 |
+
pass
|
78 |
+
else:
|
79 |
+
_import_structure["modeling_tf_clip"] = [
|
80 |
+
"TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
|
81 |
+
"TFCLIPModel",
|
82 |
+
"TFCLIPPreTrainedModel",
|
83 |
+
"TFCLIPTextModel",
|
84 |
+
"TFCLIPVisionModel",
|
85 |
+
]
|
86 |
+
|
87 |
+
try:
|
88 |
+
if not is_flax_available():
|
89 |
+
raise OptionalDependencyNotAvailable()
|
90 |
+
except OptionalDependencyNotAvailable:
|
91 |
+
pass
|
92 |
+
else:
|
93 |
+
_import_structure["modeling_flax_clip"] = [
|
94 |
+
"FlaxCLIPModel",
|
95 |
+
"FlaxCLIPPreTrainedModel",
|
96 |
+
"FlaxCLIPTextModel",
|
97 |
+
"FlaxCLIPTextPreTrainedModel",
|
98 |
+
"FlaxCLIPTextModelWithProjection",
|
99 |
+
"FlaxCLIPVisionModel",
|
100 |
+
"FlaxCLIPVisionPreTrainedModel",
|
101 |
+
]
|
102 |
+
|
103 |
+
|
104 |
+
if TYPE_CHECKING:
|
105 |
+
from .configuration_clip import (
|
106 |
+
CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
107 |
+
CLIPConfig,
|
108 |
+
CLIPOnnxConfig,
|
109 |
+
CLIPTextConfig,
|
110 |
+
CLIPVisionConfig,
|
111 |
+
)
|
112 |
+
from .processing_clip import CLIPProcessor
|
113 |
+
from .tokenization_clip import CLIPTokenizer
|
114 |
+
|
115 |
+
try:
|
116 |
+
if not is_tokenizers_available():
|
117 |
+
raise OptionalDependencyNotAvailable()
|
118 |
+
except OptionalDependencyNotAvailable:
|
119 |
+
pass
|
120 |
+
else:
|
121 |
+
from .tokenization_clip_fast import CLIPTokenizerFast
|
122 |
+
|
123 |
+
try:
|
124 |
+
if not is_vision_available():
|
125 |
+
raise OptionalDependencyNotAvailable()
|
126 |
+
except OptionalDependencyNotAvailable:
|
127 |
+
pass
|
128 |
+
else:
|
129 |
+
from .feature_extraction_clip import CLIPFeatureExtractor
|
130 |
+
from .image_processing_clip import CLIPImageProcessor
|
131 |
+
|
132 |
+
try:
|
133 |
+
if not is_torch_available():
|
134 |
+
raise OptionalDependencyNotAvailable()
|
135 |
+
except OptionalDependencyNotAvailable:
|
136 |
+
pass
|
137 |
+
else:
|
138 |
+
from .modeling_clip import (
|
139 |
+
CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
|
140 |
+
CLIPForImageClassification,
|
141 |
+
CLIPModel,
|
142 |
+
CLIPPreTrainedModel,
|
143 |
+
CLIPTextModel,
|
144 |
+
CLIPTextModelWithProjection,
|
145 |
+
CLIPVisionModel,
|
146 |
+
CLIPVisionModelWithProjection,
|
147 |
+
)
|
148 |
+
|
149 |
+
try:
|
150 |
+
if not is_tf_available():
|
151 |
+
raise OptionalDependencyNotAvailable()
|
152 |
+
except OptionalDependencyNotAvailable:
|
153 |
+
pass
|
154 |
+
else:
|
155 |
+
from .modeling_tf_clip import (
|
156 |
+
TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
|
157 |
+
TFCLIPModel,
|
158 |
+
TFCLIPPreTrainedModel,
|
159 |
+
TFCLIPTextModel,
|
160 |
+
TFCLIPVisionModel,
|
161 |
+
)
|
162 |
+
|
163 |
+
try:
|
164 |
+
if not is_flax_available():
|
165 |
+
raise OptionalDependencyNotAvailable()
|
166 |
+
except OptionalDependencyNotAvailable:
|
167 |
+
pass
|
168 |
+
else:
|
169 |
+
from .modeling_flax_clip import (
|
170 |
+
FlaxCLIPModel,
|
171 |
+
FlaxCLIPPreTrainedModel,
|
172 |
+
FlaxCLIPTextModel,
|
173 |
+
FlaxCLIPTextModelWithProjection,
|
174 |
+
FlaxCLIPTextPreTrainedModel,
|
175 |
+
FlaxCLIPVisionModel,
|
176 |
+
FlaxCLIPVisionPreTrainedModel,
|
177 |
+
)
|
178 |
+
|
179 |
+
|
180 |
+
else:
|
181 |
+
import sys
|
182 |
+
|
183 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.61 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/configuration_clip.cpython-310.pyc
ADDED
Binary file (16.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/convert_clip_original_pytorch_to_hf.cpython-310.pyc
ADDED
Binary file (3.99 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/feature_extraction_clip.cpython-310.pyc
ADDED
Binary file (1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/image_processing_clip.cpython-310.pyc
ADDED
Binary file (13.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/modeling_clip.cpython-310.pyc
ADDED
Binary file (44 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/modeling_flax_clip.cpython-310.pyc
ADDED
Binary file (38.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/modeling_tf_clip.cpython-310.pyc
ADDED
Binary file (44.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/processing_clip.cpython-310.pyc
ADDED
Binary file (6.51 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/tokenization_clip.cpython-310.pyc
ADDED
Binary file (17.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/__pycache__/tokenization_clip_fast.cpython-310.pyc
ADDED
Binary file (5.91 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/configuration_clip.py
ADDED
@@ -0,0 +1,456 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" CLIP model configuration"""
|
16 |
+
|
17 |
+
import os
|
18 |
+
from collections import OrderedDict
|
19 |
+
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
|
20 |
+
|
21 |
+
|
22 |
+
if TYPE_CHECKING:
|
23 |
+
from ...processing_utils import ProcessorMixin
|
24 |
+
from ...utils import TensorType
|
25 |
+
|
26 |
+
from ...configuration_utils import PretrainedConfig
|
27 |
+
from ...onnx import OnnxConfig
|
28 |
+
from ...utils import logging
|
29 |
+
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__)
|
32 |
+
|
33 |
+
|
34 |
+
from ..deprecated._archive_maps import CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
|
35 |
+
|
36 |
+
|
37 |
+
class CLIPTextConfig(PretrainedConfig):
|
38 |
+
r"""
|
39 |
+
This is the configuration class to store the configuration of a [`CLIPTextModel`]. It is used to instantiate a CLIP
|
40 |
+
text encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
|
41 |
+
with the defaults will yield a similar configuration to that of the text encoder of the CLIP
|
42 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
43 |
+
|
44 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
45 |
+
documentation from [`PretrainedConfig`] for more information.
|
46 |
+
|
47 |
+
Args:
|
48 |
+
vocab_size (`int`, *optional*, defaults to 49408):
|
49 |
+
Vocabulary size of the CLIP text model. Defines the number of different tokens that can be represented by
|
50 |
+
the `inputs_ids` passed when calling [`CLIPModel`].
|
51 |
+
hidden_size (`int`, *optional*, defaults to 512):
|
52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
53 |
+
intermediate_size (`int`, *optional*, defaults to 2048):
|
54 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
55 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
56 |
+
Dimentionality of text and vision projection layers.
|
57 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
58 |
+
Number of hidden layers in the Transformer encoder.
|
59 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
60 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
61 |
+
max_position_embeddings (`int`, *optional*, defaults to 77):
|
62 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
63 |
+
just in case (e.g., 512 or 1024 or 2048).
|
64 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
65 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
66 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
67 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
68 |
+
The epsilon used by the layer normalization layers.
|
69 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
70 |
+
The dropout ratio for the attention probabilities.
|
71 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
72 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
73 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
74 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
75 |
+
testing).
|
76 |
+
pad_token_id (`int`, *optional*, defaults to 1):
|
77 |
+
Padding token id.
|
78 |
+
bos_token_id (`int`, *optional*, defaults to 49406):
|
79 |
+
Beginning of stream token id.
|
80 |
+
eos_token_id (`int`, *optional*, defaults to 49407):
|
81 |
+
End of stream token id.
|
82 |
+
|
83 |
+
Example:
|
84 |
+
|
85 |
+
```python
|
86 |
+
>>> from transformers import CLIPTextConfig, CLIPTextModel
|
87 |
+
|
88 |
+
>>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
|
89 |
+
>>> configuration = CLIPTextConfig()
|
90 |
+
|
91 |
+
>>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
92 |
+
>>> model = CLIPTextModel(configuration)
|
93 |
+
|
94 |
+
>>> # Accessing the model configuration
|
95 |
+
>>> configuration = model.config
|
96 |
+
```"""
|
97 |
+
|
98 |
+
model_type = "clip_text_model"
|
99 |
+
|
100 |
+
def __init__(
|
101 |
+
self,
|
102 |
+
vocab_size=49408,
|
103 |
+
hidden_size=512,
|
104 |
+
intermediate_size=2048,
|
105 |
+
projection_dim=512,
|
106 |
+
num_hidden_layers=12,
|
107 |
+
num_attention_heads=8,
|
108 |
+
max_position_embeddings=77,
|
109 |
+
hidden_act="quick_gelu",
|
110 |
+
layer_norm_eps=1e-5,
|
111 |
+
attention_dropout=0.0,
|
112 |
+
initializer_range=0.02,
|
113 |
+
initializer_factor=1.0,
|
114 |
+
# This differs from `CLIPTokenizer`'s default and from openai/clip
|
115 |
+
# See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
|
116 |
+
pad_token_id=1,
|
117 |
+
bos_token_id=49406,
|
118 |
+
eos_token_id=49407,
|
119 |
+
**kwargs,
|
120 |
+
):
|
121 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
122 |
+
|
123 |
+
self.vocab_size = vocab_size
|
124 |
+
self.hidden_size = hidden_size
|
125 |
+
self.intermediate_size = intermediate_size
|
126 |
+
self.projection_dim = projection_dim
|
127 |
+
self.num_hidden_layers = num_hidden_layers
|
128 |
+
self.num_attention_heads = num_attention_heads
|
129 |
+
self.max_position_embeddings = max_position_embeddings
|
130 |
+
self.layer_norm_eps = layer_norm_eps
|
131 |
+
self.hidden_act = hidden_act
|
132 |
+
self.initializer_range = initializer_range
|
133 |
+
self.initializer_factor = initializer_factor
|
134 |
+
self.attention_dropout = attention_dropout
|
135 |
+
|
136 |
+
@classmethod
|
137 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
138 |
+
cls._set_token_in_kwargs(kwargs)
|
139 |
+
|
140 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
141 |
+
|
142 |
+
# get the text config dict if we are loading from CLIPConfig
|
143 |
+
if config_dict.get("model_type") == "clip":
|
144 |
+
config_dict = config_dict["text_config"]
|
145 |
+
|
146 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
147 |
+
logger.warning(
|
148 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
149 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
150 |
+
)
|
151 |
+
|
152 |
+
return cls.from_dict(config_dict, **kwargs)
|
153 |
+
|
154 |
+
|
155 |
+
class CLIPVisionConfig(PretrainedConfig):
|
156 |
+
r"""
|
157 |
+
This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
|
158 |
+
CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
159 |
+
configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP
|
160 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
161 |
+
|
162 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
163 |
+
documentation from [`PretrainedConfig`] for more information.
|
164 |
+
|
165 |
+
Args:
|
166 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
167 |
+
Dimensionality of the encoder layers and the pooler layer.
|
168 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
169 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
170 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
171 |
+
Dimentionality of text and vision projection layers.
|
172 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
173 |
+
Number of hidden layers in the Transformer encoder.
|
174 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
175 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
176 |
+
num_channels (`int`, *optional*, defaults to 3):
|
177 |
+
The number of input channels.
|
178 |
+
image_size (`int`, *optional*, defaults to 224):
|
179 |
+
The size (resolution) of each image.
|
180 |
+
patch_size (`int`, *optional*, defaults to 32):
|
181 |
+
The size (resolution) of each patch.
|
182 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
183 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
184 |
+
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
|
185 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
186 |
+
The epsilon used by the layer normalization layers.
|
187 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
188 |
+
The dropout ratio for the attention probabilities.
|
189 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
190 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
191 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
192 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
193 |
+
testing).
|
194 |
+
|
195 |
+
Example:
|
196 |
+
|
197 |
+
```python
|
198 |
+
>>> from transformers import CLIPVisionConfig, CLIPVisionModel
|
199 |
+
|
200 |
+
>>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
|
201 |
+
>>> configuration = CLIPVisionConfig()
|
202 |
+
|
203 |
+
>>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
204 |
+
>>> model = CLIPVisionModel(configuration)
|
205 |
+
|
206 |
+
>>> # Accessing the model configuration
|
207 |
+
>>> configuration = model.config
|
208 |
+
```"""
|
209 |
+
|
210 |
+
model_type = "clip_vision_model"
|
211 |
+
|
212 |
+
def __init__(
|
213 |
+
self,
|
214 |
+
hidden_size=768,
|
215 |
+
intermediate_size=3072,
|
216 |
+
projection_dim=512,
|
217 |
+
num_hidden_layers=12,
|
218 |
+
num_attention_heads=12,
|
219 |
+
num_channels=3,
|
220 |
+
image_size=224,
|
221 |
+
patch_size=32,
|
222 |
+
hidden_act="quick_gelu",
|
223 |
+
layer_norm_eps=1e-5,
|
224 |
+
attention_dropout=0.0,
|
225 |
+
initializer_range=0.02,
|
226 |
+
initializer_factor=1.0,
|
227 |
+
**kwargs,
|
228 |
+
):
|
229 |
+
super().__init__(**kwargs)
|
230 |
+
|
231 |
+
self.hidden_size = hidden_size
|
232 |
+
self.intermediate_size = intermediate_size
|
233 |
+
self.projection_dim = projection_dim
|
234 |
+
self.num_hidden_layers = num_hidden_layers
|
235 |
+
self.num_attention_heads = num_attention_heads
|
236 |
+
self.num_channels = num_channels
|
237 |
+
self.patch_size = patch_size
|
238 |
+
self.image_size = image_size
|
239 |
+
self.initializer_range = initializer_range
|
240 |
+
self.initializer_factor = initializer_factor
|
241 |
+
self.attention_dropout = attention_dropout
|
242 |
+
self.layer_norm_eps = layer_norm_eps
|
243 |
+
self.hidden_act = hidden_act
|
244 |
+
|
245 |
+
@classmethod
|
246 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
|
247 |
+
cls._set_token_in_kwargs(kwargs)
|
248 |
+
|
249 |
+
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
|
250 |
+
|
251 |
+
# get the vision config dict if we are loading from CLIPConfig
|
252 |
+
if config_dict.get("model_type") == "clip":
|
253 |
+
config_dict = config_dict["vision_config"]
|
254 |
+
|
255 |
+
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
|
256 |
+
logger.warning(
|
257 |
+
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
|
258 |
+
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
|
259 |
+
)
|
260 |
+
|
261 |
+
return cls.from_dict(config_dict, **kwargs)
|
262 |
+
|
263 |
+
|
264 |
+
class CLIPConfig(PretrainedConfig):
|
265 |
+
r"""
|
266 |
+
[`CLIPConfig`] is the configuration class to store the configuration of a [`CLIPModel`]. It is used to instantiate
|
267 |
+
a CLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
|
268 |
+
a configuration with the defaults will yield a similar configuration to that of the CLIP
|
269 |
+
[openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
|
270 |
+
|
271 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
272 |
+
documentation from [`PretrainedConfig`] for more information.
|
273 |
+
|
274 |
+
Args:
|
275 |
+
text_config (`dict`, *optional*):
|
276 |
+
Dictionary of configuration options used to initialize [`CLIPTextConfig`].
|
277 |
+
vision_config (`dict`, *optional*):
|
278 |
+
Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
|
279 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
280 |
+
Dimentionality of text and vision projection layers.
|
281 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
282 |
+
The inital value of the *logit_scale* paramter. Default is used as per the original CLIP implementation.
|
283 |
+
kwargs (*optional*):
|
284 |
+
Dictionary of keyword arguments.
|
285 |
+
|
286 |
+
Example:
|
287 |
+
|
288 |
+
```python
|
289 |
+
>>> from transformers import CLIPConfig, CLIPModel
|
290 |
+
|
291 |
+
>>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
|
292 |
+
>>> configuration = CLIPConfig()
|
293 |
+
|
294 |
+
>>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
|
295 |
+
>>> model = CLIPModel(configuration)
|
296 |
+
|
297 |
+
>>> # Accessing the model configuration
|
298 |
+
>>> configuration = model.config
|
299 |
+
|
300 |
+
>>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
|
301 |
+
>>> from transformers import CLIPTextConfig, CLIPVisionConfig
|
302 |
+
|
303 |
+
>>> # Initializing a CLIPText and CLIPVision configuration
|
304 |
+
>>> config_text = CLIPTextConfig()
|
305 |
+
>>> config_vision = CLIPVisionConfig()
|
306 |
+
|
307 |
+
>>> config = CLIPConfig.from_text_vision_configs(config_text, config_vision)
|
308 |
+
```"""
|
309 |
+
|
310 |
+
model_type = "clip"
|
311 |
+
|
312 |
+
def __init__(
|
313 |
+
self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
|
314 |
+
):
|
315 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
316 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
317 |
+
# of confusion!).
|
318 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
319 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
320 |
+
|
321 |
+
super().__init__(**kwargs)
|
322 |
+
|
323 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
324 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
325 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
326 |
+
if text_config_dict is not None:
|
327 |
+
if text_config is None:
|
328 |
+
text_config = {}
|
329 |
+
|
330 |
+
# This is the complete result when using `text_config_dict`.
|
331 |
+
_text_config_dict = CLIPTextConfig(**text_config_dict).to_dict()
|
332 |
+
|
333 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
334 |
+
for key, value in _text_config_dict.items():
|
335 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
336 |
+
# If specified in `text_config_dict`
|
337 |
+
if key in text_config_dict:
|
338 |
+
message = (
|
339 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
340 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
341 |
+
)
|
342 |
+
# If inferred from default argument values (just to be super careful)
|
343 |
+
else:
|
344 |
+
message = (
|
345 |
+
f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
|
346 |
+
f'value `text_config["{key}"]` will be overriden.'
|
347 |
+
)
|
348 |
+
logger.info(message)
|
349 |
+
|
350 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
351 |
+
text_config.update(_text_config_dict)
|
352 |
+
|
353 |
+
if vision_config_dict is not None:
|
354 |
+
if vision_config is None:
|
355 |
+
vision_config = {}
|
356 |
+
|
357 |
+
# This is the complete result when using `vision_config_dict`.
|
358 |
+
_vision_config_dict = CLIPVisionConfig(**vision_config_dict).to_dict()
|
359 |
+
# convert keys to string instead of integer
|
360 |
+
if "id2label" in _vision_config_dict:
|
361 |
+
_vision_config_dict["id2label"] = {
|
362 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
363 |
+
}
|
364 |
+
|
365 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
366 |
+
for key, value in _vision_config_dict.items():
|
367 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
368 |
+
# If specified in `vision_config_dict`
|
369 |
+
if key in vision_config_dict:
|
370 |
+
message = (
|
371 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
372 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
373 |
+
)
|
374 |
+
# If inferred from default argument values (just to be super careful)
|
375 |
+
else:
|
376 |
+
message = (
|
377 |
+
f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
|
378 |
+
f'The value `vision_config["{key}"]` will be overriden.'
|
379 |
+
)
|
380 |
+
logger.info(message)
|
381 |
+
|
382 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
383 |
+
vision_config.update(_vision_config_dict)
|
384 |
+
|
385 |
+
if text_config is None:
|
386 |
+
text_config = {}
|
387 |
+
logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.")
|
388 |
+
|
389 |
+
if vision_config is None:
|
390 |
+
vision_config = {}
|
391 |
+
logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.")
|
392 |
+
|
393 |
+
self.text_config = CLIPTextConfig(**text_config)
|
394 |
+
self.vision_config = CLIPVisionConfig(**vision_config)
|
395 |
+
|
396 |
+
self.projection_dim = projection_dim
|
397 |
+
self.logit_scale_init_value = logit_scale_init_value
|
398 |
+
self.initializer_factor = 1.0
|
399 |
+
|
400 |
+
@classmethod
|
401 |
+
def from_text_vision_configs(cls, text_config: CLIPTextConfig, vision_config: CLIPVisionConfig, **kwargs):
|
402 |
+
r"""
|
403 |
+
Instantiate a [`CLIPConfig`] (or a derived class) from clip text model configuration and clip vision model
|
404 |
+
configuration.
|
405 |
+
|
406 |
+
Returns:
|
407 |
+
[`CLIPConfig`]: An instance of a configuration object
|
408 |
+
"""
|
409 |
+
|
410 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
411 |
+
|
412 |
+
|
413 |
+
class CLIPOnnxConfig(OnnxConfig):
|
414 |
+
@property
|
415 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
416 |
+
return OrderedDict(
|
417 |
+
[
|
418 |
+
("input_ids", {0: "batch", 1: "sequence"}),
|
419 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
420 |
+
("attention_mask", {0: "batch", 1: "sequence"}),
|
421 |
+
]
|
422 |
+
)
|
423 |
+
|
424 |
+
@property
|
425 |
+
def outputs(self) -> Mapping[str, Mapping[int, str]]:
|
426 |
+
return OrderedDict(
|
427 |
+
[
|
428 |
+
("logits_per_image", {0: "batch"}),
|
429 |
+
("logits_per_text", {0: "batch"}),
|
430 |
+
("text_embeds", {0: "batch"}),
|
431 |
+
("image_embeds", {0: "batch"}),
|
432 |
+
]
|
433 |
+
)
|
434 |
+
|
435 |
+
@property
|
436 |
+
def atol_for_validation(self) -> float:
|
437 |
+
return 1e-4
|
438 |
+
|
439 |
+
def generate_dummy_inputs(
|
440 |
+
self,
|
441 |
+
processor: "ProcessorMixin",
|
442 |
+
batch_size: int = -1,
|
443 |
+
seq_length: int = -1,
|
444 |
+
framework: Optional["TensorType"] = None,
|
445 |
+
) -> Mapping[str, Any]:
|
446 |
+
text_input_dict = super().generate_dummy_inputs(
|
447 |
+
processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
|
448 |
+
)
|
449 |
+
image_input_dict = super().generate_dummy_inputs(
|
450 |
+
processor.image_processor, batch_size=batch_size, framework=framework
|
451 |
+
)
|
452 |
+
return {**text_input_dict, **image_input_dict}
|
453 |
+
|
454 |
+
@property
|
455 |
+
def default_onnx_opset(self) -> int:
|
456 |
+
return 14
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/convert_clip_original_pytorch_to_hf.py
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
import argparse
|
17 |
+
|
18 |
+
import torch
|
19 |
+
from clip import load
|
20 |
+
|
21 |
+
from transformers import CLIPConfig, CLIPModel
|
22 |
+
|
23 |
+
|
24 |
+
def copy_attn_layer(hf_attn_layer, pt_attn_layer):
|
25 |
+
q_proj, k_proj, v_proj = pt_attn_layer.in_proj_weight.chunk(3, dim=0)
|
26 |
+
q_proj_bias, k_proj_bias, v_proj_bias = pt_attn_layer.in_proj_bias.chunk(3, dim=0)
|
27 |
+
|
28 |
+
out_proj_weights = pt_attn_layer.out_proj.weight
|
29 |
+
out_proj_bias = pt_attn_layer.out_proj.bias
|
30 |
+
|
31 |
+
hf_attn_layer.q_proj.weight.data = q_proj
|
32 |
+
hf_attn_layer.q_proj.bias.data = q_proj_bias
|
33 |
+
|
34 |
+
hf_attn_layer.k_proj.weight.data = k_proj
|
35 |
+
hf_attn_layer.k_proj.bias.data = k_proj_bias
|
36 |
+
|
37 |
+
hf_attn_layer.v_proj.weight.data = v_proj
|
38 |
+
hf_attn_layer.v_proj.bias.data = v_proj_bias
|
39 |
+
|
40 |
+
hf_attn_layer.out_proj.weight = out_proj_weights
|
41 |
+
hf_attn_layer.out_proj.bias = out_proj_bias
|
42 |
+
|
43 |
+
|
44 |
+
def copy_mlp(hf_mlp, pt_mlp):
|
45 |
+
copy_linear(hf_mlp.fc1, pt_mlp.c_fc)
|
46 |
+
copy_linear(hf_mlp.fc2, pt_mlp.c_proj)
|
47 |
+
|
48 |
+
|
49 |
+
def copy_linear(hf_linear, pt_linear):
|
50 |
+
hf_linear.weight = pt_linear.weight
|
51 |
+
hf_linear.bias = pt_linear.bias
|
52 |
+
|
53 |
+
|
54 |
+
def copy_layer(hf_layer, pt_layer):
|
55 |
+
# copy layer norms
|
56 |
+
copy_linear(hf_layer.layer_norm1, pt_layer.ln_1)
|
57 |
+
copy_linear(hf_layer.layer_norm2, pt_layer.ln_2)
|
58 |
+
|
59 |
+
# copy MLP
|
60 |
+
copy_mlp(hf_layer.mlp, pt_layer.mlp)
|
61 |
+
|
62 |
+
# copy attn
|
63 |
+
copy_attn_layer(hf_layer.self_attn, pt_layer.attn)
|
64 |
+
|
65 |
+
|
66 |
+
def copy_layers(hf_layers, pt_layers):
|
67 |
+
for hf_layer, pt_layer in zip(hf_layers, pt_layers):
|
68 |
+
copy_layer(hf_layer, pt_layer)
|
69 |
+
|
70 |
+
|
71 |
+
def copy_encoder(hf_encoder, pt_model):
|
72 |
+
# copy embeds
|
73 |
+
hf_encoder.embeddings.token_embedding.weight = pt_model.token_embedding.weight
|
74 |
+
hf_encoder.embeddings.position_embedding.weight.data = pt_model.positional_embedding
|
75 |
+
|
76 |
+
# copy layer norm
|
77 |
+
copy_linear(hf_encoder.final_layer_norm, pt_model.ln_final)
|
78 |
+
|
79 |
+
# copy hidden layers
|
80 |
+
copy_layers(hf_encoder.encoder.layers, pt_model.transformer.resblocks)
|
81 |
+
|
82 |
+
|
83 |
+
def copy_text_model_and_projection(hf_model, pt_model):
|
84 |
+
# copy projection
|
85 |
+
hf_model.text_projection.weight.data = pt_model.text_projection.data.T
|
86 |
+
|
87 |
+
# copy text encoder
|
88 |
+
copy_encoder(hf_model.text_model, pt_model)
|
89 |
+
|
90 |
+
|
91 |
+
def copy_vison_model_and_projection(hf_model, pt_model):
|
92 |
+
# copy projection
|
93 |
+
hf_model.visual_projection.weight.data = pt_model.visual.proj.data.T
|
94 |
+
|
95 |
+
# copy layer norms
|
96 |
+
copy_linear(hf_model.vision_model.pre_layrnorm, pt_model.visual.ln_pre)
|
97 |
+
copy_linear(hf_model.vision_model.post_layernorm, pt_model.visual.ln_post)
|
98 |
+
|
99 |
+
# copy embeds
|
100 |
+
hf_model.vision_model.embeddings.patch_embedding.weight.data = pt_model.visual.conv1.weight.data
|
101 |
+
hf_model.vision_model.embeddings.class_embedding = pt_model.visual.class_embedding
|
102 |
+
hf_model.vision_model.embeddings.position_embedding.weight.data = pt_model.visual.positional_embedding.data
|
103 |
+
|
104 |
+
# copy encoder
|
105 |
+
copy_layers(hf_model.vision_model.encoder.layers, pt_model.visual.transformer.resblocks)
|
106 |
+
|
107 |
+
|
108 |
+
@torch.no_grad()
|
109 |
+
def convert_clip_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None):
|
110 |
+
"""
|
111 |
+
Copy/paste/tweak model's weights to transformers design.
|
112 |
+
"""
|
113 |
+
if config_path is not None:
|
114 |
+
config = CLIPConfig.from_pretrained(config_path)
|
115 |
+
else:
|
116 |
+
config = CLIPConfig(projection_dim=512, text_config={}, vision_config={})
|
117 |
+
|
118 |
+
hf_model = CLIPModel(config).eval()
|
119 |
+
|
120 |
+
pt_model, _ = load(checkpoint_path, device="cpu", jit=False)
|
121 |
+
pt_model = pt_model.eval()
|
122 |
+
|
123 |
+
copy_text_model_and_projection(hf_model, pt_model)
|
124 |
+
copy_vison_model_and_projection(hf_model, pt_model)
|
125 |
+
hf_model.logit_scale = pt_model.logit_scale
|
126 |
+
|
127 |
+
input_ids = torch.arange(0, 77).unsqueeze(0)
|
128 |
+
pixel_values = torch.randn(1, 3, 224, 224)
|
129 |
+
|
130 |
+
hf_outputs = hf_model(input_ids=input_ids, pixel_values=pixel_values, return_dict=True)
|
131 |
+
hf_logits_per_image = hf_outputs.logits_per_image
|
132 |
+
hf_logits_per_text = hf_outputs.logits_per_text
|
133 |
+
pt_logits_per_image, pt_logits_per_text = pt_model(pixel_values, input_ids)
|
134 |
+
|
135 |
+
assert torch.allclose(hf_logits_per_image, pt_logits_per_image, atol=1e-3)
|
136 |
+
assert torch.allclose(hf_logits_per_text, pt_logits_per_text, atol=1e-3)
|
137 |
+
|
138 |
+
hf_model.save_pretrained(pytorch_dump_folder_path)
|
139 |
+
|
140 |
+
|
141 |
+
if __name__ == "__main__":
|
142 |
+
parser = argparse.ArgumentParser()
|
143 |
+
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
|
144 |
+
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
|
145 |
+
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
|
146 |
+
args = parser.parse_args()
|
147 |
+
|
148 |
+
convert_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/feature_extraction_clip.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Feature extractor class for CLIP."""
|
16 |
+
|
17 |
+
import warnings
|
18 |
+
|
19 |
+
from ...utils import logging
|
20 |
+
from .image_processing_clip import CLIPImageProcessor
|
21 |
+
|
22 |
+
|
23 |
+
logger = logging.get_logger(__name__)
|
24 |
+
|
25 |
+
|
26 |
+
class CLIPFeatureExtractor(CLIPImageProcessor):
|
27 |
+
def __init__(self, *args, **kwargs) -> None:
|
28 |
+
warnings.warn(
|
29 |
+
"The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
|
30 |
+
" use CLIPImageProcessor instead.",
|
31 |
+
FutureWarning,
|
32 |
+
)
|
33 |
+
super().__init__(*args, **kwargs)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/image_processing_clip.py
ADDED
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 CLIP."""
|
16 |
+
|
17 |
+
from typing import Dict, List, Optional, Union
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
|
21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
22 |
+
from ...image_transforms import (
|
23 |
+
convert_to_rgb,
|
24 |
+
get_resize_output_image_size,
|
25 |
+
resize,
|
26 |
+
to_channel_dimension_format,
|
27 |
+
)
|
28 |
+
from ...image_utils import (
|
29 |
+
OPENAI_CLIP_MEAN,
|
30 |
+
OPENAI_CLIP_STD,
|
31 |
+
ChannelDimension,
|
32 |
+
ImageInput,
|
33 |
+
PILImageResampling,
|
34 |
+
infer_channel_dimension_format,
|
35 |
+
is_scaled_image,
|
36 |
+
make_list_of_images,
|
37 |
+
to_numpy_array,
|
38 |
+
valid_images,
|
39 |
+
validate_kwargs,
|
40 |
+
validate_preprocess_arguments,
|
41 |
+
)
|
42 |
+
from ...utils import TensorType, is_vision_available, logging
|
43 |
+
|
44 |
+
|
45 |
+
logger = logging.get_logger(__name__)
|
46 |
+
|
47 |
+
|
48 |
+
if is_vision_available():
|
49 |
+
import PIL
|
50 |
+
|
51 |
+
|
52 |
+
class CLIPImageProcessor(BaseImageProcessor):
|
53 |
+
r"""
|
54 |
+
Constructs a CLIP image processor.
|
55 |
+
|
56 |
+
Args:
|
57 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
58 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
|
59 |
+
`do_resize` in the `preprocess` method.
|
60 |
+
size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
|
61 |
+
Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
|
62 |
+
the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
|
63 |
+
method.
|
64 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
65 |
+
Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
|
66 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
67 |
+
Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
|
68 |
+
`preprocess` method.
|
69 |
+
crop_size (`Dict[str, int]` *optional*, defaults to 224):
|
70 |
+
Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
|
71 |
+
method.
|
72 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
73 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
|
74 |
+
the `preprocess` method.
|
75 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
76 |
+
Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
|
77 |
+
method.
|
78 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
79 |
+
Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
|
80 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
|
81 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
82 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
83 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
|
84 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
85 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
86 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
87 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
88 |
+
Whether to convert the image to RGB.
|
89 |
+
"""
|
90 |
+
|
91 |
+
model_input_names = ["pixel_values"]
|
92 |
+
|
93 |
+
def __init__(
|
94 |
+
self,
|
95 |
+
do_resize: bool = True,
|
96 |
+
size: Dict[str, int] = None,
|
97 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
98 |
+
do_center_crop: bool = True,
|
99 |
+
crop_size: Dict[str, int] = None,
|
100 |
+
do_rescale: bool = True,
|
101 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
102 |
+
do_normalize: bool = True,
|
103 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
104 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
105 |
+
do_convert_rgb: bool = True,
|
106 |
+
**kwargs,
|
107 |
+
) -> None:
|
108 |
+
super().__init__(**kwargs)
|
109 |
+
size = size if size is not None else {"shortest_edge": 224}
|
110 |
+
size = get_size_dict(size, default_to_square=False)
|
111 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
112 |
+
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
|
113 |
+
|
114 |
+
self.do_resize = do_resize
|
115 |
+
self.size = size
|
116 |
+
self.resample = resample
|
117 |
+
self.do_center_crop = do_center_crop
|
118 |
+
self.crop_size = crop_size
|
119 |
+
self.do_rescale = do_rescale
|
120 |
+
self.rescale_factor = rescale_factor
|
121 |
+
self.do_normalize = do_normalize
|
122 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
123 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
124 |
+
self.do_convert_rgb = do_convert_rgb
|
125 |
+
self._valid_processor_keys = [
|
126 |
+
"images",
|
127 |
+
"do_resize",
|
128 |
+
"size",
|
129 |
+
"resample",
|
130 |
+
"do_center_crop",
|
131 |
+
"crop_size",
|
132 |
+
"do_rescale",
|
133 |
+
"rescale_factor",
|
134 |
+
"do_normalize",
|
135 |
+
"image_mean",
|
136 |
+
"image_std",
|
137 |
+
"do_convert_rgb",
|
138 |
+
"return_tensors",
|
139 |
+
"data_format",
|
140 |
+
"input_data_format",
|
141 |
+
]
|
142 |
+
|
143 |
+
# for backwards compatibility of KOSMOS-2
|
144 |
+
if "use_square_size" in kwargs:
|
145 |
+
self.size = {"height": size["shortest_edge"], "width": size["shortest_edge"]}
|
146 |
+
|
147 |
+
def resize(
|
148 |
+
self,
|
149 |
+
image: np.ndarray,
|
150 |
+
size: Dict[str, int],
|
151 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
152 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
153 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
154 |
+
**kwargs,
|
155 |
+
) -> np.ndarray:
|
156 |
+
"""
|
157 |
+
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
|
158 |
+
resized to keep the input aspect ratio.
|
159 |
+
|
160 |
+
Args:
|
161 |
+
image (`np.ndarray`):
|
162 |
+
Image to resize.
|
163 |
+
size (`Dict[str, int]`):
|
164 |
+
Size of the output image.
|
165 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
166 |
+
Resampling filter to use when resiizing the image.
|
167 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
168 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
169 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
170 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
171 |
+
"""
|
172 |
+
default_to_square = True
|
173 |
+
if "shortest_edge" in size:
|
174 |
+
size = size["shortest_edge"]
|
175 |
+
default_to_square = False
|
176 |
+
elif "height" in size and "width" in size:
|
177 |
+
size = (size["height"], size["width"])
|
178 |
+
else:
|
179 |
+
raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
|
180 |
+
|
181 |
+
output_size = get_resize_output_image_size(
|
182 |
+
image,
|
183 |
+
size=size,
|
184 |
+
default_to_square=default_to_square,
|
185 |
+
input_data_format=input_data_format,
|
186 |
+
)
|
187 |
+
return resize(
|
188 |
+
image,
|
189 |
+
size=output_size,
|
190 |
+
resample=resample,
|
191 |
+
data_format=data_format,
|
192 |
+
input_data_format=input_data_format,
|
193 |
+
**kwargs,
|
194 |
+
)
|
195 |
+
|
196 |
+
def preprocess(
|
197 |
+
self,
|
198 |
+
images: ImageInput,
|
199 |
+
do_resize: bool = None,
|
200 |
+
size: Dict[str, int] = None,
|
201 |
+
resample: PILImageResampling = None,
|
202 |
+
do_center_crop: bool = None,
|
203 |
+
crop_size: int = None,
|
204 |
+
do_rescale: bool = None,
|
205 |
+
rescale_factor: float = None,
|
206 |
+
do_normalize: bool = None,
|
207 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
208 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
209 |
+
do_convert_rgb: bool = None,
|
210 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
211 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
212 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
213 |
+
**kwargs,
|
214 |
+
) -> PIL.Image.Image:
|
215 |
+
"""
|
216 |
+
Preprocess an image or batch of images.
|
217 |
+
|
218 |
+
Args:
|
219 |
+
images (`ImageInput`):
|
220 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
221 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
222 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
223 |
+
Whether to resize the image.
|
224 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
225 |
+
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
|
226 |
+
the longest edge resized to keep the input aspect ratio.
|
227 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
228 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
229 |
+
has an effect if `do_resize` is set to `True`.
|
230 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
231 |
+
Whether to center crop the image.
|
232 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
233 |
+
Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
|
234 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
235 |
+
Whether to rescale the image.
|
236 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
237 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
238 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
239 |
+
Whether to normalize the image.
|
240 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
241 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
242 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
243 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
244 |
+
`True`.
|
245 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
246 |
+
Whether to convert the image to RGB.
|
247 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
248 |
+
The type of tensors to return. Can be one of:
|
249 |
+
- Unset: Return a list of `np.ndarray`.
|
250 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
251 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
252 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
253 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
254 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
255 |
+
The channel dimension format for the output image. Can be one of:
|
256 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
257 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
258 |
+
- Unset: Use the channel dimension format of the input image.
|
259 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
260 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
261 |
+
from the input image. Can be one of:
|
262 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
263 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
264 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
265 |
+
"""
|
266 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
267 |
+
size = size if size is not None else self.size
|
268 |
+
size = get_size_dict(size, param_name="size", default_to_square=False)
|
269 |
+
resample = resample if resample is not None else self.resample
|
270 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
271 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
272 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
|
273 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
274 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
275 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
276 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
277 |
+
image_std = image_std if image_std is not None else self.image_std
|
278 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
279 |
+
|
280 |
+
validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
|
281 |
+
|
282 |
+
images = make_list_of_images(images)
|
283 |
+
|
284 |
+
if not valid_images(images):
|
285 |
+
raise ValueError(
|
286 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
287 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
288 |
+
)
|
289 |
+
validate_preprocess_arguments(
|
290 |
+
do_rescale=do_rescale,
|
291 |
+
rescale_factor=rescale_factor,
|
292 |
+
do_normalize=do_normalize,
|
293 |
+
image_mean=image_mean,
|
294 |
+
image_std=image_std,
|
295 |
+
do_center_crop=do_center_crop,
|
296 |
+
crop_size=crop_size,
|
297 |
+
do_resize=do_resize,
|
298 |
+
size=size,
|
299 |
+
resample=resample,
|
300 |
+
)
|
301 |
+
|
302 |
+
if do_convert_rgb:
|
303 |
+
images = [convert_to_rgb(image) for image in images]
|
304 |
+
|
305 |
+
# All transformations expect numpy arrays.
|
306 |
+
images = [to_numpy_array(image) for image in images]
|
307 |
+
|
308 |
+
if is_scaled_image(images[0]) and do_rescale:
|
309 |
+
logger.warning_once(
|
310 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
311 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
312 |
+
)
|
313 |
+
|
314 |
+
if input_data_format is None:
|
315 |
+
# We assume that all images have the same channel dimension format.
|
316 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
317 |
+
|
318 |
+
if do_resize:
|
319 |
+
images = [
|
320 |
+
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
321 |
+
for image in images
|
322 |
+
]
|
323 |
+
|
324 |
+
if do_center_crop:
|
325 |
+
images = [
|
326 |
+
self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
|
327 |
+
]
|
328 |
+
|
329 |
+
if do_rescale:
|
330 |
+
images = [
|
331 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
332 |
+
for image in images
|
333 |
+
]
|
334 |
+
|
335 |
+
if do_normalize:
|
336 |
+
images = [
|
337 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
338 |
+
for image in images
|
339 |
+
]
|
340 |
+
|
341 |
+
images = [
|
342 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
343 |
+
]
|
344 |
+
|
345 |
+
data = {"pixel_values": images}
|
346 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/modeling_clip.py
ADDED
@@ -0,0 +1,1416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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penAI Team Authors and The HuggingFace 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 CLIP model."""
|
16 |
+
|
17 |
+
|
18 |
+
from dataclasses import dataclass
|
19 |
+
from typing import Any, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.utils.checkpoint
|
23 |
+
from torch import nn
|
24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
25 |
+
|
26 |
+
from ...activations import ACT2FN
|
27 |
+
from ...modeling_attn_mask_utils import _create_4d_causal_attention_mask, _prepare_4d_attention_mask
|
28 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
|
29 |
+
from ...modeling_utils import PreTrainedModel
|
30 |
+
from ...utils import (
|
31 |
+
ModelOutput,
|
32 |
+
add_code_sample_docstrings,
|
33 |
+
add_start_docstrings,
|
34 |
+
add_start_docstrings_to_model_forward,
|
35 |
+
logging,
|
36 |
+
replace_return_docstrings,
|
37 |
+
)
|
38 |
+
from .configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
|
39 |
+
|
40 |
+
|
41 |
+
logger = logging.get_logger(__name__)
|
42 |
+
|
43 |
+
# General docstring
|
44 |
+
_CONFIG_FOR_DOC = "CLIPConfig"
|
45 |
+
_CHECKPOINT_FOR_DOC = "openai/clip-vit-base-patch32"
|
46 |
+
|
47 |
+
# Image classification docstring
|
48 |
+
_IMAGE_CLASS_CHECKPOINT = "openai/clip-vit-base-patch32"
|
49 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "LABEL_0"
|
50 |
+
|
51 |
+
|
52 |
+
from ..deprecated._archive_maps import CLIP_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
53 |
+
|
54 |
+
|
55 |
+
# contrastive loss function, adapted from
|
56 |
+
# https://sachinruk.github.io/blog/2021-03-07-clip.html
|
57 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
58 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
59 |
+
|
60 |
+
|
61 |
+
def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
62 |
+
caption_loss = contrastive_loss(similarity)
|
63 |
+
image_loss = contrastive_loss(similarity.t())
|
64 |
+
return (caption_loss + image_loss) / 2.0
|
65 |
+
|
66 |
+
|
67 |
+
@dataclass
|
68 |
+
class CLIPVisionModelOutput(ModelOutput):
|
69 |
+
"""
|
70 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
71 |
+
|
72 |
+
Args:
|
73 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
74 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
75 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
76 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
77 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
78 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
79 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
80 |
+
|
81 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
82 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
83 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
84 |
+
sequence_length)`.
|
85 |
+
|
86 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
87 |
+
heads.
|
88 |
+
"""
|
89 |
+
|
90 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
91 |
+
last_hidden_state: torch.FloatTensor = None
|
92 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
93 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
94 |
+
|
95 |
+
|
96 |
+
@dataclass
|
97 |
+
class CLIPTextModelOutput(ModelOutput):
|
98 |
+
"""
|
99 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
100 |
+
|
101 |
+
Args:
|
102 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
103 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
104 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
105 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
106 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
107 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
108 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
109 |
+
|
110 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
111 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
112 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
113 |
+
sequence_length)`.
|
114 |
+
|
115 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
116 |
+
heads.
|
117 |
+
"""
|
118 |
+
|
119 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
120 |
+
last_hidden_state: torch.FloatTensor = None
|
121 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
122 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
123 |
+
|
124 |
+
|
125 |
+
@dataclass
|
126 |
+
class CLIPOutput(ModelOutput):
|
127 |
+
"""
|
128 |
+
Args:
|
129 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
130 |
+
Contrastive loss for image-text similarity.
|
131 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
132 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
133 |
+
similarity scores.
|
134 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
135 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
136 |
+
similarity scores.
|
137 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
138 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPTextModel`].
|
139 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
140 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`].
|
141 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
142 |
+
The output of the [`CLIPTextModel`].
|
143 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
144 |
+
The output of the [`CLIPVisionModel`].
|
145 |
+
"""
|
146 |
+
|
147 |
+
loss: Optional[torch.FloatTensor] = None
|
148 |
+
logits_per_image: torch.FloatTensor = None
|
149 |
+
logits_per_text: torch.FloatTensor = None
|
150 |
+
text_embeds: torch.FloatTensor = None
|
151 |
+
image_embeds: torch.FloatTensor = None
|
152 |
+
text_model_output: BaseModelOutputWithPooling = None
|
153 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
154 |
+
|
155 |
+
def to_tuple(self) -> Tuple[Any]:
|
156 |
+
return tuple(
|
157 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
158 |
+
for k in self.keys()
|
159 |
+
)
|
160 |
+
|
161 |
+
|
162 |
+
class CLIPVisionEmbeddings(nn.Module):
|
163 |
+
def __init__(self, config: CLIPVisionConfig):
|
164 |
+
super().__init__()
|
165 |
+
self.config = config
|
166 |
+
self.embed_dim = config.hidden_size
|
167 |
+
self.image_size = config.image_size
|
168 |
+
self.patch_size = config.patch_size
|
169 |
+
|
170 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
171 |
+
|
172 |
+
self.patch_embedding = nn.Conv2d(
|
173 |
+
in_channels=config.num_channels,
|
174 |
+
out_channels=self.embed_dim,
|
175 |
+
kernel_size=self.patch_size,
|
176 |
+
stride=self.patch_size,
|
177 |
+
bias=False,
|
178 |
+
)
|
179 |
+
|
180 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
181 |
+
self.num_positions = self.num_patches + 1
|
182 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
183 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
184 |
+
|
185 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
186 |
+
batch_size = pixel_values.shape[0]
|
187 |
+
target_dtype = self.patch_embedding.weight.dtype
|
188 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
189 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
190 |
+
|
191 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
192 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
193 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
194 |
+
return embeddings
|
195 |
+
|
196 |
+
|
197 |
+
class CLIPTextEmbeddings(nn.Module):
|
198 |
+
def __init__(self, config: CLIPTextConfig):
|
199 |
+
super().__init__()
|
200 |
+
embed_dim = config.hidden_size
|
201 |
+
|
202 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
203 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
204 |
+
|
205 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
206 |
+
self.register_buffer(
|
207 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
208 |
+
)
|
209 |
+
|
210 |
+
def forward(
|
211 |
+
self,
|
212 |
+
input_ids: Optional[torch.LongTensor] = None,
|
213 |
+
position_ids: Optional[torch.LongTensor] = None,
|
214 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
215 |
+
) -> torch.Tensor:
|
216 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
217 |
+
|
218 |
+
if position_ids is None:
|
219 |
+
position_ids = self.position_ids[:, :seq_length]
|
220 |
+
|
221 |
+
if inputs_embeds is None:
|
222 |
+
inputs_embeds = self.token_embedding(input_ids)
|
223 |
+
|
224 |
+
position_embeddings = self.position_embedding(position_ids)
|
225 |
+
embeddings = inputs_embeds + position_embeddings
|
226 |
+
|
227 |
+
return embeddings
|
228 |
+
|
229 |
+
|
230 |
+
class CLIPAttention(nn.Module):
|
231 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
232 |
+
|
233 |
+
def __init__(self, config):
|
234 |
+
super().__init__()
|
235 |
+
self.config = config
|
236 |
+
self.embed_dim = config.hidden_size
|
237 |
+
self.num_heads = config.num_attention_heads
|
238 |
+
self.head_dim = self.embed_dim // self.num_heads
|
239 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
240 |
+
raise ValueError(
|
241 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
242 |
+
f" {self.num_heads})."
|
243 |
+
)
|
244 |
+
self.scale = self.head_dim**-0.5
|
245 |
+
self.dropout = config.attention_dropout
|
246 |
+
|
247 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
248 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
249 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
250 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
251 |
+
|
252 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
253 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
254 |
+
|
255 |
+
def forward(
|
256 |
+
self,
|
257 |
+
hidden_states: torch.Tensor,
|
258 |
+
attention_mask: Optional[torch.Tensor] = None,
|
259 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
260 |
+
output_attentions: Optional[bool] = False,
|
261 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
262 |
+
"""Input shape: Batch x Time x Channel"""
|
263 |
+
|
264 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
265 |
+
|
266 |
+
# get query proj
|
267 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
268 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
269 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
270 |
+
|
271 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
272 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
273 |
+
key_states = key_states.view(*proj_shape)
|
274 |
+
value_states = value_states.view(*proj_shape)
|
275 |
+
|
276 |
+
src_len = key_states.size(1)
|
277 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
278 |
+
|
279 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
280 |
+
raise ValueError(
|
281 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
282 |
+
f" {attn_weights.size()}"
|
283 |
+
)
|
284 |
+
|
285 |
+
# apply the causal_attention_mask first
|
286 |
+
if causal_attention_mask is not None:
|
287 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
288 |
+
raise ValueError(
|
289 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
290 |
+
f" {causal_attention_mask.size()}"
|
291 |
+
)
|
292 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
293 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
294 |
+
|
295 |
+
if attention_mask is not None:
|
296 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
297 |
+
raise ValueError(
|
298 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
299 |
+
)
|
300 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
301 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
302 |
+
|
303 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
304 |
+
|
305 |
+
if output_attentions:
|
306 |
+
# this operation is a bit akward, but it's required to
|
307 |
+
# make sure that attn_weights keeps its gradient.
|
308 |
+
# In order to do so, attn_weights have to reshaped
|
309 |
+
# twice and have to be reused in the following
|
310 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
311 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
312 |
+
else:
|
313 |
+
attn_weights_reshaped = None
|
314 |
+
|
315 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
316 |
+
|
317 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
318 |
+
|
319 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
320 |
+
raise ValueError(
|
321 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
322 |
+
f" {attn_output.size()}"
|
323 |
+
)
|
324 |
+
|
325 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
326 |
+
attn_output = attn_output.transpose(1, 2)
|
327 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
328 |
+
|
329 |
+
attn_output = self.out_proj(attn_output)
|
330 |
+
|
331 |
+
return attn_output, attn_weights_reshaped
|
332 |
+
|
333 |
+
|
334 |
+
class CLIPMLP(nn.Module):
|
335 |
+
def __init__(self, config):
|
336 |
+
super().__init__()
|
337 |
+
self.config = config
|
338 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
339 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
340 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
341 |
+
|
342 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
343 |
+
hidden_states = self.fc1(hidden_states)
|
344 |
+
hidden_states = self.activation_fn(hidden_states)
|
345 |
+
hidden_states = self.fc2(hidden_states)
|
346 |
+
return hidden_states
|
347 |
+
|
348 |
+
|
349 |
+
class CLIPEncoderLayer(nn.Module):
|
350 |
+
def __init__(self, config: CLIPConfig):
|
351 |
+
super().__init__()
|
352 |
+
self.embed_dim = config.hidden_size
|
353 |
+
self.self_attn = CLIPAttention(config)
|
354 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
355 |
+
self.mlp = CLIPMLP(config)
|
356 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
357 |
+
|
358 |
+
def forward(
|
359 |
+
self,
|
360 |
+
hidden_states: torch.Tensor,
|
361 |
+
attention_mask: torch.Tensor,
|
362 |
+
causal_attention_mask: torch.Tensor,
|
363 |
+
output_attentions: Optional[bool] = False,
|
364 |
+
) -> Tuple[torch.FloatTensor]:
|
365 |
+
"""
|
366 |
+
Args:
|
367 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
368 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
369 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
370 |
+
`(config.encoder_attention_heads,)`.
|
371 |
+
output_attentions (`bool`, *optional*):
|
372 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
373 |
+
returned tensors for more detail.
|
374 |
+
"""
|
375 |
+
residual = hidden_states
|
376 |
+
|
377 |
+
hidden_states = self.layer_norm1(hidden_states)
|
378 |
+
hidden_states, attn_weights = self.self_attn(
|
379 |
+
hidden_states=hidden_states,
|
380 |
+
attention_mask=attention_mask,
|
381 |
+
causal_attention_mask=causal_attention_mask,
|
382 |
+
output_attentions=output_attentions,
|
383 |
+
)
|
384 |
+
hidden_states = residual + hidden_states
|
385 |
+
|
386 |
+
residual = hidden_states
|
387 |
+
hidden_states = self.layer_norm2(hidden_states)
|
388 |
+
hidden_states = self.mlp(hidden_states)
|
389 |
+
hidden_states = residual + hidden_states
|
390 |
+
|
391 |
+
outputs = (hidden_states,)
|
392 |
+
|
393 |
+
if output_attentions:
|
394 |
+
outputs += (attn_weights,)
|
395 |
+
|
396 |
+
return outputs
|
397 |
+
|
398 |
+
|
399 |
+
class CLIPPreTrainedModel(PreTrainedModel):
|
400 |
+
"""
|
401 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
402 |
+
models.
|
403 |
+
"""
|
404 |
+
|
405 |
+
config_class = CLIPConfig
|
406 |
+
base_model_prefix = "clip"
|
407 |
+
supports_gradient_checkpointing = True
|
408 |
+
|
409 |
+
def _init_weights(self, module):
|
410 |
+
"""Initialize the weights"""
|
411 |
+
factor = self.config.initializer_factor
|
412 |
+
if isinstance(module, CLIPTextEmbeddings):
|
413 |
+
module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
414 |
+
module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
415 |
+
elif isinstance(module, CLIPVisionEmbeddings):
|
416 |
+
factor = self.config.initializer_factor
|
417 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
418 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
419 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
420 |
+
elif isinstance(module, CLIPAttention):
|
421 |
+
factor = self.config.initializer_factor
|
422 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
423 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
424 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
425 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
426 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
427 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
428 |
+
elif isinstance(module, CLIPMLP):
|
429 |
+
factor = self.config.initializer_factor
|
430 |
+
in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
431 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
432 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
433 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
434 |
+
elif isinstance(module, CLIPModel):
|
435 |
+
nn.init.normal_(
|
436 |
+
module.text_projection.weight,
|
437 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
438 |
+
)
|
439 |
+
nn.init.normal_(
|
440 |
+
module.visual_projection.weight,
|
441 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
442 |
+
)
|
443 |
+
elif isinstance(module, CLIPVisionModelWithProjection):
|
444 |
+
nn.init.normal_(
|
445 |
+
module.visual_projection.weight,
|
446 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
447 |
+
)
|
448 |
+
elif isinstance(module, CLIPTextModelWithProjection):
|
449 |
+
nn.init.normal_(
|
450 |
+
module.text_projection.weight,
|
451 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
452 |
+
)
|
453 |
+
|
454 |
+
if isinstance(module, nn.LayerNorm):
|
455 |
+
module.bias.data.zero_()
|
456 |
+
module.weight.data.fill_(1.0)
|
457 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
458 |
+
module.bias.data.zero_()
|
459 |
+
|
460 |
+
|
461 |
+
CLIP_START_DOCSTRING = r"""
|
462 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
463 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
464 |
+
etc.)
|
465 |
+
|
466 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
467 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
468 |
+
and behavior.
|
469 |
+
|
470 |
+
Parameters:
|
471 |
+
config ([`CLIPConfig`]): 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 |
+
CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
477 |
+
Args:
|
478 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
479 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
480 |
+
it.
|
481 |
+
|
482 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
483 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
484 |
+
|
485 |
+
[What are input IDs?](../glossary#input-ids)
|
486 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
487 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
488 |
+
|
489 |
+
- 1 for tokens that are **not masked**,
|
490 |
+
- 0 for tokens that are **masked**.
|
491 |
+
|
492 |
+
[What are attention masks?](../glossary#attention-mask)
|
493 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
494 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
495 |
+
config.max_position_embeddings - 1]`.
|
496 |
+
|
497 |
+
[What are position IDs?](../glossary#position-ids)
|
498 |
+
output_attentions (`bool`, *optional*):
|
499 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
500 |
+
tensors for more detail.
|
501 |
+
output_hidden_states (`bool`, *optional*):
|
502 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
503 |
+
more detail.
|
504 |
+
return_dict (`bool`, *optional*):
|
505 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
506 |
+
"""
|
507 |
+
|
508 |
+
CLIP_VISION_INPUTS_DOCSTRING = r"""
|
509 |
+
Args:
|
510 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
511 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
512 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
513 |
+
output_attentions (`bool`, *optional*):
|
514 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
515 |
+
tensors for more detail.
|
516 |
+
output_hidden_states (`bool`, *optional*):
|
517 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
518 |
+
more detail.
|
519 |
+
return_dict (`bool`, *optional*):
|
520 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
521 |
+
"""
|
522 |
+
|
523 |
+
CLIP_INPUTS_DOCSTRING = r"""
|
524 |
+
Args:
|
525 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
526 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
527 |
+
it.
|
528 |
+
|
529 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
530 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
531 |
+
|
532 |
+
[What are input IDs?](../glossary#input-ids)
|
533 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
534 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
535 |
+
|
536 |
+
- 1 for tokens that are **not masked**,
|
537 |
+
- 0 for tokens that are **masked**.
|
538 |
+
|
539 |
+
[What are attention masks?](../glossary#attention-mask)
|
540 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
541 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
542 |
+
config.max_position_embeddings - 1]`.
|
543 |
+
|
544 |
+
[What are position IDs?](../glossary#position-ids)
|
545 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
546 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
547 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
548 |
+
return_loss (`bool`, *optional*):
|
549 |
+
Whether or not to return the contrastive loss.
|
550 |
+
output_attentions (`bool`, *optional*):
|
551 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
552 |
+
tensors for more detail.
|
553 |
+
output_hidden_states (`bool`, *optional*):
|
554 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
555 |
+
more detail.
|
556 |
+
return_dict (`bool`, *optional*):
|
557 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
558 |
+
"""
|
559 |
+
|
560 |
+
|
561 |
+
class CLIPEncoder(nn.Module):
|
562 |
+
"""
|
563 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
564 |
+
[`CLIPEncoderLayer`].
|
565 |
+
|
566 |
+
Args:
|
567 |
+
config: CLIPConfig
|
568 |
+
"""
|
569 |
+
|
570 |
+
def __init__(self, config: CLIPConfig):
|
571 |
+
super().__init__()
|
572 |
+
self.config = config
|
573 |
+
self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
574 |
+
self.gradient_checkpointing = False
|
575 |
+
|
576 |
+
def forward(
|
577 |
+
self,
|
578 |
+
inputs_embeds,
|
579 |
+
attention_mask: Optional[torch.Tensor] = None,
|
580 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
581 |
+
output_attentions: Optional[bool] = None,
|
582 |
+
output_hidden_states: Optional[bool] = None,
|
583 |
+
return_dict: Optional[bool] = None,
|
584 |
+
) -> Union[Tuple, BaseModelOutput]:
|
585 |
+
r"""
|
586 |
+
Args:
|
587 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
588 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
589 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
590 |
+
than the model's internal embedding lookup matrix.
|
591 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
592 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
593 |
+
|
594 |
+
- 1 for tokens that are **not masked**,
|
595 |
+
- 0 for tokens that are **masked**.
|
596 |
+
|
597 |
+
[What are attention masks?](../glossary#attention-mask)
|
598 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
599 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
600 |
+
|
601 |
+
- 1 for tokens that are **not masked**,
|
602 |
+
- 0 for tokens that are **masked**.
|
603 |
+
|
604 |
+
[What are attention masks?](../glossary#attention-mask)
|
605 |
+
output_attentions (`bool`, *optional*):
|
606 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
607 |
+
returned tensors for more detail.
|
608 |
+
output_hidden_states (`bool`, *optional*):
|
609 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
610 |
+
for more detail.
|
611 |
+
return_dict (`bool`, *optional*):
|
612 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
613 |
+
"""
|
614 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
615 |
+
output_hidden_states = (
|
616 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
617 |
+
)
|
618 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
619 |
+
|
620 |
+
encoder_states = () if output_hidden_states else None
|
621 |
+
all_attentions = () if output_attentions else None
|
622 |
+
|
623 |
+
hidden_states = inputs_embeds
|
624 |
+
for idx, encoder_layer in enumerate(self.layers):
|
625 |
+
if output_hidden_states:
|
626 |
+
encoder_states = encoder_states + (hidden_states,)
|
627 |
+
if self.gradient_checkpointing and self.training:
|
628 |
+
layer_outputs = self._gradient_checkpointing_func(
|
629 |
+
encoder_layer.__call__,
|
630 |
+
hidden_states,
|
631 |
+
attention_mask,
|
632 |
+
causal_attention_mask,
|
633 |
+
output_attentions,
|
634 |
+
)
|
635 |
+
else:
|
636 |
+
layer_outputs = encoder_layer(
|
637 |
+
hidden_states,
|
638 |
+
attention_mask,
|
639 |
+
causal_attention_mask,
|
640 |
+
output_attentions=output_attentions,
|
641 |
+
)
|
642 |
+
|
643 |
+
hidden_states = layer_outputs[0]
|
644 |
+
|
645 |
+
if output_attentions:
|
646 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
647 |
+
|
648 |
+
if output_hidden_states:
|
649 |
+
encoder_states = encoder_states + (hidden_states,)
|
650 |
+
|
651 |
+
if not return_dict:
|
652 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
653 |
+
return BaseModelOutput(
|
654 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
655 |
+
)
|
656 |
+
|
657 |
+
|
658 |
+
class CLIPTextTransformer(nn.Module):
|
659 |
+
def __init__(self, config: CLIPTextConfig):
|
660 |
+
super().__init__()
|
661 |
+
self.config = config
|
662 |
+
embed_dim = config.hidden_size
|
663 |
+
self.embeddings = CLIPTextEmbeddings(config)
|
664 |
+
self.encoder = CLIPEncoder(config)
|
665 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
666 |
+
|
667 |
+
# For `pooled_output` computation
|
668 |
+
self.eos_token_id = config.eos_token_id
|
669 |
+
|
670 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
671 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
|
672 |
+
def forward(
|
673 |
+
self,
|
674 |
+
input_ids: Optional[torch.Tensor] = None,
|
675 |
+
attention_mask: Optional[torch.Tensor] = None,
|
676 |
+
position_ids: Optional[torch.Tensor] = None,
|
677 |
+
output_attentions: Optional[bool] = None,
|
678 |
+
output_hidden_states: Optional[bool] = None,
|
679 |
+
return_dict: Optional[bool] = None,
|
680 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
681 |
+
r"""
|
682 |
+
Returns:
|
683 |
+
|
684 |
+
"""
|
685 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
686 |
+
output_hidden_states = (
|
687 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
688 |
+
)
|
689 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
690 |
+
|
691 |
+
if input_ids is None:
|
692 |
+
raise ValueError("You have to specify input_ids")
|
693 |
+
|
694 |
+
input_shape = input_ids.size()
|
695 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
696 |
+
|
697 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
698 |
+
|
699 |
+
# CLIP's text model uses causal mask, prepare it here.
|
700 |
+
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
|
701 |
+
causal_attention_mask = _create_4d_causal_attention_mask(
|
702 |
+
input_shape, hidden_states.dtype, device=hidden_states.device
|
703 |
+
)
|
704 |
+
# expand attention_mask
|
705 |
+
if attention_mask is not None:
|
706 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
707 |
+
attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
|
708 |
+
|
709 |
+
encoder_outputs = self.encoder(
|
710 |
+
inputs_embeds=hidden_states,
|
711 |
+
attention_mask=attention_mask,
|
712 |
+
causal_attention_mask=causal_attention_mask,
|
713 |
+
output_attentions=output_attentions,
|
714 |
+
output_hidden_states=output_hidden_states,
|
715 |
+
return_dict=return_dict,
|
716 |
+
)
|
717 |
+
|
718 |
+
last_hidden_state = encoder_outputs[0]
|
719 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
720 |
+
|
721 |
+
if self.eos_token_id == 2:
|
722 |
+
# The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
|
723 |
+
# A CLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added
|
724 |
+
# ------------------------------------------------------------
|
725 |
+
# text_embeds.shape = [batch_size, sequence_length, transformer.width]
|
726 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
727 |
+
# casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
|
728 |
+
pooled_output = last_hidden_state[
|
729 |
+
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
|
730 |
+
input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
|
731 |
+
]
|
732 |
+
else:
|
733 |
+
# The config gets updated `eos_token_id` from PR #24773 (so the use of exta new tokens is possible)
|
734 |
+
pooled_output = last_hidden_state[
|
735 |
+
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
|
736 |
+
# We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`)
|
737 |
+
(input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id)
|
738 |
+
.int()
|
739 |
+
.argmax(dim=-1),
|
740 |
+
]
|
741 |
+
|
742 |
+
if not return_dict:
|
743 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
744 |
+
|
745 |
+
return BaseModelOutputWithPooling(
|
746 |
+
last_hidden_state=last_hidden_state,
|
747 |
+
pooler_output=pooled_output,
|
748 |
+
hidden_states=encoder_outputs.hidden_states,
|
749 |
+
attentions=encoder_outputs.attentions,
|
750 |
+
)
|
751 |
+
|
752 |
+
|
753 |
+
@add_start_docstrings(
|
754 |
+
"""The text model from CLIP without any head or projection on top.""",
|
755 |
+
CLIP_START_DOCSTRING,
|
756 |
+
)
|
757 |
+
class CLIPTextModel(CLIPPreTrainedModel):
|
758 |
+
config_class = CLIPTextConfig
|
759 |
+
|
760 |
+
_no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
|
761 |
+
|
762 |
+
def __init__(self, config: CLIPTextConfig):
|
763 |
+
super().__init__(config)
|
764 |
+
self.text_model = CLIPTextTransformer(config)
|
765 |
+
# Initialize weights and apply final processing
|
766 |
+
self.post_init()
|
767 |
+
|
768 |
+
def get_input_embeddings(self) -> nn.Module:
|
769 |
+
return self.text_model.embeddings.token_embedding
|
770 |
+
|
771 |
+
def set_input_embeddings(self, value):
|
772 |
+
self.text_model.embeddings.token_embedding = value
|
773 |
+
|
774 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
775 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
|
776 |
+
def forward(
|
777 |
+
self,
|
778 |
+
input_ids: Optional[torch.Tensor] = None,
|
779 |
+
attention_mask: Optional[torch.Tensor] = None,
|
780 |
+
position_ids: Optional[torch.Tensor] = None,
|
781 |
+
output_attentions: Optional[bool] = None,
|
782 |
+
output_hidden_states: Optional[bool] = None,
|
783 |
+
return_dict: Optional[bool] = None,
|
784 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
785 |
+
r"""
|
786 |
+
Returns:
|
787 |
+
|
788 |
+
Examples:
|
789 |
+
|
790 |
+
```python
|
791 |
+
>>> from transformers import AutoTokenizer, CLIPTextModel
|
792 |
+
|
793 |
+
>>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
|
794 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
795 |
+
|
796 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
797 |
+
|
798 |
+
>>> outputs = model(**inputs)
|
799 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
800 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
801 |
+
```"""
|
802 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
803 |
+
|
804 |
+
return self.text_model(
|
805 |
+
input_ids=input_ids,
|
806 |
+
attention_mask=attention_mask,
|
807 |
+
position_ids=position_ids,
|
808 |
+
output_attentions=output_attentions,
|
809 |
+
output_hidden_states=output_hidden_states,
|
810 |
+
return_dict=return_dict,
|
811 |
+
)
|
812 |
+
|
813 |
+
|
814 |
+
class CLIPVisionTransformer(nn.Module):
|
815 |
+
def __init__(self, config: CLIPVisionConfig):
|
816 |
+
super().__init__()
|
817 |
+
self.config = config
|
818 |
+
embed_dim = config.hidden_size
|
819 |
+
|
820 |
+
self.embeddings = CLIPVisionEmbeddings(config)
|
821 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
822 |
+
self.encoder = CLIPEncoder(config)
|
823 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
824 |
+
|
825 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
826 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
|
827 |
+
def forward(
|
828 |
+
self,
|
829 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
830 |
+
output_attentions: Optional[bool] = None,
|
831 |
+
output_hidden_states: Optional[bool] = None,
|
832 |
+
return_dict: Optional[bool] = None,
|
833 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
834 |
+
r"""
|
835 |
+
Returns:
|
836 |
+
|
837 |
+
"""
|
838 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
839 |
+
output_hidden_states = (
|
840 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
841 |
+
)
|
842 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
843 |
+
|
844 |
+
if pixel_values is None:
|
845 |
+
raise ValueError("You have to specify pixel_values")
|
846 |
+
|
847 |
+
hidden_states = self.embeddings(pixel_values)
|
848 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
849 |
+
|
850 |
+
encoder_outputs = self.encoder(
|
851 |
+
inputs_embeds=hidden_states,
|
852 |
+
output_attentions=output_attentions,
|
853 |
+
output_hidden_states=output_hidden_states,
|
854 |
+
return_dict=return_dict,
|
855 |
+
)
|
856 |
+
|
857 |
+
last_hidden_state = encoder_outputs[0]
|
858 |
+
pooled_output = last_hidden_state[:, 0, :]
|
859 |
+
pooled_output = self.post_layernorm(pooled_output)
|
860 |
+
|
861 |
+
if not return_dict:
|
862 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
863 |
+
|
864 |
+
return BaseModelOutputWithPooling(
|
865 |
+
last_hidden_state=last_hidden_state,
|
866 |
+
pooler_output=pooled_output,
|
867 |
+
hidden_states=encoder_outputs.hidden_states,
|
868 |
+
attentions=encoder_outputs.attentions,
|
869 |
+
)
|
870 |
+
|
871 |
+
|
872 |
+
@add_start_docstrings(
|
873 |
+
"""The vision model from CLIP without any head or projection on top.""",
|
874 |
+
CLIP_START_DOCSTRING,
|
875 |
+
)
|
876 |
+
class CLIPVisionModel(CLIPPreTrainedModel):
|
877 |
+
config_class = CLIPVisionConfig
|
878 |
+
main_input_name = "pixel_values"
|
879 |
+
_no_split_modules = ["CLIPEncoderLayer"]
|
880 |
+
|
881 |
+
def __init__(self, config: CLIPVisionConfig):
|
882 |
+
super().__init__(config)
|
883 |
+
self.vision_model = CLIPVisionTransformer(config)
|
884 |
+
# Initialize weights and apply final processing
|
885 |
+
self.post_init()
|
886 |
+
|
887 |
+
def get_input_embeddings(self) -> nn.Module:
|
888 |
+
return self.vision_model.embeddings.patch_embedding
|
889 |
+
|
890 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
891 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
|
892 |
+
def forward(
|
893 |
+
self,
|
894 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
895 |
+
output_attentions: Optional[bool] = None,
|
896 |
+
output_hidden_states: Optional[bool] = None,
|
897 |
+
return_dict: Optional[bool] = None,
|
898 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
899 |
+
r"""
|
900 |
+
Returns:
|
901 |
+
|
902 |
+
Examples:
|
903 |
+
|
904 |
+
```python
|
905 |
+
>>> from PIL import Image
|
906 |
+
>>> import requests
|
907 |
+
>>> from transformers import AutoProcessor, CLIPVisionModel
|
908 |
+
|
909 |
+
>>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
|
910 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
911 |
+
|
912 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
913 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
914 |
+
|
915 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
916 |
+
|
917 |
+
>>> outputs = model(**inputs)
|
918 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
919 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
920 |
+
```"""
|
921 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
922 |
+
|
923 |
+
return self.vision_model(
|
924 |
+
pixel_values=pixel_values,
|
925 |
+
output_attentions=output_attentions,
|
926 |
+
output_hidden_states=output_hidden_states,
|
927 |
+
return_dict=return_dict,
|
928 |
+
)
|
929 |
+
|
930 |
+
|
931 |
+
@add_start_docstrings(CLIP_START_DOCSTRING)
|
932 |
+
class CLIPModel(CLIPPreTrainedModel):
|
933 |
+
config_class = CLIPConfig
|
934 |
+
_no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
|
935 |
+
|
936 |
+
def __init__(self, config: CLIPConfig):
|
937 |
+
super().__init__(config)
|
938 |
+
|
939 |
+
if not isinstance(config.text_config, CLIPTextConfig):
|
940 |
+
raise ValueError(
|
941 |
+
"config.text_config is expected to be of type CLIPTextConfig but is of type"
|
942 |
+
f" {type(config.text_config)}."
|
943 |
+
)
|
944 |
+
|
945 |
+
if not isinstance(config.vision_config, CLIPVisionConfig):
|
946 |
+
raise ValueError(
|
947 |
+
"config.vision_config is expected to be of type CLIPVisionConfig but is of type"
|
948 |
+
f" {type(config.vision_config)}."
|
949 |
+
)
|
950 |
+
|
951 |
+
text_config = config.text_config
|
952 |
+
vision_config = config.vision_config
|
953 |
+
|
954 |
+
self.projection_dim = config.projection_dim
|
955 |
+
self.text_embed_dim = text_config.hidden_size
|
956 |
+
self.vision_embed_dim = vision_config.hidden_size
|
957 |
+
|
958 |
+
self.text_model = CLIPTextTransformer(text_config)
|
959 |
+
self.vision_model = CLIPVisionTransformer(vision_config)
|
960 |
+
|
961 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
962 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
963 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
964 |
+
|
965 |
+
# Initialize weights and apply final processing
|
966 |
+
self.post_init()
|
967 |
+
|
968 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
969 |
+
def get_text_features(
|
970 |
+
self,
|
971 |
+
input_ids: Optional[torch.Tensor] = None,
|
972 |
+
attention_mask: Optional[torch.Tensor] = None,
|
973 |
+
position_ids: Optional[torch.Tensor] = None,
|
974 |
+
output_attentions: Optional[bool] = None,
|
975 |
+
output_hidden_states: Optional[bool] = None,
|
976 |
+
return_dict: Optional[bool] = None,
|
977 |
+
) -> torch.FloatTensor:
|
978 |
+
r"""
|
979 |
+
Returns:
|
980 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
981 |
+
applying the projection layer to the pooled output of [`CLIPTextModel`].
|
982 |
+
|
983 |
+
Examples:
|
984 |
+
|
985 |
+
```python
|
986 |
+
>>> from transformers import AutoTokenizer, CLIPModel
|
987 |
+
|
988 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
989 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
990 |
+
|
991 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
992 |
+
>>> text_features = model.get_text_features(**inputs)
|
993 |
+
```"""
|
994 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
995 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
996 |
+
output_hidden_states = (
|
997 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
998 |
+
)
|
999 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1000 |
+
|
1001 |
+
text_outputs = self.text_model(
|
1002 |
+
input_ids=input_ids,
|
1003 |
+
attention_mask=attention_mask,
|
1004 |
+
position_ids=position_ids,
|
1005 |
+
output_attentions=output_attentions,
|
1006 |
+
output_hidden_states=output_hidden_states,
|
1007 |
+
return_dict=return_dict,
|
1008 |
+
)
|
1009 |
+
|
1010 |
+
pooled_output = text_outputs[1]
|
1011 |
+
text_features = self.text_projection(pooled_output)
|
1012 |
+
|
1013 |
+
return text_features
|
1014 |
+
|
1015 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
1016 |
+
def get_image_features(
|
1017 |
+
self,
|
1018 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1019 |
+
output_attentions: Optional[bool] = None,
|
1020 |
+
output_hidden_states: Optional[bool] = None,
|
1021 |
+
return_dict: Optional[bool] = None,
|
1022 |
+
) -> torch.FloatTensor:
|
1023 |
+
r"""
|
1024 |
+
Returns:
|
1025 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
1026 |
+
applying the projection layer to the pooled output of [`CLIPVisionModel`].
|
1027 |
+
|
1028 |
+
Examples:
|
1029 |
+
|
1030 |
+
```python
|
1031 |
+
>>> from PIL import Image
|
1032 |
+
>>> import requests
|
1033 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
1034 |
+
|
1035 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1036 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1037 |
+
|
1038 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1039 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1040 |
+
|
1041 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
1042 |
+
|
1043 |
+
>>> image_features = model.get_image_features(**inputs)
|
1044 |
+
```"""
|
1045 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1046 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1047 |
+
output_hidden_states = (
|
1048 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1049 |
+
)
|
1050 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1051 |
+
|
1052 |
+
vision_outputs = self.vision_model(
|
1053 |
+
pixel_values=pixel_values,
|
1054 |
+
output_attentions=output_attentions,
|
1055 |
+
output_hidden_states=output_hidden_states,
|
1056 |
+
return_dict=return_dict,
|
1057 |
+
)
|
1058 |
+
|
1059 |
+
pooled_output = vision_outputs[1] # pooled_output
|
1060 |
+
image_features = self.visual_projection(pooled_output)
|
1061 |
+
|
1062 |
+
return image_features
|
1063 |
+
|
1064 |
+
@add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING)
|
1065 |
+
@replace_return_docstrings(output_type=CLIPOutput, config_class=CLIPConfig)
|
1066 |
+
def forward(
|
1067 |
+
self,
|
1068 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1069 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1070 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1071 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1072 |
+
return_loss: Optional[bool] = None,
|
1073 |
+
output_attentions: Optional[bool] = None,
|
1074 |
+
output_hidden_states: Optional[bool] = None,
|
1075 |
+
return_dict: Optional[bool] = None,
|
1076 |
+
) -> Union[Tuple, CLIPOutput]:
|
1077 |
+
r"""
|
1078 |
+
Returns:
|
1079 |
+
|
1080 |
+
Examples:
|
1081 |
+
|
1082 |
+
```python
|
1083 |
+
>>> from PIL import Image
|
1084 |
+
>>> import requests
|
1085 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
1086 |
+
|
1087 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1088 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1089 |
+
|
1090 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1091 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1092 |
+
|
1093 |
+
>>> inputs = processor(
|
1094 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
1095 |
+
... )
|
1096 |
+
|
1097 |
+
>>> outputs = model(**inputs)
|
1098 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
1099 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
1100 |
+
```"""
|
1101 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
1102 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1103 |
+
output_hidden_states = (
|
1104 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1105 |
+
)
|
1106 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1107 |
+
|
1108 |
+
vision_outputs = self.vision_model(
|
1109 |
+
pixel_values=pixel_values,
|
1110 |
+
output_attentions=output_attentions,
|
1111 |
+
output_hidden_states=output_hidden_states,
|
1112 |
+
return_dict=return_dict,
|
1113 |
+
)
|
1114 |
+
|
1115 |
+
text_outputs = self.text_model(
|
1116 |
+
input_ids=input_ids,
|
1117 |
+
attention_mask=attention_mask,
|
1118 |
+
position_ids=position_ids,
|
1119 |
+
output_attentions=output_attentions,
|
1120 |
+
output_hidden_states=output_hidden_states,
|
1121 |
+
return_dict=return_dict,
|
1122 |
+
)
|
1123 |
+
|
1124 |
+
image_embeds = vision_outputs[1]
|
1125 |
+
image_embeds = self.visual_projection(image_embeds)
|
1126 |
+
|
1127 |
+
text_embeds = text_outputs[1]
|
1128 |
+
text_embeds = self.text_projection(text_embeds)
|
1129 |
+
|
1130 |
+
# normalized features
|
1131 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
1132 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
1133 |
+
|
1134 |
+
# cosine similarity as logits
|
1135 |
+
logit_scale = self.logit_scale.exp()
|
1136 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
1137 |
+
logits_per_image = logits_per_text.t()
|
1138 |
+
|
1139 |
+
loss = None
|
1140 |
+
if return_loss:
|
1141 |
+
loss = clip_loss(logits_per_text)
|
1142 |
+
|
1143 |
+
if not return_dict:
|
1144 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
1145 |
+
return ((loss,) + output) if loss is not None else output
|
1146 |
+
|
1147 |
+
return CLIPOutput(
|
1148 |
+
loss=loss,
|
1149 |
+
logits_per_image=logits_per_image,
|
1150 |
+
logits_per_text=logits_per_text,
|
1151 |
+
text_embeds=text_embeds,
|
1152 |
+
image_embeds=image_embeds,
|
1153 |
+
text_model_output=text_outputs,
|
1154 |
+
vision_model_output=vision_outputs,
|
1155 |
+
)
|
1156 |
+
|
1157 |
+
|
1158 |
+
@add_start_docstrings(
|
1159 |
+
"""
|
1160 |
+
CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output).
|
1161 |
+
""",
|
1162 |
+
CLIP_START_DOCSTRING,
|
1163 |
+
)
|
1164 |
+
class CLIPTextModelWithProjection(CLIPPreTrainedModel):
|
1165 |
+
config_class = CLIPTextConfig
|
1166 |
+
|
1167 |
+
_no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
|
1168 |
+
|
1169 |
+
def __init__(self, config: CLIPTextConfig):
|
1170 |
+
super().__init__(config)
|
1171 |
+
|
1172 |
+
self.text_model = CLIPTextTransformer(config)
|
1173 |
+
|
1174 |
+
self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
1175 |
+
|
1176 |
+
# Initialize weights and apply final processing
|
1177 |
+
self.post_init()
|
1178 |
+
|
1179 |
+
def get_input_embeddings(self) -> nn.Module:
|
1180 |
+
return self.text_model.embeddings.token_embedding
|
1181 |
+
|
1182 |
+
def set_input_embeddings(self, value):
|
1183 |
+
self.text_model.embeddings.token_embedding = value
|
1184 |
+
|
1185 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
1186 |
+
@replace_return_docstrings(output_type=CLIPTextModelOutput, config_class=CLIPTextConfig)
|
1187 |
+
def forward(
|
1188 |
+
self,
|
1189 |
+
input_ids: Optional[torch.Tensor] = None,
|
1190 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1191 |
+
position_ids: Optional[torch.Tensor] = None,
|
1192 |
+
output_attentions: Optional[bool] = None,
|
1193 |
+
output_hidden_states: Optional[bool] = None,
|
1194 |
+
return_dict: Optional[bool] = None,
|
1195 |
+
) -> Union[Tuple, CLIPTextModelOutput]:
|
1196 |
+
r"""
|
1197 |
+
Returns:
|
1198 |
+
|
1199 |
+
Examples:
|
1200 |
+
|
1201 |
+
```python
|
1202 |
+
>>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
|
1203 |
+
|
1204 |
+
>>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
1205 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
1206 |
+
|
1207 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
1208 |
+
|
1209 |
+
>>> outputs = model(**inputs)
|
1210 |
+
>>> text_embeds = outputs.text_embeds
|
1211 |
+
```"""
|
1212 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1213 |
+
|
1214 |
+
text_outputs = self.text_model(
|
1215 |
+
input_ids=input_ids,
|
1216 |
+
attention_mask=attention_mask,
|
1217 |
+
position_ids=position_ids,
|
1218 |
+
output_attentions=output_attentions,
|
1219 |
+
output_hidden_states=output_hidden_states,
|
1220 |
+
return_dict=return_dict,
|
1221 |
+
)
|
1222 |
+
|
1223 |
+
pooled_output = text_outputs[1]
|
1224 |
+
|
1225 |
+
text_embeds = self.text_projection(pooled_output)
|
1226 |
+
|
1227 |
+
if not return_dict:
|
1228 |
+
outputs = (text_embeds, text_outputs[0]) + text_outputs[2:]
|
1229 |
+
return tuple(output for output in outputs if output is not None)
|
1230 |
+
|
1231 |
+
return CLIPTextModelOutput(
|
1232 |
+
text_embeds=text_embeds,
|
1233 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
1234 |
+
hidden_states=text_outputs.hidden_states,
|
1235 |
+
attentions=text_outputs.attentions,
|
1236 |
+
)
|
1237 |
+
|
1238 |
+
|
1239 |
+
@add_start_docstrings(
|
1240 |
+
"""
|
1241 |
+
CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output).
|
1242 |
+
""",
|
1243 |
+
CLIP_START_DOCSTRING,
|
1244 |
+
)
|
1245 |
+
class CLIPVisionModelWithProjection(CLIPPreTrainedModel):
|
1246 |
+
config_class = CLIPVisionConfig
|
1247 |
+
main_input_name = "pixel_values"
|
1248 |
+
|
1249 |
+
def __init__(self, config: CLIPVisionConfig):
|
1250 |
+
super().__init__(config)
|
1251 |
+
|
1252 |
+
self.vision_model = CLIPVisionTransformer(config)
|
1253 |
+
|
1254 |
+
self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
1255 |
+
|
1256 |
+
# Initialize weights and apply final processing
|
1257 |
+
self.post_init()
|
1258 |
+
|
1259 |
+
def get_input_embeddings(self) -> nn.Module:
|
1260 |
+
return self.vision_model.embeddings.patch_embedding
|
1261 |
+
|
1262 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
1263 |
+
@replace_return_docstrings(output_type=CLIPVisionModelOutput, config_class=CLIPVisionConfig)
|
1264 |
+
def forward(
|
1265 |
+
self,
|
1266 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
1267 |
+
output_attentions: Optional[bool] = None,
|
1268 |
+
output_hidden_states: Optional[bool] = None,
|
1269 |
+
return_dict: Optional[bool] = None,
|
1270 |
+
) -> Union[Tuple, CLIPVisionModelOutput]:
|
1271 |
+
r"""
|
1272 |
+
Returns:
|
1273 |
+
|
1274 |
+
Examples:
|
1275 |
+
|
1276 |
+
```python
|
1277 |
+
>>> from PIL import Image
|
1278 |
+
>>> import requests
|
1279 |
+
>>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
|
1280 |
+
|
1281 |
+
>>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
1282 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1283 |
+
|
1284 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1285 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1286 |
+
|
1287 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
1288 |
+
|
1289 |
+
>>> outputs = model(**inputs)
|
1290 |
+
>>> image_embeds = outputs.image_embeds
|
1291 |
+
```"""
|
1292 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1293 |
+
|
1294 |
+
vision_outputs = self.vision_model(
|
1295 |
+
pixel_values=pixel_values,
|
1296 |
+
output_attentions=output_attentions,
|
1297 |
+
output_hidden_states=output_hidden_states,
|
1298 |
+
return_dict=return_dict,
|
1299 |
+
)
|
1300 |
+
|
1301 |
+
pooled_output = vision_outputs[1] # pooled_output
|
1302 |
+
|
1303 |
+
image_embeds = self.visual_projection(pooled_output)
|
1304 |
+
|
1305 |
+
if not return_dict:
|
1306 |
+
outputs = (image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
1307 |
+
return tuple(output for output in outputs if output is not None)
|
1308 |
+
|
1309 |
+
return CLIPVisionModelOutput(
|
1310 |
+
image_embeds=image_embeds,
|
1311 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
1312 |
+
hidden_states=vision_outputs.hidden_states,
|
1313 |
+
attentions=vision_outputs.attentions,
|
1314 |
+
)
|
1315 |
+
|
1316 |
+
|
1317 |
+
@add_start_docstrings(
|
1318 |
+
"""
|
1319 |
+
CLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
|
1320 |
+
the patch tokens) e.g. for ImageNet.
|
1321 |
+
""",
|
1322 |
+
CLIP_START_DOCSTRING,
|
1323 |
+
)
|
1324 |
+
class CLIPForImageClassification(CLIPPreTrainedModel):
|
1325 |
+
main_input_name = "pixel_values"
|
1326 |
+
|
1327 |
+
def __init__(self, config: CLIPConfig) -> None:
|
1328 |
+
super().__init__(config)
|
1329 |
+
|
1330 |
+
self.num_labels = config.num_labels
|
1331 |
+
self.vision_model = CLIPVisionTransformer(config.vision_config)
|
1332 |
+
|
1333 |
+
# Classifier head
|
1334 |
+
self.classifier = (
|
1335 |
+
nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
1336 |
+
)
|
1337 |
+
|
1338 |
+
# Initialize weights and apply final processing
|
1339 |
+
self.post_init()
|
1340 |
+
|
1341 |
+
@add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING)
|
1342 |
+
@add_code_sample_docstrings(
|
1343 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
1344 |
+
output_type=ImageClassifierOutput,
|
1345 |
+
config_class=_CONFIG_FOR_DOC,
|
1346 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
1347 |
+
)
|
1348 |
+
def forward(
|
1349 |
+
self,
|
1350 |
+
pixel_values: Optional[torch.Tensor] = None,
|
1351 |
+
labels: Optional[torch.Tensor] = None,
|
1352 |
+
output_attentions: Optional[bool] = None,
|
1353 |
+
output_hidden_states: Optional[bool] = None,
|
1354 |
+
return_dict: Optional[bool] = None,
|
1355 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
1356 |
+
r"""
|
1357 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1358 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
1359 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1360 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1361 |
+
"""
|
1362 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1363 |
+
output_hidden_states = (
|
1364 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1365 |
+
)
|
1366 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1367 |
+
|
1368 |
+
outputs = self.vision_model(
|
1369 |
+
pixel_values,
|
1370 |
+
output_attentions=output_attentions,
|
1371 |
+
output_hidden_states=output_hidden_states,
|
1372 |
+
return_dict=return_dict,
|
1373 |
+
)
|
1374 |
+
|
1375 |
+
sequence_output = outputs[0]
|
1376 |
+
|
1377 |
+
# average pool the patch tokens
|
1378 |
+
sequence_output = torch.mean(sequence_output[:, 1:, :], dim=1)
|
1379 |
+
# apply classifier
|
1380 |
+
logits = self.classifier(sequence_output)
|
1381 |
+
|
1382 |
+
loss = None
|
1383 |
+
if labels is not None:
|
1384 |
+
# move labels to correct device to enable model parallelism
|
1385 |
+
labels = labels.to(logits.device)
|
1386 |
+
if self.config.problem_type is None:
|
1387 |
+
if self.num_labels == 1:
|
1388 |
+
self.config.problem_type = "regression"
|
1389 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1390 |
+
self.config.problem_type = "single_label_classification"
|
1391 |
+
else:
|
1392 |
+
self.config.problem_type = "multi_label_classification"
|
1393 |
+
|
1394 |
+
if self.config.problem_type == "regression":
|
1395 |
+
loss_fct = MSELoss()
|
1396 |
+
if self.num_labels == 1:
|
1397 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
1398 |
+
else:
|
1399 |
+
loss = loss_fct(logits, labels)
|
1400 |
+
elif self.config.problem_type == "single_label_classification":
|
1401 |
+
loss_fct = CrossEntropyLoss()
|
1402 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1403 |
+
elif self.config.problem_type == "multi_label_classification":
|
1404 |
+
loss_fct = BCEWithLogitsLoss()
|
1405 |
+
loss = loss_fct(logits, labels)
|
1406 |
+
|
1407 |
+
if not return_dict:
|
1408 |
+
output = (logits,) + outputs[2:]
|
1409 |
+
return ((loss,) + output) if loss is not None else output
|
1410 |
+
|
1411 |
+
return ImageClassifierOutput(
|
1412 |
+
loss=loss,
|
1413 |
+
logits=logits,
|
1414 |
+
hidden_states=outputs.hidden_states,
|
1415 |
+
attentions=outputs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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The OpenAI Team Authors, The Google Flax Team 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 |
+
|
16 |
+
from typing import Any, Optional, Tuple, Union
|
17 |
+
|
18 |
+
import flax
|
19 |
+
import flax.linen as nn
|
20 |
+
import jax
|
21 |
+
import jax.numpy as jnp
|
22 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
23 |
+
from flax.linen import combine_masks, make_causal_mask
|
24 |
+
from flax.linen.attention import dot_product_attention_weights
|
25 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
26 |
+
from jax import lax
|
27 |
+
|
28 |
+
from ...modeling_flax_outputs import FlaxBaseModelOutput, FlaxBaseModelOutputWithPooling
|
29 |
+
from ...modeling_flax_utils import (
|
30 |
+
ACT2FN,
|
31 |
+
FlaxPreTrainedModel,
|
32 |
+
append_replace_return_docstrings,
|
33 |
+
overwrite_call_docstring,
|
34 |
+
)
|
35 |
+
from ...utils import ModelOutput, add_start_docstrings, logging
|
36 |
+
from .configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
|
37 |
+
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
CLIP_START_DOCSTRING = r"""
|
42 |
+
|
43 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
44 |
+
library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
|
45 |
+
|
46 |
+
This model is also a
|
47 |
+
[flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
|
48 |
+
a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
|
49 |
+
behavior.
|
50 |
+
|
51 |
+
Finally, this model supports inherent JAX features such as:
|
52 |
+
|
53 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
54 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
55 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
56 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
57 |
+
|
58 |
+
Parameters:
|
59 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
60 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
61 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
62 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
63 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
64 |
+
`jax.numpy.bfloat16` (on TPUs).
|
65 |
+
|
66 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
67 |
+
specified all the computation will be performed with the given `dtype`.
|
68 |
+
|
69 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
70 |
+
parameters.**
|
71 |
+
|
72 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
73 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
74 |
+
"""
|
75 |
+
|
76 |
+
CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
77 |
+
Args:
|
78 |
+
input_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`):
|
79 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
80 |
+
it.
|
81 |
+
|
82 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
83 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
84 |
+
|
85 |
+
[What are input IDs?](../glossary#input-ids)
|
86 |
+
attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
87 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
88 |
+
|
89 |
+
- 1 for tokens that are **not masked**,
|
90 |
+
- 0 for tokens that are **masked**.
|
91 |
+
|
92 |
+
[What are attention masks?](../glossary#attention-mask)
|
93 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
94 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
95 |
+
config.max_position_embeddings - 1]`.
|
96 |
+
|
97 |
+
[What are position IDs?](../glossary#position-ids)
|
98 |
+
output_attentions (`bool`, *optional*):
|
99 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
100 |
+
tensors for more detail.
|
101 |
+
output_hidden_states (`bool`, *optional*):
|
102 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
103 |
+
more detail.
|
104 |
+
return_dict (`bool`, *optional*):
|
105 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
106 |
+
"""
|
107 |
+
|
108 |
+
CLIP_VISION_INPUTS_DOCSTRING = r"""
|
109 |
+
Args:
|
110 |
+
pixel_values (`numpy.ndarray` of shape `(batch_size, num_channels, height, width)`):
|
111 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
112 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
113 |
+
output_attentions (`bool`, *optional*):
|
114 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
115 |
+
tensors for more detail.
|
116 |
+
output_hidden_states (`bool`, *optional*):
|
117 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
118 |
+
more detail.
|
119 |
+
return_dict (`bool`, *optional*):
|
120 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
121 |
+
"""
|
122 |
+
|
123 |
+
CLIP_INPUTS_DOCSTRING = r"""
|
124 |
+
Args:
|
125 |
+
input_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`):
|
126 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
127 |
+
it.
|
128 |
+
|
129 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
130 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
131 |
+
|
132 |
+
[What are input IDs?](../glossary#input-ids)
|
133 |
+
attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
134 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
135 |
+
|
136 |
+
- 1 for tokens that are **not masked**,
|
137 |
+
- 0 for tokens that are **masked**.
|
138 |
+
|
139 |
+
[What are attention masks?](../glossary#attention-mask)
|
140 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
141 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
142 |
+
config.max_position_embeddings - 1]`.
|
143 |
+
|
144 |
+
[What are position IDs?](../glossary#position-ids)
|
145 |
+
pixel_values (`numpy.ndarray` of shape `(batch_size, num_channels, height, width)`):
|
146 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
147 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
148 |
+
output_attentions (`bool`, *optional*):
|
149 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
150 |
+
tensors for more detail.
|
151 |
+
output_hidden_states (`bool`, *optional*):
|
152 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
153 |
+
more detail.
|
154 |
+
return_dict (`bool`, *optional*):
|
155 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
156 |
+
"""
|
157 |
+
|
158 |
+
|
159 |
+
@flax.struct.dataclass
|
160 |
+
class FlaxCLIPTextModelOutput(ModelOutput):
|
161 |
+
"""
|
162 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
163 |
+
|
164 |
+
Args:
|
165 |
+
text_embeds (`jnp.ndarray` of shape `(batch_size, output_dim`):
|
166 |
+
The text embeddings obtained by applying the projection layer to the pooled output of
|
167 |
+
[`FlaxCLIPTextModel`].
|
168 |
+
last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`):
|
169 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
170 |
+
hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
171 |
+
Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
|
172 |
+
`(batch_size, sequence_length, hidden_size)`.
|
173 |
+
|
174 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
175 |
+
attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
176 |
+
Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
177 |
+
sequence_length)`.
|
178 |
+
|
179 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
180 |
+
heads.
|
181 |
+
"""
|
182 |
+
|
183 |
+
text_embeds: jnp.ndarray = None
|
184 |
+
last_hidden_state: jnp.ndarray = None
|
185 |
+
hidden_states: Optional[Tuple[jnp.ndarray, ...]] = None
|
186 |
+
attentions: Optional[Tuple[jnp.ndarray, ...]] = None
|
187 |
+
|
188 |
+
|
189 |
+
@flax.struct.dataclass
|
190 |
+
class FlaxCLIPOutput(ModelOutput):
|
191 |
+
"""
|
192 |
+
Args:
|
193 |
+
logits_per_image:(`jnp.ndarray` of shape `(image_batch_size, text_batch_size)`):
|
194 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
195 |
+
similarity scores.
|
196 |
+
logits_per_text:(`jnp.ndarray` of shape `(text_batch_size, image_batch_size)`):
|
197 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
198 |
+
similarity scores.
|
199 |
+
text_embeds(`jnp.ndarray` of shape `(batch_size, output_dim`):
|
200 |
+
The text embeddings obtained by applying the projection layer to the pooled output of
|
201 |
+
[`FlaxCLIPTextModel`].
|
202 |
+
image_embeds(`jnp.ndarray` of shape `(batch_size, output_dim`):
|
203 |
+
The image embeddings obtained by applying the projection layer to the pooled output of
|
204 |
+
[`FlaxCLIPVisionModel`].
|
205 |
+
text_model_output(`FlaxBaseModelOutputWithPooling`):
|
206 |
+
The output of the [`FlaxCLIPTextModel`].
|
207 |
+
vision_model_output(`FlaxBaseModelOutputWithPooling`):
|
208 |
+
The output of the [`FlaxCLIPVisionModel`].
|
209 |
+
"""
|
210 |
+
|
211 |
+
logits_per_image: jnp.ndarray = None
|
212 |
+
logits_per_text: jnp.ndarray = None
|
213 |
+
text_embeds: jnp.ndarray = None
|
214 |
+
image_embeds: jnp.ndarray = None
|
215 |
+
text_model_output: FlaxBaseModelOutputWithPooling = None
|
216 |
+
vision_model_output: FlaxBaseModelOutputWithPooling = None
|
217 |
+
|
218 |
+
def to_tuple(self) -> Tuple[Any]:
|
219 |
+
return tuple(
|
220 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
221 |
+
for k in self.keys()
|
222 |
+
)
|
223 |
+
|
224 |
+
|
225 |
+
class FlaxCLIPVisionEmbeddings(nn.Module):
|
226 |
+
config: CLIPVisionConfig
|
227 |
+
dtype: jnp.dtype = jnp.float32
|
228 |
+
|
229 |
+
def setup(self):
|
230 |
+
embed_dim = self.config.hidden_size
|
231 |
+
image_size = self.config.image_size
|
232 |
+
patch_size = self.config.patch_size
|
233 |
+
|
234 |
+
self.class_embedding = self.param("class_embedding", jax.nn.initializers.normal(stddev=0.02), (embed_dim,))
|
235 |
+
|
236 |
+
self.patch_embedding = nn.Conv(
|
237 |
+
embed_dim,
|
238 |
+
kernel_size=(patch_size, patch_size),
|
239 |
+
strides=(patch_size, patch_size),
|
240 |
+
padding="VALID",
|
241 |
+
use_bias=False,
|
242 |
+
dtype=self.dtype,
|
243 |
+
kernel_init=jax.nn.initializers.normal(),
|
244 |
+
)
|
245 |
+
|
246 |
+
self.num_patches = (image_size // patch_size) ** 2
|
247 |
+
num_positions = self.num_patches + 1
|
248 |
+
self.position_embedding = nn.Embed(num_positions, embed_dim, embedding_init=jax.nn.initializers.normal())
|
249 |
+
self.position_ids = jnp.expand_dims(jnp.arange(0, num_positions, dtype="i4"), axis=0)
|
250 |
+
|
251 |
+
def __call__(self, pixel_values):
|
252 |
+
patch_embeds = self.patch_embedding(pixel_values)
|
253 |
+
batch_size, height, width, channels = patch_embeds.shape
|
254 |
+
patch_embeds = jnp.reshape(patch_embeds, (batch_size, height * width, channels))
|
255 |
+
|
256 |
+
class_embeds = jnp.expand_dims(self.class_embedding, axis=(0, 1))
|
257 |
+
class_embeds = jnp.tile(class_embeds, (batch_size, 1, 1))
|
258 |
+
embeddings = jnp.concatenate([class_embeds, patch_embeds], axis=1)
|
259 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
260 |
+
return embeddings
|
261 |
+
|
262 |
+
|
263 |
+
class FlaxCLIPTextEmbeddings(nn.Module):
|
264 |
+
config: CLIPTextConfig
|
265 |
+
dtype: jnp.dtype = jnp.float32
|
266 |
+
|
267 |
+
def setup(self):
|
268 |
+
embed_dim = self.config.hidden_size
|
269 |
+
|
270 |
+
self.token_embedding = nn.Embed(self.config.vocab_size, embed_dim, embedding_init=jax.nn.initializers.normal())
|
271 |
+
self.position_embedding = nn.Embed(
|
272 |
+
self.config.max_position_embeddings, embed_dim, embedding_init=jax.nn.initializers.normal()
|
273 |
+
)
|
274 |
+
self.position_ids = jnp.expand_dims(
|
275 |
+
jnp.arange(0, self.config.max_position_embeddings, dtype="i4"), axis=(0, 1)
|
276 |
+
)
|
277 |
+
|
278 |
+
def __call__(self, input_ids, position_ids):
|
279 |
+
input_embeds = self.token_embedding(input_ids.astype("i4"))
|
280 |
+
position_embeds = self.position_embedding(position_ids.astype("i4"))
|
281 |
+
|
282 |
+
embeddings = input_embeds + position_embeds
|
283 |
+
return embeddings
|
284 |
+
|
285 |
+
|
286 |
+
class FlaxCLIPAttention(nn.Module):
|
287 |
+
config: Union[CLIPTextConfig, CLIPVisionConfig]
|
288 |
+
dtype: jnp.dtype = jnp.float32
|
289 |
+
|
290 |
+
def setup(self):
|
291 |
+
self.embed_dim = self.config.hidden_size
|
292 |
+
self.num_heads = self.config.num_attention_heads
|
293 |
+
self.head_dim = self.embed_dim // self.num_heads
|
294 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
295 |
+
raise ValueError(
|
296 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
297 |
+
f" {self.num_heads})."
|
298 |
+
)
|
299 |
+
self.scale = self.head_dim**-0.5
|
300 |
+
self.dropout = self.config.attention_dropout
|
301 |
+
|
302 |
+
self.k_proj = nn.Dense(self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(0.01))
|
303 |
+
self.v_proj = nn.Dense(self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(0.01))
|
304 |
+
self.q_proj = nn.Dense(self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(0.01))
|
305 |
+
self.out_proj = nn.Dense(self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(0.01))
|
306 |
+
|
307 |
+
self.causal = isinstance(self.config, CLIPTextConfig)
|
308 |
+
if self.causal:
|
309 |
+
self.causal_mask = make_causal_mask(jnp.ones((1, self.config.max_position_embeddings), dtype="i4"))
|
310 |
+
|
311 |
+
def _split_heads(self, hidden_states):
|
312 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
|
313 |
+
|
314 |
+
def _merge_heads(self, hidden_states):
|
315 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
|
316 |
+
|
317 |
+
def __call__(
|
318 |
+
self,
|
319 |
+
hidden_states,
|
320 |
+
attention_mask=None,
|
321 |
+
deterministic: bool = True,
|
322 |
+
output_attentions: bool = False,
|
323 |
+
):
|
324 |
+
query = self.q_proj(hidden_states)
|
325 |
+
key = self.k_proj(hidden_states)
|
326 |
+
value = self.v_proj(hidden_states)
|
327 |
+
|
328 |
+
query = self._split_heads(query)
|
329 |
+
key = self._split_heads(key)
|
330 |
+
value = self._split_heads(value)
|
331 |
+
|
332 |
+
causal_attention_mask = None
|
333 |
+
if self.causal:
|
334 |
+
query_length, key_length = query.shape[1], key.shape[1]
|
335 |
+
causal_attention_mask = self.causal_mask[:, :, key_length - query_length : key_length, :key_length]
|
336 |
+
|
337 |
+
if attention_mask is not None and causal_attention_mask is not None:
|
338 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
339 |
+
attention_mask = combine_masks(attention_mask, causal_attention_mask, dtype="i4")
|
340 |
+
elif causal_attention_mask is not None:
|
341 |
+
attention_mask = causal_attention_mask
|
342 |
+
elif attention_mask is not None:
|
343 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
344 |
+
|
345 |
+
if attention_mask is not None:
|
346 |
+
attention_bias = lax.select(
|
347 |
+
attention_mask > 0,
|
348 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
349 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
350 |
+
)
|
351 |
+
else:
|
352 |
+
attention_bias = None
|
353 |
+
|
354 |
+
dropout_rng = None
|
355 |
+
if not deterministic and self.dropout > 0.0:
|
356 |
+
dropout_rng = self.make_rng("dropout")
|
357 |
+
|
358 |
+
attn_weights = dot_product_attention_weights(
|
359 |
+
query,
|
360 |
+
key,
|
361 |
+
bias=attention_bias,
|
362 |
+
dropout_rng=dropout_rng,
|
363 |
+
dropout_rate=self.dropout,
|
364 |
+
deterministic=deterministic,
|
365 |
+
dtype=self.dtype,
|
366 |
+
precision=None,
|
367 |
+
)
|
368 |
+
|
369 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
|
370 |
+
attn_output = self._merge_heads(attn_output)
|
371 |
+
attn_output = self.out_proj(attn_output)
|
372 |
+
|
373 |
+
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
|
374 |
+
return outputs
|
375 |
+
|
376 |
+
|
377 |
+
class FlaxCLIPMLP(nn.Module):
|
378 |
+
config: Union[CLIPTextConfig, CLIPVisionConfig]
|
379 |
+
dtype: jnp.dtype = jnp.float32
|
380 |
+
|
381 |
+
def setup(self):
|
382 |
+
self.activation_fn = ACT2FN[self.config.hidden_act]
|
383 |
+
self.fc1 = nn.Dense(
|
384 |
+
self.config.intermediate_size,
|
385 |
+
dtype=self.dtype,
|
386 |
+
kernel_init=jax.nn.initializers.normal(0.01),
|
387 |
+
)
|
388 |
+
self.fc2 = nn.Dense(self.config.hidden_size, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(0.01))
|
389 |
+
|
390 |
+
def __call__(self, hidden_states):
|
391 |
+
hidden_states = self.fc1(hidden_states)
|
392 |
+
hidden_states = self.activation_fn(hidden_states)
|
393 |
+
hidden_states = self.fc2(hidden_states)
|
394 |
+
return hidden_states
|
395 |
+
|
396 |
+
|
397 |
+
class FlaxCLIPEncoderLayer(nn.Module):
|
398 |
+
config: Union[CLIPTextConfig, CLIPVisionConfig]
|
399 |
+
dtype: jnp.dtype = jnp.float32
|
400 |
+
|
401 |
+
def setup(self):
|
402 |
+
self.self_attn = FlaxCLIPAttention(self.config, dtype=self.dtype)
|
403 |
+
self.layer_norm1 = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
404 |
+
self.mlp = FlaxCLIPMLP(self.config, dtype=self.dtype)
|
405 |
+
self.layer_norm2 = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
406 |
+
|
407 |
+
def __call__(
|
408 |
+
self,
|
409 |
+
hidden_states,
|
410 |
+
attention_mask,
|
411 |
+
deterministic: bool = True,
|
412 |
+
output_attentions: bool = False,
|
413 |
+
):
|
414 |
+
residual = hidden_states
|
415 |
+
|
416 |
+
hidden_states = self.layer_norm1(hidden_states)
|
417 |
+
attn_outputs = self.self_attn(
|
418 |
+
hidden_states=hidden_states,
|
419 |
+
attention_mask=attention_mask,
|
420 |
+
deterministic=deterministic,
|
421 |
+
output_attentions=output_attentions,
|
422 |
+
)
|
423 |
+
hidden_states = attn_outputs[0]
|
424 |
+
hidden_states = residual + hidden_states
|
425 |
+
|
426 |
+
residual = hidden_states
|
427 |
+
hidden_states = self.layer_norm2(hidden_states)
|
428 |
+
hidden_states = self.mlp(hidden_states)
|
429 |
+
hidden_states = residual + hidden_states
|
430 |
+
|
431 |
+
outputs = (hidden_states,)
|
432 |
+
|
433 |
+
if output_attentions:
|
434 |
+
outputs += attn_outputs[1:]
|
435 |
+
|
436 |
+
return outputs
|
437 |
+
|
438 |
+
|
439 |
+
class FlaxCLIPLayerCollection(nn.Module):
|
440 |
+
config: Union[CLIPTextConfig, CLIPVisionConfig]
|
441 |
+
dtype: jnp.dtype = jnp.float32
|
442 |
+
|
443 |
+
def setup(self):
|
444 |
+
self.layers = [
|
445 |
+
FlaxCLIPEncoderLayer(self.config, name=str(i), dtype=self.dtype)
|
446 |
+
for i in range(self.config.num_hidden_layers)
|
447 |
+
]
|
448 |
+
|
449 |
+
def __call__(
|
450 |
+
self,
|
451 |
+
hidden_states,
|
452 |
+
attention_mask=None,
|
453 |
+
deterministic: bool = True,
|
454 |
+
output_attentions: bool = False,
|
455 |
+
output_hidden_states: bool = False,
|
456 |
+
return_dict: bool = True,
|
457 |
+
):
|
458 |
+
all_attentions = () if output_attentions else None
|
459 |
+
all_hidden_states = () if output_hidden_states else None
|
460 |
+
|
461 |
+
for layer in self.layers:
|
462 |
+
if output_hidden_states:
|
463 |
+
all_hidden_states += (hidden_states,)
|
464 |
+
|
465 |
+
layer_outputs = layer(
|
466 |
+
hidden_states, attention_mask, deterministic=deterministic, output_attentions=output_attentions
|
467 |
+
)
|
468 |
+
hidden_states = layer_outputs[0]
|
469 |
+
|
470 |
+
if output_attentions:
|
471 |
+
all_attentions += (layer_outputs[1],)
|
472 |
+
|
473 |
+
if output_hidden_states:
|
474 |
+
all_hidden_states += (hidden_states,)
|
475 |
+
|
476 |
+
outputs = (hidden_states,)
|
477 |
+
|
478 |
+
if not return_dict:
|
479 |
+
return tuple(v for v in outputs if v is not None)
|
480 |
+
|
481 |
+
return FlaxBaseModelOutput(
|
482 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
483 |
+
)
|
484 |
+
|
485 |
+
|
486 |
+
class FlaxCLIPEncoder(nn.Module):
|
487 |
+
config: Union[CLIPTextConfig, CLIPVisionConfig]
|
488 |
+
dtype: jnp.dtype = jnp.float32
|
489 |
+
|
490 |
+
def setup(self):
|
491 |
+
self.layers = FlaxCLIPLayerCollection(self.config, dtype=self.dtype)
|
492 |
+
|
493 |
+
def __call__(
|
494 |
+
self,
|
495 |
+
inputs_embeds,
|
496 |
+
attention_mask=None,
|
497 |
+
deterministic: bool = True,
|
498 |
+
output_attentions: bool = False,
|
499 |
+
output_hidden_states: bool = False,
|
500 |
+
return_dict: bool = True,
|
501 |
+
):
|
502 |
+
return self.layers(
|
503 |
+
hidden_states=inputs_embeds,
|
504 |
+
attention_mask=attention_mask,
|
505 |
+
deterministic=deterministic,
|
506 |
+
output_attentions=output_attentions,
|
507 |
+
output_hidden_states=output_hidden_states,
|
508 |
+
return_dict=return_dict,
|
509 |
+
)
|
510 |
+
|
511 |
+
|
512 |
+
class FlaxCLIPTextTransformer(nn.Module):
|
513 |
+
config: CLIPTextConfig
|
514 |
+
dtype: jnp.dtype = jnp.float32
|
515 |
+
|
516 |
+
def setup(self):
|
517 |
+
self.embeddings = FlaxCLIPTextEmbeddings(self.config, dtype=self.dtype)
|
518 |
+
self.encoder = FlaxCLIPEncoder(self.config, dtype=self.dtype)
|
519 |
+
self.final_layer_norm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
520 |
+
|
521 |
+
# For `pooled_output` computation
|
522 |
+
self.eos_token_id = self.config.eos_token_id
|
523 |
+
|
524 |
+
def __call__(
|
525 |
+
self,
|
526 |
+
input_ids,
|
527 |
+
attention_mask,
|
528 |
+
position_ids,
|
529 |
+
deterministic: bool = True,
|
530 |
+
output_attentions: bool = False,
|
531 |
+
output_hidden_states: bool = False,
|
532 |
+
return_dict: bool = True,
|
533 |
+
):
|
534 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
535 |
+
output_hidden_states = (
|
536 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
537 |
+
)
|
538 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
539 |
+
|
540 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
541 |
+
|
542 |
+
encoder_outputs = self.encoder(
|
543 |
+
inputs_embeds=hidden_states,
|
544 |
+
attention_mask=attention_mask,
|
545 |
+
deterministic=deterministic,
|
546 |
+
output_attentions=output_attentions,
|
547 |
+
output_hidden_states=output_hidden_states,
|
548 |
+
return_dict=return_dict,
|
549 |
+
)
|
550 |
+
|
551 |
+
last_hidden_state = encoder_outputs[0]
|
552 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
553 |
+
|
554 |
+
if self.eos_token_id == 2:
|
555 |
+
# The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
|
556 |
+
# A CLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added
|
557 |
+
# ------------------------------------------------------------
|
558 |
+
# text_embeds.shape = [batch_size, sequence_length, transformer.width]
|
559 |
+
# take features from the EOS embedding (eos_token_id is the highest number in each sequence)
|
560 |
+
pooled_output = last_hidden_state[jnp.arange(last_hidden_state.shape[0]), input_ids.argmax(axis=-1)]
|
561 |
+
else:
|
562 |
+
# (no need to cast from bool to int after comparing to `eos_token_id`)
|
563 |
+
pooled_output = last_hidden_state[
|
564 |
+
jnp.arange(last_hidden_state.shape[0]), (input_ids == self.eos_token_id).argmax(axis=-1)
|
565 |
+
]
|
566 |
+
|
567 |
+
if not return_dict:
|
568 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
569 |
+
|
570 |
+
return FlaxBaseModelOutputWithPooling(
|
571 |
+
last_hidden_state=last_hidden_state,
|
572 |
+
pooler_output=pooled_output,
|
573 |
+
hidden_states=encoder_outputs.hidden_states,
|
574 |
+
attentions=encoder_outputs.attentions,
|
575 |
+
)
|
576 |
+
|
577 |
+
|
578 |
+
class FlaxCLIPVisionTransformer(nn.Module):
|
579 |
+
config: CLIPVisionConfig
|
580 |
+
dtype: jnp.dtype = jnp.float32
|
581 |
+
|
582 |
+
def setup(self):
|
583 |
+
self.embeddings = FlaxCLIPVisionEmbeddings(self.config, dtype=self.dtype)
|
584 |
+
self.pre_layrnorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
585 |
+
self.encoder = FlaxCLIPEncoder(self.config, dtype=self.dtype)
|
586 |
+
self.post_layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
587 |
+
|
588 |
+
def __call__(
|
589 |
+
self,
|
590 |
+
pixel_values=None,
|
591 |
+
deterministic: bool = True,
|
592 |
+
output_attentions=None,
|
593 |
+
output_hidden_states=None,
|
594 |
+
return_dict: bool = True,
|
595 |
+
):
|
596 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
597 |
+
output_hidden_states = (
|
598 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
599 |
+
)
|
600 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
601 |
+
|
602 |
+
hidden_states = self.embeddings(pixel_values)
|
603 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
604 |
+
|
605 |
+
encoder_outputs = self.encoder(
|
606 |
+
inputs_embeds=hidden_states,
|
607 |
+
deterministic=deterministic,
|
608 |
+
output_attentions=output_attentions,
|
609 |
+
output_hidden_states=output_hidden_states,
|
610 |
+
return_dict=return_dict,
|
611 |
+
)
|
612 |
+
|
613 |
+
last_hidden_state = encoder_outputs[0]
|
614 |
+
pooled_output = last_hidden_state[:, 0, :]
|
615 |
+
pooled_output = self.post_layernorm(pooled_output)
|
616 |
+
|
617 |
+
if not return_dict:
|
618 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
619 |
+
|
620 |
+
return FlaxBaseModelOutputWithPooling(
|
621 |
+
last_hidden_state=last_hidden_state,
|
622 |
+
pooler_output=pooled_output,
|
623 |
+
hidden_states=encoder_outputs.hidden_states,
|
624 |
+
attentions=encoder_outputs.attentions,
|
625 |
+
)
|
626 |
+
|
627 |
+
|
628 |
+
class FlaxCLIPTextPreTrainedModel(FlaxPreTrainedModel):
|
629 |
+
config_class = CLIPTextConfig
|
630 |
+
module_class: nn.Module = None
|
631 |
+
|
632 |
+
def __init__(
|
633 |
+
self,
|
634 |
+
config: CLIPTextConfig,
|
635 |
+
input_shape=(1, 1),
|
636 |
+
seed: int = 0,
|
637 |
+
dtype: jnp.dtype = jnp.float32,
|
638 |
+
_do_init: bool = True,
|
639 |
+
**kwargs,
|
640 |
+
):
|
641 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
642 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
643 |
+
|
644 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
645 |
+
# init input tensor
|
646 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
647 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
|
648 |
+
attention_mask = jnp.ones_like(input_ids)
|
649 |
+
|
650 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
651 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
652 |
+
|
653 |
+
random_params = self.module.init(rngs, input_ids, attention_mask, position_ids)["params"]
|
654 |
+
|
655 |
+
if params is not None:
|
656 |
+
random_params = flatten_dict(unfreeze(random_params))
|
657 |
+
params = flatten_dict(unfreeze(params))
|
658 |
+
for missing_key in self._missing_keys:
|
659 |
+
params[missing_key] = random_params[missing_key]
|
660 |
+
self._missing_keys = set()
|
661 |
+
return freeze(unflatten_dict(params))
|
662 |
+
else:
|
663 |
+
return random_params
|
664 |
+
|
665 |
+
def __call__(
|
666 |
+
self,
|
667 |
+
input_ids,
|
668 |
+
attention_mask=None,
|
669 |
+
position_ids=None,
|
670 |
+
params: dict = None,
|
671 |
+
dropout_rng: jax.random.PRNGKey = None,
|
672 |
+
train: bool = False,
|
673 |
+
output_attentions: Optional[bool] = None,
|
674 |
+
output_hidden_states: Optional[bool] = None,
|
675 |
+
return_dict: Optional[bool] = None,
|
676 |
+
):
|
677 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
678 |
+
output_hidden_states = (
|
679 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
680 |
+
)
|
681 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
682 |
+
|
683 |
+
if position_ids is None:
|
684 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
685 |
+
|
686 |
+
if attention_mask is None:
|
687 |
+
attention_mask = jnp.ones_like(input_ids)
|
688 |
+
|
689 |
+
# Handle any PRNG if needed
|
690 |
+
rngs = {}
|
691 |
+
if dropout_rng is not None:
|
692 |
+
rngs["dropout"] = dropout_rng
|
693 |
+
|
694 |
+
return self.module.apply(
|
695 |
+
{"params": params or self.params},
|
696 |
+
jnp.array(input_ids, dtype="i4"),
|
697 |
+
jnp.array(attention_mask, dtype="i4"),
|
698 |
+
jnp.array(position_ids, dtype="i4"),
|
699 |
+
not train,
|
700 |
+
output_attentions,
|
701 |
+
output_hidden_states,
|
702 |
+
return_dict,
|
703 |
+
rngs=rngs,
|
704 |
+
)
|
705 |
+
|
706 |
+
|
707 |
+
class FlaxCLIPVisionPreTrainedModel(FlaxPreTrainedModel):
|
708 |
+
config_class = CLIPVisionConfig
|
709 |
+
main_input_name = "pixel_values"
|
710 |
+
module_class: nn.Module = None
|
711 |
+
|
712 |
+
def __init__(
|
713 |
+
self,
|
714 |
+
config: CLIPVisionConfig,
|
715 |
+
input_shape: Optional[Tuple] = None,
|
716 |
+
seed: int = 0,
|
717 |
+
dtype: jnp.dtype = jnp.float32,
|
718 |
+
_do_init: bool = True,
|
719 |
+
**kwargs,
|
720 |
+
):
|
721 |
+
if input_shape is None:
|
722 |
+
input_shape = (1, config.image_size, config.image_size, 3)
|
723 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
724 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
725 |
+
|
726 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
727 |
+
# init input tensor
|
728 |
+
pixel_values = jax.random.normal(rng, input_shape)
|
729 |
+
|
730 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
731 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
732 |
+
|
733 |
+
random_params = self.module.init(rngs, pixel_values)["params"]
|
734 |
+
|
735 |
+
if params is not None:
|
736 |
+
random_params = flatten_dict(unfreeze(random_params))
|
737 |
+
params = flatten_dict(unfreeze(params))
|
738 |
+
for missing_key in self._missing_keys:
|
739 |
+
params[missing_key] = random_params[missing_key]
|
740 |
+
self._missing_keys = set()
|
741 |
+
return freeze(unflatten_dict(params))
|
742 |
+
else:
|
743 |
+
return random_params
|
744 |
+
|
745 |
+
def __call__(
|
746 |
+
self,
|
747 |
+
pixel_values,
|
748 |
+
params: dict = None,
|
749 |
+
dropout_rng: jax.random.PRNGKey = None,
|
750 |
+
train: bool = False,
|
751 |
+
output_attentions: Optional[bool] = None,
|
752 |
+
output_hidden_states: Optional[bool] = None,
|
753 |
+
return_dict: Optional[bool] = None,
|
754 |
+
):
|
755 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
756 |
+
output_hidden_states = (
|
757 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
758 |
+
)
|
759 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
760 |
+
|
761 |
+
pixel_values = jnp.transpose(pixel_values, (0, 2, 3, 1))
|
762 |
+
|
763 |
+
# Handle any PRNG if needed
|
764 |
+
rngs = {}
|
765 |
+
if dropout_rng is not None:
|
766 |
+
rngs["dropout"] = dropout_rng
|
767 |
+
|
768 |
+
return self.module.apply(
|
769 |
+
{"params": params or self.params},
|
770 |
+
jnp.array(pixel_values, dtype=jnp.float32),
|
771 |
+
not train,
|
772 |
+
output_attentions,
|
773 |
+
output_hidden_states,
|
774 |
+
return_dict,
|
775 |
+
rngs=rngs,
|
776 |
+
)
|
777 |
+
|
778 |
+
|
779 |
+
class FlaxCLIPPreTrainedModel(FlaxPreTrainedModel):
|
780 |
+
config_class = CLIPConfig
|
781 |
+
module_class: nn.Module = None
|
782 |
+
|
783 |
+
def __init__(
|
784 |
+
self,
|
785 |
+
config: CLIPConfig,
|
786 |
+
input_shape: Optional[Tuple] = None,
|
787 |
+
seed: int = 0,
|
788 |
+
dtype: jnp.dtype = jnp.float32,
|
789 |
+
_do_init: bool = True,
|
790 |
+
**kwargs,
|
791 |
+
):
|
792 |
+
if input_shape is None:
|
793 |
+
input_shape = ((1, 1), (1, config.vision_config.image_size, config.vision_config.image_size, 3))
|
794 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
795 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
796 |
+
|
797 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
798 |
+
# init input tensor
|
799 |
+
input_ids = jnp.zeros(input_shape[0], dtype="i4")
|
800 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape[0])
|
801 |
+
attention_mask = jnp.ones_like(input_ids)
|
802 |
+
|
803 |
+
pixel_values = jax.random.normal(rng, input_shape[1])
|
804 |
+
|
805 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
806 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
807 |
+
|
808 |
+
random_params = self.module.init(rngs, input_ids, pixel_values, attention_mask, position_ids)["params"]
|
809 |
+
|
810 |
+
if params is not None:
|
811 |
+
random_params = flatten_dict(unfreeze(random_params))
|
812 |
+
params = flatten_dict(unfreeze(params))
|
813 |
+
for missing_key in self._missing_keys:
|
814 |
+
params[missing_key] = random_params[missing_key]
|
815 |
+
self._missing_keys = set()
|
816 |
+
return freeze(unflatten_dict(params))
|
817 |
+
else:
|
818 |
+
return random_params
|
819 |
+
|
820 |
+
def __call__(
|
821 |
+
self,
|
822 |
+
input_ids,
|
823 |
+
pixel_values,
|
824 |
+
attention_mask=None,
|
825 |
+
position_ids=None,
|
826 |
+
params: dict = None,
|
827 |
+
dropout_rng: jax.random.PRNGKey = None,
|
828 |
+
train: bool = False,
|
829 |
+
output_attentions: Optional[bool] = None,
|
830 |
+
output_hidden_states: Optional[bool] = None,
|
831 |
+
return_dict: Optional[bool] = None,
|
832 |
+
):
|
833 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
834 |
+
output_hidden_states = (
|
835 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
836 |
+
)
|
837 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
838 |
+
|
839 |
+
if position_ids is None:
|
840 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
841 |
+
|
842 |
+
if attention_mask is None:
|
843 |
+
attention_mask = jnp.ones_like(input_ids)
|
844 |
+
|
845 |
+
pixel_values = jnp.transpose(pixel_values, (0, 2, 3, 1))
|
846 |
+
|
847 |
+
# Handle any PRNG if needed
|
848 |
+
rngs = {}
|
849 |
+
if dropout_rng is not None:
|
850 |
+
rngs["dropout"] = dropout_rng
|
851 |
+
|
852 |
+
return self.module.apply(
|
853 |
+
{"params": params or self.params},
|
854 |
+
jnp.array(input_ids, dtype="i4"),
|
855 |
+
jnp.array(pixel_values, dtype=jnp.float32),
|
856 |
+
jnp.array(attention_mask, dtype="i4"),
|
857 |
+
jnp.array(position_ids, dtype="i4"),
|
858 |
+
not train,
|
859 |
+
output_attentions,
|
860 |
+
output_hidden_states,
|
861 |
+
return_dict,
|
862 |
+
rngs=rngs,
|
863 |
+
)
|
864 |
+
|
865 |
+
def get_text_features(
|
866 |
+
self,
|
867 |
+
input_ids,
|
868 |
+
attention_mask=None,
|
869 |
+
position_ids=None,
|
870 |
+
params: dict = None,
|
871 |
+
dropout_rng: jax.random.PRNGKey = None,
|
872 |
+
train=False,
|
873 |
+
):
|
874 |
+
r"""
|
875 |
+
Args:
|
876 |
+
input_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`):
|
877 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
|
878 |
+
provide it.
|
879 |
+
|
880 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
881 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
882 |
+
|
883 |
+
[What are input IDs?](../glossary#input-ids)
|
884 |
+
|
885 |
+
Returns:
|
886 |
+
text_features (`jnp.ndarray` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
|
887 |
+
the projection layer to the pooled output of [`FlaxCLIPTextModel`].
|
888 |
+
|
889 |
+
Examples:
|
890 |
+
|
891 |
+
```python
|
892 |
+
>>> from transformers import AutoTokenizer, FlaxCLIPModel
|
893 |
+
|
894 |
+
>>> model = FlaxCLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
895 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
896 |
+
|
897 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="np")
|
898 |
+
>>> text_features = model.get_text_features(**inputs)
|
899 |
+
```"""
|
900 |
+
if position_ids is None:
|
901 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
902 |
+
|
903 |
+
if attention_mask is None:
|
904 |
+
attention_mask = jnp.ones_like(input_ids)
|
905 |
+
|
906 |
+
# Handle any PRNG if needed
|
907 |
+
rngs = {}
|
908 |
+
if dropout_rng is not None:
|
909 |
+
rngs["dropout"] = dropout_rng
|
910 |
+
|
911 |
+
def _get_features(module, input_ids, attention_mask, position_ids, deterministic):
|
912 |
+
text_outputs = module.text_model(
|
913 |
+
input_ids=input_ids,
|
914 |
+
attention_mask=attention_mask,
|
915 |
+
position_ids=position_ids,
|
916 |
+
deterministic=deterministic,
|
917 |
+
)
|
918 |
+
pooled_output = text_outputs[1]
|
919 |
+
text_features = module.text_projection(pooled_output)
|
920 |
+
return text_features
|
921 |
+
|
922 |
+
return self.module.apply(
|
923 |
+
{"params": params or self.params},
|
924 |
+
jnp.array(input_ids, dtype="i4"),
|
925 |
+
jnp.array(attention_mask, dtype="i4"),
|
926 |
+
jnp.array(position_ids, dtype="i4"),
|
927 |
+
not train,
|
928 |
+
method=_get_features,
|
929 |
+
rngs=rngs,
|
930 |
+
)
|
931 |
+
|
932 |
+
def get_image_features(
|
933 |
+
self, pixel_values, params: dict = None, dropout_rng: jax.random.PRNGKey = None, train=False
|
934 |
+
):
|
935 |
+
r"""
|
936 |
+
Args:
|
937 |
+
pixel_values (`numpy.ndarray` of shape `(batch_size, num_channels, height, width)`):
|
938 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained
|
939 |
+
using [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
940 |
+
|
941 |
+
Returns:
|
942 |
+
image_features (`jnp.ndarray` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
943 |
+
applying the projection layer to the pooled output of [`FlaxCLIPVisionModel`]
|
944 |
+
|
945 |
+
Examples:
|
946 |
+
|
947 |
+
```python
|
948 |
+
>>> from PIL import Image
|
949 |
+
>>> import requests
|
950 |
+
>>> from transformers import AutoProcessor, FlaxCLIPModel
|
951 |
+
|
952 |
+
>>> model = FlaxCLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
953 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
954 |
+
|
955 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
956 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
957 |
+
|
958 |
+
>>> inputs = processor(images=image, return_tensors="np")
|
959 |
+
|
960 |
+
>>> image_features = model.get_image_features(**inputs)
|
961 |
+
```"""
|
962 |
+
pixel_values = jnp.transpose(pixel_values, (0, 2, 3, 1))
|
963 |
+
|
964 |
+
# Handle any PRNG if needed
|
965 |
+
rngs = {}
|
966 |
+
if dropout_rng is not None:
|
967 |
+
rngs["dropout"] = dropout_rng
|
968 |
+
|
969 |
+
def _get_features(module, pixel_values, deterministic):
|
970 |
+
vision_outputs = module.vision_model(pixel_values=pixel_values, deterministic=deterministic)
|
971 |
+
pooled_output = vision_outputs[1] # pooled_output
|
972 |
+
image_features = module.visual_projection(pooled_output)
|
973 |
+
return image_features
|
974 |
+
|
975 |
+
return self.module.apply(
|
976 |
+
{"params": params or self.params},
|
977 |
+
jnp.array(pixel_values, dtype=jnp.float32),
|
978 |
+
not train,
|
979 |
+
method=_get_features,
|
980 |
+
rngs=rngs,
|
981 |
+
)
|
982 |
+
|
983 |
+
|
984 |
+
class FlaxCLIPTextModule(nn.Module):
|
985 |
+
config: CLIPTextConfig
|
986 |
+
dtype: jnp.dtype = jnp.float32
|
987 |
+
|
988 |
+
def setup(self):
|
989 |
+
self.text_model = FlaxCLIPTextTransformer(self.config, dtype=self.dtype)
|
990 |
+
|
991 |
+
def __call__(
|
992 |
+
self,
|
993 |
+
input_ids,
|
994 |
+
attention_mask,
|
995 |
+
position_ids,
|
996 |
+
deterministic: bool = True,
|
997 |
+
output_attentions: bool = False,
|
998 |
+
output_hidden_states: bool = False,
|
999 |
+
return_dict: bool = True,
|
1000 |
+
):
|
1001 |
+
return self.text_model(
|
1002 |
+
input_ids=input_ids,
|
1003 |
+
attention_mask=attention_mask,
|
1004 |
+
position_ids=position_ids,
|
1005 |
+
deterministic=deterministic,
|
1006 |
+
output_attentions=output_attentions,
|
1007 |
+
output_hidden_states=output_hidden_states,
|
1008 |
+
return_dict=return_dict,
|
1009 |
+
)
|
1010 |
+
|
1011 |
+
|
1012 |
+
class FlaxCLIPTextModel(FlaxCLIPTextPreTrainedModel):
|
1013 |
+
module_class = FlaxCLIPTextModule
|
1014 |
+
|
1015 |
+
|
1016 |
+
FLAX_CLIP_TEXT_MODEL_DOCSTRING = """
|
1017 |
+
Returns:
|
1018 |
+
|
1019 |
+
Example:
|
1020 |
+
|
1021 |
+
```python
|
1022 |
+
>>> from transformers import AutoTokenizer, FlaxCLIPTextModel
|
1023 |
+
|
1024 |
+
>>> model = FlaxCLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
|
1025 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
1026 |
+
|
1027 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="np")
|
1028 |
+
|
1029 |
+
>>> outputs = model(**inputs)
|
1030 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
1031 |
+
>>> pooler_output = outputs.pooler_output # pooled (EOS token) states
|
1032 |
+
```
|
1033 |
+
"""
|
1034 |
+
|
1035 |
+
overwrite_call_docstring(FlaxCLIPTextModel, CLIP_TEXT_INPUTS_DOCSTRING + FLAX_CLIP_TEXT_MODEL_DOCSTRING)
|
1036 |
+
append_replace_return_docstrings(
|
1037 |
+
FlaxCLIPTextModel, output_type=FlaxBaseModelOutputWithPooling, config_class=CLIPTextConfig
|
1038 |
+
)
|
1039 |
+
|
1040 |
+
|
1041 |
+
class FlaxCLIPTextModelWithProjectionModule(nn.Module):
|
1042 |
+
config: CLIPTextConfig
|
1043 |
+
dtype: jnp.dtype = jnp.float32
|
1044 |
+
|
1045 |
+
def setup(self):
|
1046 |
+
self.text_model = FlaxCLIPTextTransformer(self.config, dtype=self.dtype)
|
1047 |
+
self.text_projection = nn.Dense(self.config.projection_dim, use_bias=False, dtype=self.dtype)
|
1048 |
+
|
1049 |
+
def __call__(
|
1050 |
+
self,
|
1051 |
+
input_ids,
|
1052 |
+
attention_mask,
|
1053 |
+
position_ids,
|
1054 |
+
deterministic: bool = True,
|
1055 |
+
output_attentions: bool = False,
|
1056 |
+
output_hidden_states: bool = False,
|
1057 |
+
return_dict: bool = True,
|
1058 |
+
):
|
1059 |
+
text_outputs = self.text_model(
|
1060 |
+
input_ids=input_ids,
|
1061 |
+
attention_mask=attention_mask,
|
1062 |
+
position_ids=position_ids,
|
1063 |
+
deterministic=deterministic,
|
1064 |
+
output_attentions=output_attentions,
|
1065 |
+
output_hidden_states=output_hidden_states,
|
1066 |
+
return_dict=return_dict,
|
1067 |
+
)
|
1068 |
+
|
1069 |
+
pooled_output = text_outputs[1]
|
1070 |
+
text_embeds = self.text_projection(pooled_output)
|
1071 |
+
|
1072 |
+
if not return_dict:
|
1073 |
+
return (text_embeds, text_outputs[0]) + text_outputs[2:]
|
1074 |
+
|
1075 |
+
return FlaxCLIPTextModelOutput(
|
1076 |
+
text_embeds=text_embeds,
|
1077 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
1078 |
+
hidden_states=text_outputs.hidden_states,
|
1079 |
+
attentions=text_outputs.attentions,
|
1080 |
+
)
|
1081 |
+
|
1082 |
+
|
1083 |
+
class FlaxCLIPTextModelWithProjection(FlaxCLIPTextPreTrainedModel):
|
1084 |
+
module_class = FlaxCLIPTextModelWithProjectionModule
|
1085 |
+
|
1086 |
+
|
1087 |
+
FLAX_CLIP_TEXT_MODEL_WITH_PROJECTION_DOCSTRING = """
|
1088 |
+
Returns:
|
1089 |
+
|
1090 |
+
Example:
|
1091 |
+
|
1092 |
+
```python
|
1093 |
+
>>> from transformers import AutoTokenizer, FlaxCLIPTextModelWithProjection
|
1094 |
+
|
1095 |
+
>>> model = FlaxCLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
1096 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
1097 |
+
|
1098 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="np")
|
1099 |
+
|
1100 |
+
>>> outputs = model(**inputs)
|
1101 |
+
>>> text_embeds = outputs.text_embeds
|
1102 |
+
```
|
1103 |
+
"""
|
1104 |
+
|
1105 |
+
overwrite_call_docstring(
|
1106 |
+
FlaxCLIPTextModelWithProjection, CLIP_TEXT_INPUTS_DOCSTRING + FLAX_CLIP_TEXT_MODEL_WITH_PROJECTION_DOCSTRING
|
1107 |
+
)
|
1108 |
+
append_replace_return_docstrings(
|
1109 |
+
FlaxCLIPTextModelWithProjection, output_type=FlaxCLIPTextModelOutput, config_class=CLIPTextConfig
|
1110 |
+
)
|
1111 |
+
|
1112 |
+
|
1113 |
+
class FlaxCLIPVisionModule(nn.Module):
|
1114 |
+
config: CLIPVisionConfig
|
1115 |
+
dtype: jnp.dtype = jnp.float32
|
1116 |
+
|
1117 |
+
def setup(self):
|
1118 |
+
self.vision_model = FlaxCLIPVisionTransformer(self.config, dtype=self.dtype)
|
1119 |
+
|
1120 |
+
def __call__(
|
1121 |
+
self,
|
1122 |
+
pixel_values,
|
1123 |
+
deterministic: bool = True,
|
1124 |
+
output_attentions: bool = False,
|
1125 |
+
output_hidden_states: bool = False,
|
1126 |
+
return_dict: bool = True,
|
1127 |
+
):
|
1128 |
+
return self.vision_model(
|
1129 |
+
pixel_values=pixel_values,
|
1130 |
+
deterministic=deterministic,
|
1131 |
+
output_attentions=output_attentions,
|
1132 |
+
output_hidden_states=output_hidden_states,
|
1133 |
+
return_dict=return_dict,
|
1134 |
+
)
|
1135 |
+
|
1136 |
+
|
1137 |
+
class FlaxCLIPVisionModel(FlaxCLIPVisionPreTrainedModel):
|
1138 |
+
module_class = FlaxCLIPVisionModule
|
1139 |
+
|
1140 |
+
|
1141 |
+
FLAX_CLIP_VISION_MODEL_DOCSTRING = """
|
1142 |
+
Returns:
|
1143 |
+
|
1144 |
+
Example:
|
1145 |
+
|
1146 |
+
```python
|
1147 |
+
>>> from PIL import Image
|
1148 |
+
>>> import requests
|
1149 |
+
>>> from transformers import AutoProcessor, FlaxCLIPVisionModel
|
1150 |
+
|
1151 |
+
>>> model = FlaxCLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
|
1152 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1153 |
+
|
1154 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1155 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1156 |
+
|
1157 |
+
>>> inputs = processor(images=image, return_tensors="np")
|
1158 |
+
|
1159 |
+
>>> outputs = model(**inputs)
|
1160 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
1161 |
+
>>> pooler_output = outputs.pooler_output # pooled CLS states
|
1162 |
+
```
|
1163 |
+
"""
|
1164 |
+
|
1165 |
+
overwrite_call_docstring(FlaxCLIPVisionModel, CLIP_VISION_INPUTS_DOCSTRING + FLAX_CLIP_VISION_MODEL_DOCSTRING)
|
1166 |
+
append_replace_return_docstrings(
|
1167 |
+
FlaxCLIPVisionModel, output_type=FlaxBaseModelOutputWithPooling, config_class=CLIPVisionConfig
|
1168 |
+
)
|
1169 |
+
|
1170 |
+
|
1171 |
+
class FlaxCLIPModule(nn.Module):
|
1172 |
+
config: CLIPConfig
|
1173 |
+
dtype: jnp.dtype = jnp.float32
|
1174 |
+
|
1175 |
+
def setup(self):
|
1176 |
+
text_config = self.config.text_config
|
1177 |
+
vision_config = self.config.vision_config
|
1178 |
+
|
1179 |
+
self.projection_dim = self.config.projection_dim
|
1180 |
+
self.text_embed_dim = text_config.hidden_size
|
1181 |
+
self.vision_embed_dim = vision_config.hidden_size
|
1182 |
+
|
1183 |
+
self.text_model = FlaxCLIPTextTransformer(text_config, dtype=self.dtype)
|
1184 |
+
self.vision_model = FlaxCLIPVisionTransformer(vision_config, dtype=self.dtype)
|
1185 |
+
|
1186 |
+
self.visual_projection = nn.Dense(
|
1187 |
+
self.projection_dim,
|
1188 |
+
dtype=self.dtype,
|
1189 |
+
kernel_init=jax.nn.initializers.normal(0.02),
|
1190 |
+
use_bias=False,
|
1191 |
+
)
|
1192 |
+
self.text_projection = nn.Dense(
|
1193 |
+
self.projection_dim,
|
1194 |
+
dtype=self.dtype,
|
1195 |
+
kernel_init=jax.nn.initializers.normal(0.02),
|
1196 |
+
use_bias=False,
|
1197 |
+
)
|
1198 |
+
|
1199 |
+
self.logit_scale = self.param(
|
1200 |
+
"logit_scale", lambda _, shape: jnp.ones(shape) * self.config.logit_scale_init_value, []
|
1201 |
+
)
|
1202 |
+
|
1203 |
+
def __call__(
|
1204 |
+
self,
|
1205 |
+
input_ids=None,
|
1206 |
+
pixel_values=None,
|
1207 |
+
attention_mask=None,
|
1208 |
+
position_ids=None,
|
1209 |
+
deterministic: bool = True,
|
1210 |
+
output_attentions=None,
|
1211 |
+
output_hidden_states=None,
|
1212 |
+
return_dict=None,
|
1213 |
+
):
|
1214 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
1215 |
+
|
1216 |
+
vision_outputs = self.vision_model(
|
1217 |
+
pixel_values=pixel_values,
|
1218 |
+
deterministic=deterministic,
|
1219 |
+
output_attentions=output_attentions,
|
1220 |
+
output_hidden_states=output_hidden_states,
|
1221 |
+
return_dict=return_dict,
|
1222 |
+
)
|
1223 |
+
|
1224 |
+
text_outputs = self.text_model(
|
1225 |
+
input_ids=input_ids,
|
1226 |
+
attention_mask=attention_mask,
|
1227 |
+
position_ids=position_ids,
|
1228 |
+
deterministic=deterministic,
|
1229 |
+
output_attentions=output_attentions,
|
1230 |
+
output_hidden_states=output_hidden_states,
|
1231 |
+
return_dict=return_dict,
|
1232 |
+
)
|
1233 |
+
|
1234 |
+
image_embeds = vision_outputs[1]
|
1235 |
+
image_embeds = self.visual_projection(image_embeds)
|
1236 |
+
|
1237 |
+
text_embeds = text_outputs[1]
|
1238 |
+
text_embeds = self.text_projection(text_embeds)
|
1239 |
+
|
1240 |
+
# normalized features
|
1241 |
+
image_embeds = image_embeds / jnp.linalg.norm(image_embeds, axis=-1, keepdims=True)
|
1242 |
+
text_embeds = text_embeds / jnp.linalg.norm(text_embeds, axis=-1, keepdims=True)
|
1243 |
+
|
1244 |
+
# cosine similarity as logits
|
1245 |
+
logit_scale = jnp.exp(self.logit_scale)
|
1246 |
+
logits_per_text = jnp.matmul(text_embeds, image_embeds.T) * logit_scale
|
1247 |
+
logits_per_image = logits_per_text.T
|
1248 |
+
|
1249 |
+
if not return_dict:
|
1250 |
+
return (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
1251 |
+
|
1252 |
+
return FlaxCLIPOutput(
|
1253 |
+
logits_per_image=logits_per_image,
|
1254 |
+
logits_per_text=logits_per_text,
|
1255 |
+
text_embeds=text_embeds,
|
1256 |
+
image_embeds=image_embeds,
|
1257 |
+
text_model_output=text_outputs,
|
1258 |
+
vision_model_output=vision_outputs,
|
1259 |
+
)
|
1260 |
+
|
1261 |
+
|
1262 |
+
@add_start_docstrings(CLIP_START_DOCSTRING)
|
1263 |
+
class FlaxCLIPModel(FlaxCLIPPreTrainedModel):
|
1264 |
+
module_class = FlaxCLIPModule
|
1265 |
+
|
1266 |
+
|
1267 |
+
FLAX_CLIP_MODEL_DOCSTRING = """
|
1268 |
+
Returns:
|
1269 |
+
|
1270 |
+
Example:
|
1271 |
+
|
1272 |
+
```python
|
1273 |
+
>>> import jax
|
1274 |
+
>>> from PIL import Image
|
1275 |
+
>>> import requests
|
1276 |
+
>>> from transformers import AutoProcessor, FlaxCLIPModel
|
1277 |
+
|
1278 |
+
>>> model = FlaxCLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1279 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1280 |
+
|
1281 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1282 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1283 |
+
|
1284 |
+
>>> inputs = processor(
|
1285 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="np", padding=True
|
1286 |
+
... )
|
1287 |
+
|
1288 |
+
>>> outputs = model(**inputs)
|
1289 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
1290 |
+
>>> probs = jax.nn.softmax(logits_per_image, axis=1) # we can take the softmax to get the label probabilities
|
1291 |
+
```
|
1292 |
+
"""
|
1293 |
+
|
1294 |
+
overwrite_call_docstring(FlaxCLIPModel, CLIP_INPUTS_DOCSTRING + FLAX_CLIP_MODEL_DOCSTRING)
|
1295 |
+
append_replace_return_docstrings(FlaxCLIPModel, output_type=FlaxCLIPOutput, config_class=CLIPConfig)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/modeling_tf_clip.py
ADDED
@@ -0,0 +1,1461 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The OpenAI Team Authors and The HuggingFace 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 |
+
""" TF 2.0 CLIP model."""
|
16 |
+
|
17 |
+
|
18 |
+
from __future__ import annotations
|
19 |
+
|
20 |
+
import math
|
21 |
+
from dataclasses import dataclass
|
22 |
+
from typing import Any, Optional, Tuple, Union
|
23 |
+
|
24 |
+
import numpy as np
|
25 |
+
import tensorflow as tf
|
26 |
+
|
27 |
+
from ...activations_tf import get_tf_activation
|
28 |
+
from ...modeling_tf_outputs import TFBaseModelOutput, TFBaseModelOutputWithPooling
|
29 |
+
|
30 |
+
# Public API
|
31 |
+
from ...modeling_tf_utils import (
|
32 |
+
TFModelInputType,
|
33 |
+
TFPreTrainedModel,
|
34 |
+
get_initializer,
|
35 |
+
keras,
|
36 |
+
keras_serializable,
|
37 |
+
unpack_inputs,
|
38 |
+
)
|
39 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
40 |
+
from ...utils import (
|
41 |
+
ModelOutput,
|
42 |
+
add_start_docstrings,
|
43 |
+
add_start_docstrings_to_model_forward,
|
44 |
+
logging,
|
45 |
+
replace_return_docstrings,
|
46 |
+
)
|
47 |
+
from .configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
|
48 |
+
|
49 |
+
|
50 |
+
logger = logging.get_logger(__name__)
|
51 |
+
|
52 |
+
_CHECKPOINT_FOR_DOC = "openai/clip-vit-base-patch32"
|
53 |
+
|
54 |
+
|
55 |
+
from ..deprecated._archive_maps import TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
56 |
+
|
57 |
+
|
58 |
+
LARGE_NEGATIVE = -1e8
|
59 |
+
|
60 |
+
|
61 |
+
# Copied from transformers.models.bart.modeling_tf_bart._expand_mask
|
62 |
+
def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
|
63 |
+
"""
|
64 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
65 |
+
"""
|
66 |
+
src_len = shape_list(mask)[1]
|
67 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
68 |
+
one_cst = tf.constant(1.0)
|
69 |
+
mask = tf.cast(mask, dtype=one_cst.dtype)
|
70 |
+
expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
|
71 |
+
|
72 |
+
return (one_cst - expanded_mask) * LARGE_NEGATIVE
|
73 |
+
|
74 |
+
|
75 |
+
# contrastive loss function, adapted from
|
76 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
77 |
+
def contrastive_loss(logits: tf.Tensor) -> tf.Tensor:
|
78 |
+
return tf.math.reduce_mean(
|
79 |
+
keras.metrics.sparse_categorical_crossentropy(
|
80 |
+
y_true=tf.range(shape_list(logits)[0]), y_pred=logits, from_logits=True
|
81 |
+
)
|
82 |
+
)
|
83 |
+
|
84 |
+
|
85 |
+
def clip_loss(similarity: tf.Tensor) -> tf.Tensor:
|
86 |
+
caption_loss = contrastive_loss(similarity)
|
87 |
+
image_loss = contrastive_loss(tf.transpose(similarity))
|
88 |
+
return (caption_loss + image_loss) / 2.0
|
89 |
+
|
90 |
+
|
91 |
+
@dataclass
|
92 |
+
class TFCLIPOutput(ModelOutput):
|
93 |
+
"""
|
94 |
+
Args:
|
95 |
+
loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
96 |
+
Contrastive loss for image-text similarity.
|
97 |
+
logits_per_image:(`tf.Tensor` of shape `(image_batch_size, text_batch_size)`):
|
98 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
99 |
+
similarity scores.
|
100 |
+
logits_per_text:(`tf.Tensor` of shape `(text_batch_size, image_batch_size)`):
|
101 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
102 |
+
similarity scores.
|
103 |
+
text_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
|
104 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`TFCLIPTextModel`].
|
105 |
+
image_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
|
106 |
+
The image embeddings obtained by applying the projection layer to the pooled output of
|
107 |
+
[`TFCLIPVisionModel`].
|
108 |
+
text_model_output([`~modeling_tf_utils.TFBaseModelOutputWithPooling`]):
|
109 |
+
The output of the [`TFCLIPTextModel`].
|
110 |
+
vision_model_output([`~modeling_tf_utils.TFBaseModelOutputWithPooling`]):
|
111 |
+
The output of the [`TFCLIPVisionModel`].
|
112 |
+
"""
|
113 |
+
|
114 |
+
loss: tf.Tensor | None = None
|
115 |
+
logits_per_image: tf.Tensor = None
|
116 |
+
logits_per_text: tf.Tensor = None
|
117 |
+
text_embeds: tf.Tensor = None
|
118 |
+
image_embeds: tf.Tensor = None
|
119 |
+
text_model_output: TFBaseModelOutputWithPooling = None
|
120 |
+
vision_model_output: TFBaseModelOutputWithPooling = None
|
121 |
+
|
122 |
+
def to_tuple(self) -> Tuple[Any]:
|
123 |
+
return tuple(
|
124 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
125 |
+
for k in self.keys()
|
126 |
+
)
|
127 |
+
|
128 |
+
|
129 |
+
class TFCLIPVisionEmbeddings(keras.layers.Layer):
|
130 |
+
def __init__(self, config: CLIPVisionConfig, **kwargs):
|
131 |
+
super().__init__(**kwargs)
|
132 |
+
|
133 |
+
self.embed_dim = config.hidden_size
|
134 |
+
self.image_size = config.image_size
|
135 |
+
self.patch_size = config.patch_size
|
136 |
+
|
137 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
138 |
+
self.num_positions = self.num_patches + 1
|
139 |
+
|
140 |
+
self.config = config
|
141 |
+
|
142 |
+
self.patch_embedding = keras.layers.Conv2D(
|
143 |
+
filters=self.embed_dim,
|
144 |
+
kernel_size=self.patch_size,
|
145 |
+
strides=self.patch_size,
|
146 |
+
padding="valid",
|
147 |
+
data_format="channels_last",
|
148 |
+
use_bias=False,
|
149 |
+
kernel_initializer=get_initializer(self.config.initializer_range * self.config.initializer_factor),
|
150 |
+
name="patch_embedding",
|
151 |
+
)
|
152 |
+
|
153 |
+
def build(self, input_shape: tf.TensorShape = None):
|
154 |
+
factor = self.config.initializer_factor
|
155 |
+
|
156 |
+
self.class_embedding = self.add_weight(
|
157 |
+
shape=(self.embed_dim,),
|
158 |
+
initializer=get_initializer(self.embed_dim**-0.5 * factor),
|
159 |
+
trainable=True,
|
160 |
+
name="class_embedding",
|
161 |
+
)
|
162 |
+
|
163 |
+
with tf.name_scope("position_embedding"):
|
164 |
+
self.position_embedding = self.add_weight(
|
165 |
+
shape=(self.num_positions, self.embed_dim),
|
166 |
+
initializer=get_initializer(self.config.initializer_range * factor),
|
167 |
+
trainable=True,
|
168 |
+
name="embeddings",
|
169 |
+
)
|
170 |
+
|
171 |
+
if self.built:
|
172 |
+
return
|
173 |
+
self.built = True
|
174 |
+
if getattr(self, "patch_embedding", None) is not None:
|
175 |
+
with tf.name_scope(self.patch_embedding.name):
|
176 |
+
self.patch_embedding.build([None, None, None, self.config.num_channels])
|
177 |
+
|
178 |
+
def call(self, pixel_values: tf.Tensor) -> tf.Tensor:
|
179 |
+
"""`pixel_values` is expected to be of NCHW format."""
|
180 |
+
|
181 |
+
batch_size, num_channels, height, width = shape_list(pixel_values)
|
182 |
+
|
183 |
+
# When running on CPU, `tf.nn.conv2d` doesn't support `NCHW` format.
|
184 |
+
# So change the input format from `NCHW` to `NHWC`.
|
185 |
+
# shape = (batch_size, in_height, in_width, in_channels=num_channels)
|
186 |
+
pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
|
187 |
+
|
188 |
+
patch_embeds = self.patch_embedding(pixel_values)
|
189 |
+
|
190 |
+
# Change the 2D spatial dimensions to a single temporal dimension.
|
191 |
+
# shape = (batch_size, num_patches, out_channels=embed_dim)
|
192 |
+
patch_embeds = tf.reshape(tensor=patch_embeds, shape=(batch_size, self.num_patches, -1))
|
193 |
+
|
194 |
+
# add the [CLS] token to the embedded patch tokens
|
195 |
+
class_embeds = tf.broadcast_to(self.class_embedding, shape=(batch_size, 1, self.embed_dim))
|
196 |
+
embeddings = tf.concat((class_embeds, patch_embeds), axis=1)
|
197 |
+
|
198 |
+
embeddings = embeddings + self.position_embedding
|
199 |
+
|
200 |
+
return embeddings
|
201 |
+
|
202 |
+
|
203 |
+
class TFCLIPTextEmbeddings(keras.layers.Layer):
|
204 |
+
def __init__(self, config: CLIPTextConfig, **kwargs):
|
205 |
+
super().__init__(**kwargs)
|
206 |
+
|
207 |
+
self.embed_dim = config.hidden_size
|
208 |
+
|
209 |
+
self.config = config
|
210 |
+
|
211 |
+
def build(self, input_shape: tf.TensorShape = None):
|
212 |
+
with tf.name_scope("token_embedding"):
|
213 |
+
self.weight = self.add_weight(
|
214 |
+
shape=(self.config.vocab_size, self.embed_dim),
|
215 |
+
initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
|
216 |
+
trainable=True,
|
217 |
+
name="weight",
|
218 |
+
)
|
219 |
+
|
220 |
+
with tf.name_scope("position_embedding"):
|
221 |
+
self.position_embedding = self.add_weight(
|
222 |
+
shape=(self.config.max_position_embeddings, self.embed_dim),
|
223 |
+
initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
|
224 |
+
trainable=True,
|
225 |
+
name="embeddings",
|
226 |
+
)
|
227 |
+
|
228 |
+
super().build(input_shape)
|
229 |
+
|
230 |
+
def call(
|
231 |
+
self,
|
232 |
+
input_ids: tf.Tensor = None,
|
233 |
+
position_ids: tf.Tensor = None,
|
234 |
+
inputs_embeds: tf.Tensor = None,
|
235 |
+
) -> tf.Tensor:
|
236 |
+
"""
|
237 |
+
Applies embedding based on inputs tensor.
|
238 |
+
|
239 |
+
Returns:
|
240 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
241 |
+
"""
|
242 |
+
if input_ids is None and inputs_embeds is None:
|
243 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
244 |
+
|
245 |
+
if inputs_embeds is None:
|
246 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
247 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
248 |
+
|
249 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
250 |
+
|
251 |
+
if position_ids is None:
|
252 |
+
position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
|
253 |
+
|
254 |
+
position_embeds = tf.gather(params=self.position_embedding, indices=position_ids)
|
255 |
+
position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
|
256 |
+
final_embeddings = inputs_embeds + position_embeds
|
257 |
+
|
258 |
+
return final_embeddings
|
259 |
+
|
260 |
+
|
261 |
+
class TFCLIPAttention(keras.layers.Layer):
|
262 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
263 |
+
|
264 |
+
def __init__(self, config: CLIPConfig, **kwargs):
|
265 |
+
super().__init__(**kwargs)
|
266 |
+
|
267 |
+
self.embed_dim = config.hidden_size
|
268 |
+
self.num_attention_heads = config.num_attention_heads
|
269 |
+
self.attention_head_size = self.embed_dim // self.num_attention_heads
|
270 |
+
if self.attention_head_size * self.num_attention_heads != self.embed_dim:
|
271 |
+
raise ValueError(
|
272 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
273 |
+
f" {self.num_attention_heads})."
|
274 |
+
)
|
275 |
+
|
276 |
+
factor = config.initializer_factor
|
277 |
+
in_proj_std = (self.embed_dim**-0.5) * ((2 * config.num_hidden_layers) ** -0.5) * factor
|
278 |
+
out_proj_std = (self.embed_dim**-0.5) * factor
|
279 |
+
|
280 |
+
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
|
281 |
+
|
282 |
+
self.q_proj = keras.layers.Dense(
|
283 |
+
units=self.embed_dim, kernel_initializer=get_initializer(in_proj_std), name="q_proj"
|
284 |
+
)
|
285 |
+
self.k_proj = keras.layers.Dense(
|
286 |
+
units=self.embed_dim, kernel_initializer=get_initializer(in_proj_std), name="k_proj"
|
287 |
+
)
|
288 |
+
self.v_proj = keras.layers.Dense(
|
289 |
+
units=self.embed_dim, kernel_initializer=get_initializer(in_proj_std), name="v_proj"
|
290 |
+
)
|
291 |
+
|
292 |
+
self.dropout = keras.layers.Dropout(rate=config.attention_dropout)
|
293 |
+
|
294 |
+
self.out_proj = keras.layers.Dense(
|
295 |
+
units=self.embed_dim, kernel_initializer=get_initializer(out_proj_std), name="out_proj"
|
296 |
+
)
|
297 |
+
|
298 |
+
# copied from transformers.models.bert.modeling_tf_bert.TFBertSelfAttention.transpose_for_scores
|
299 |
+
def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
|
300 |
+
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
|
301 |
+
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
|
302 |
+
|
303 |
+
# 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]
|
304 |
+
return tf.transpose(tensor, perm=[0, 2, 1, 3])
|
305 |
+
|
306 |
+
def call(
|
307 |
+
self,
|
308 |
+
hidden_states: tf.Tensor,
|
309 |
+
attention_mask: tf.Tensor,
|
310 |
+
causal_attention_mask: tf.Tensor,
|
311 |
+
output_attentions: bool,
|
312 |
+
training: bool = False,
|
313 |
+
) -> Tuple[tf.Tensor]:
|
314 |
+
"""Input shape: Batch x Time x Channel"""
|
315 |
+
|
316 |
+
batch_size = shape_list(hidden_states)[0]
|
317 |
+
mixed_query_layer = self.q_proj(inputs=hidden_states)
|
318 |
+
mixed_key_layer = self.k_proj(inputs=hidden_states)
|
319 |
+
mixed_value_layer = self.v_proj(inputs=hidden_states)
|
320 |
+
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
|
321 |
+
key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)
|
322 |
+
value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)
|
323 |
+
|
324 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
325 |
+
# (batch size, num_heads, seq_len_q, seq_len_k)
|
326 |
+
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
|
327 |
+
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
|
328 |
+
attention_scores = tf.divide(attention_scores, dk)
|
329 |
+
|
330 |
+
# apply the causal_attention_mask first
|
331 |
+
if causal_attention_mask is not None:
|
332 |
+
# Apply the causal attention mask (precomputed for all layers in TFCLIPModel call() function)
|
333 |
+
attention_scores = tf.add(attention_scores, causal_attention_mask)
|
334 |
+
|
335 |
+
if attention_mask is not None:
|
336 |
+
# Apply the attention mask (precomputed for all layers in TFCLIPModel call() function)
|
337 |
+
attention_scores = tf.add(attention_scores, attention_mask)
|
338 |
+
|
339 |
+
# Normalize the attention scores to probabilities.
|
340 |
+
_attention_probs = stable_softmax(logits=attention_scores, axis=-1)
|
341 |
+
|
342 |
+
# This is actually dropping out entire tokens to attend to, which might
|
343 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
344 |
+
attention_probs = self.dropout(inputs=_attention_probs, training=training)
|
345 |
+
|
346 |
+
attention_output = tf.matmul(attention_probs, value_layer)
|
347 |
+
attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
|
348 |
+
|
349 |
+
# (batch_size, seq_len_q, embed_dim)
|
350 |
+
attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.embed_dim))
|
351 |
+
|
352 |
+
attention_output = self.out_proj(attention_output, training=training)
|
353 |
+
# In TFBert, attention weights are returned after dropout.
|
354 |
+
# However, in CLIP, they are returned before dropout.
|
355 |
+
outputs = (attention_output, _attention_probs) if output_attentions else (attention_output,)
|
356 |
+
|
357 |
+
return outputs
|
358 |
+
|
359 |
+
def build(self, input_shape=None):
|
360 |
+
if self.built:
|
361 |
+
return
|
362 |
+
self.built = True
|
363 |
+
if getattr(self, "q_proj", None) is not None:
|
364 |
+
with tf.name_scope(self.q_proj.name):
|
365 |
+
self.q_proj.build([None, None, self.embed_dim])
|
366 |
+
if getattr(self, "k_proj", None) is not None:
|
367 |
+
with tf.name_scope(self.k_proj.name):
|
368 |
+
self.k_proj.build([None, None, self.embed_dim])
|
369 |
+
if getattr(self, "v_proj", None) is not None:
|
370 |
+
with tf.name_scope(self.v_proj.name):
|
371 |
+
self.v_proj.build([None, None, self.embed_dim])
|
372 |
+
if getattr(self, "out_proj", None) is not None:
|
373 |
+
with tf.name_scope(self.out_proj.name):
|
374 |
+
self.out_proj.build([None, None, self.embed_dim])
|
375 |
+
|
376 |
+
|
377 |
+
class TFCLIPMLP(keras.layers.Layer):
|
378 |
+
def __init__(self, config: CLIPConfig, **kwargs):
|
379 |
+
super().__init__(**kwargs)
|
380 |
+
|
381 |
+
self.activation_fn = get_tf_activation(config.hidden_act)
|
382 |
+
|
383 |
+
factor = config.initializer_factor
|
384 |
+
in_proj_std = (config.hidden_size**-0.5) * ((2 * config.num_hidden_layers) ** -0.5) * factor
|
385 |
+
fc_std = (2 * config.hidden_size) ** -0.5 * factor
|
386 |
+
|
387 |
+
self.fc1 = keras.layers.Dense(
|
388 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(fc_std), name="fc1"
|
389 |
+
)
|
390 |
+
self.fc2 = keras.layers.Dense(
|
391 |
+
units=config.hidden_size, kernel_initializer=get_initializer(in_proj_std), name="fc2"
|
392 |
+
)
|
393 |
+
self.config = config
|
394 |
+
|
395 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
396 |
+
hidden_states = self.fc1(inputs=hidden_states)
|
397 |
+
hidden_states = self.activation_fn(hidden_states)
|
398 |
+
hidden_states = self.fc2(inputs=hidden_states)
|
399 |
+
return hidden_states
|
400 |
+
|
401 |
+
def build(self, input_shape=None):
|
402 |
+
if self.built:
|
403 |
+
return
|
404 |
+
self.built = True
|
405 |
+
if getattr(self, "fc1", None) is not None:
|
406 |
+
with tf.name_scope(self.fc1.name):
|
407 |
+
self.fc1.build([None, None, self.config.hidden_size])
|
408 |
+
if getattr(self, "fc2", None) is not None:
|
409 |
+
with tf.name_scope(self.fc2.name):
|
410 |
+
self.fc2.build([None, None, self.config.intermediate_size])
|
411 |
+
|
412 |
+
|
413 |
+
class TFCLIPEncoderLayer(keras.layers.Layer):
|
414 |
+
def __init__(self, config: CLIPConfig, **kwargs):
|
415 |
+
super().__init__(**kwargs)
|
416 |
+
|
417 |
+
self.embed_dim = config.hidden_size
|
418 |
+
self.self_attn = TFCLIPAttention(config, name="self_attn")
|
419 |
+
self.layer_norm1 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm1")
|
420 |
+
self.mlp = TFCLIPMLP(config, name="mlp")
|
421 |
+
self.layer_norm2 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm2")
|
422 |
+
|
423 |
+
def call(
|
424 |
+
self,
|
425 |
+
hidden_states: tf.Tensor,
|
426 |
+
attention_mask: tf.Tensor,
|
427 |
+
causal_attention_mask: tf.Tensor,
|
428 |
+
output_attentions: bool,
|
429 |
+
training: bool = False,
|
430 |
+
) -> Tuple[tf.Tensor]:
|
431 |
+
"""
|
432 |
+
Args:
|
433 |
+
hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
434 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
435 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
436 |
+
causal_attention_mask (`tf.Tensor`): causal attention mask of size
|
437 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
438 |
+
output_attentions (`bool`):
|
439 |
+
Whether or not to return the attentions tensors of all attention layers. See `outputs` under returned
|
440 |
+
tensors for more detail.
|
441 |
+
"""
|
442 |
+
residual = hidden_states
|
443 |
+
|
444 |
+
hidden_states = self.layer_norm1(inputs=hidden_states)
|
445 |
+
attention_outputs = self.self_attn(
|
446 |
+
hidden_states=hidden_states,
|
447 |
+
attention_mask=attention_mask,
|
448 |
+
causal_attention_mask=causal_attention_mask,
|
449 |
+
output_attentions=output_attentions,
|
450 |
+
training=training,
|
451 |
+
)
|
452 |
+
hidden_states = attention_outputs[0]
|
453 |
+
hidden_states = residual + hidden_states
|
454 |
+
|
455 |
+
residual = hidden_states
|
456 |
+
hidden_states = self.layer_norm2(inputs=hidden_states)
|
457 |
+
hidden_states = self.mlp(hidden_states=hidden_states)
|
458 |
+
hidden_states = residual + hidden_states
|
459 |
+
|
460 |
+
outputs = (hidden_states,) + attention_outputs[1:] # add attentions if we output them
|
461 |
+
|
462 |
+
return outputs
|
463 |
+
|
464 |
+
def build(self, input_shape=None):
|
465 |
+
if self.built:
|
466 |
+
return
|
467 |
+
self.built = True
|
468 |
+
if getattr(self, "self_attn", None) is not None:
|
469 |
+
with tf.name_scope(self.self_attn.name):
|
470 |
+
self.self_attn.build(None)
|
471 |
+
if getattr(self, "layer_norm1", None) is not None:
|
472 |
+
with tf.name_scope(self.layer_norm1.name):
|
473 |
+
self.layer_norm1.build([None, None, self.embed_dim])
|
474 |
+
if getattr(self, "mlp", None) is not None:
|
475 |
+
with tf.name_scope(self.mlp.name):
|
476 |
+
self.mlp.build(None)
|
477 |
+
if getattr(self, "layer_norm2", None) is not None:
|
478 |
+
with tf.name_scope(self.layer_norm2.name):
|
479 |
+
self.layer_norm2.build([None, None, self.embed_dim])
|
480 |
+
|
481 |
+
|
482 |
+
class TFCLIPEncoder(keras.layers.Layer):
|
483 |
+
"""
|
484 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
485 |
+
[`TFCLIPEncoderLayer`].
|
486 |
+
|
487 |
+
Args:
|
488 |
+
config: CLIPConfig
|
489 |
+
"""
|
490 |
+
|
491 |
+
def __init__(self, config: CLIPConfig, **kwargs):
|
492 |
+
super().__init__(**kwargs)
|
493 |
+
|
494 |
+
self.layers = [TFCLIPEncoderLayer(config, name=f"layers_._{i}") for i in range(config.num_hidden_layers)]
|
495 |
+
|
496 |
+
def call(
|
497 |
+
self,
|
498 |
+
hidden_states: tf.Tensor,
|
499 |
+
attention_mask: tf.Tensor,
|
500 |
+
causal_attention_mask: tf.Tensor,
|
501 |
+
output_attentions: bool,
|
502 |
+
output_hidden_states: bool,
|
503 |
+
return_dict: bool,
|
504 |
+
training: bool = False,
|
505 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
506 |
+
all_hidden_states = () if output_hidden_states else None
|
507 |
+
all_attentions = () if output_attentions else None
|
508 |
+
|
509 |
+
for i, layer_module in enumerate(self.layers):
|
510 |
+
if output_hidden_states:
|
511 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
512 |
+
|
513 |
+
layer_outputs = layer_module(
|
514 |
+
hidden_states=hidden_states,
|
515 |
+
attention_mask=attention_mask,
|
516 |
+
causal_attention_mask=causal_attention_mask,
|
517 |
+
output_attentions=output_attentions,
|
518 |
+
training=training,
|
519 |
+
)
|
520 |
+
hidden_states = layer_outputs[0]
|
521 |
+
|
522 |
+
if output_attentions:
|
523 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
524 |
+
|
525 |
+
# Add last layer
|
526 |
+
if output_hidden_states:
|
527 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
528 |
+
|
529 |
+
if not return_dict:
|
530 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
|
531 |
+
|
532 |
+
return TFBaseModelOutput(
|
533 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
534 |
+
)
|
535 |
+
|
536 |
+
def build(self, input_shape=None):
|
537 |
+
if self.built:
|
538 |
+
return
|
539 |
+
self.built = True
|
540 |
+
if getattr(self, "layers", None) is not None:
|
541 |
+
for layer in self.layers:
|
542 |
+
with tf.name_scope(layer.name):
|
543 |
+
layer.build(None)
|
544 |
+
|
545 |
+
|
546 |
+
class TFCLIPTextTransformer(keras.layers.Layer):
|
547 |
+
def __init__(self, config: CLIPTextConfig, **kwargs):
|
548 |
+
super().__init__(**kwargs)
|
549 |
+
|
550 |
+
self.embeddings = TFCLIPTextEmbeddings(config, name="embeddings")
|
551 |
+
self.encoder = TFCLIPEncoder(config, name="encoder")
|
552 |
+
self.final_layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="final_layer_norm")
|
553 |
+
|
554 |
+
# For `pooled_output` computation
|
555 |
+
self.eos_token_id = config.eos_token_id
|
556 |
+
self.embed_dim = config.hidden_size
|
557 |
+
|
558 |
+
def call(
|
559 |
+
self,
|
560 |
+
input_ids: TFModelInputType,
|
561 |
+
attention_mask: tf.Tensor,
|
562 |
+
position_ids: tf.Tensor,
|
563 |
+
output_attentions: bool,
|
564 |
+
output_hidden_states: bool,
|
565 |
+
return_dict: bool,
|
566 |
+
training: bool = False,
|
567 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
568 |
+
input_shape = shape_list(input_ids)
|
569 |
+
|
570 |
+
embedding_output = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
571 |
+
|
572 |
+
batch_size, seq_length = input_shape
|
573 |
+
# CLIP's text model uses causal mask, prepare it here.
|
574 |
+
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
|
575 |
+
causal_attention_mask = self._build_causal_attention_mask(batch_size, seq_length, dtype=embedding_output.dtype)
|
576 |
+
|
577 |
+
# check attention mask and invert
|
578 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
579 |
+
attention_mask = _expand_mask(attention_mask)
|
580 |
+
|
581 |
+
encoder_outputs = self.encoder(
|
582 |
+
hidden_states=embedding_output,
|
583 |
+
attention_mask=attention_mask,
|
584 |
+
causal_attention_mask=causal_attention_mask,
|
585 |
+
output_attentions=output_attentions,
|
586 |
+
output_hidden_states=output_hidden_states,
|
587 |
+
return_dict=return_dict,
|
588 |
+
training=training,
|
589 |
+
)
|
590 |
+
|
591 |
+
sequence_output = encoder_outputs[0]
|
592 |
+
sequence_output = self.final_layer_norm(inputs=sequence_output)
|
593 |
+
|
594 |
+
if self.eos_token_id == 2:
|
595 |
+
# The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
|
596 |
+
# A CLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added
|
597 |
+
# ------------------------------------------------------------
|
598 |
+
# text_embeds.shape = [batch_size, n_ctx, transformer.width]
|
599 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
600 |
+
pooled_output = tf.gather_nd(
|
601 |
+
params=sequence_output,
|
602 |
+
indices=tf.stack(
|
603 |
+
values=(tf.range(input_shape[0], dtype=tf.int64), tf.math.argmax(input_ids, axis=-1)), axis=1
|
604 |
+
),
|
605 |
+
)
|
606 |
+
else:
|
607 |
+
# The config gets updated `eos_token_id` from PR #24773 (so the use of exta new tokens is possible)
|
608 |
+
pooled_output = tf.gather_nd(
|
609 |
+
params=sequence_output,
|
610 |
+
indices=tf.stack(
|
611 |
+
values=(
|
612 |
+
tf.range(input_shape[0], dtype=tf.int64),
|
613 |
+
tf.math.argmax(tf.cast(input_ids == self.eos_token_id, dtype=tf.int8), axis=-1),
|
614 |
+
),
|
615 |
+
axis=1,
|
616 |
+
),
|
617 |
+
)
|
618 |
+
|
619 |
+
if not return_dict:
|
620 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
621 |
+
|
622 |
+
return TFBaseModelOutputWithPooling(
|
623 |
+
last_hidden_state=sequence_output,
|
624 |
+
pooler_output=pooled_output,
|
625 |
+
hidden_states=encoder_outputs.hidden_states,
|
626 |
+
attentions=encoder_outputs.attentions,
|
627 |
+
)
|
628 |
+
|
629 |
+
def _build_causal_attention_mask(self, batch_size, seq_length, dtype=tf.float32):
|
630 |
+
# It is possible with an unspecified sequence length for seq_length to be
|
631 |
+
# a runtime value, which is unsupported by tf.constant. Per the TensorFlow
|
632 |
+
# docs, tf.fill can handle runtime dynamic shapes:
|
633 |
+
# https://www.tensorflow.org/api_docs/python/tf/fill
|
634 |
+
diag = tf.cast(tf.fill((seq_length,), 0.0), dtype)
|
635 |
+
|
636 |
+
# set an additive 2D attention mask with all places being masked
|
637 |
+
to_mask = tf.cast(tf.fill((seq_length, seq_length), -10000.0), dtype)
|
638 |
+
|
639 |
+
# set diagonal & lower triangular parts to 0 (i.e. the places not to be masked)
|
640 |
+
# TIP: think the 2D matrix as the space of (query_seq, key_seq)
|
641 |
+
to_mask = tf.linalg.band_part(to_mask, 0, -1)
|
642 |
+
# to_mask = tf.linalg.band_part(to_mask, -1, 0)
|
643 |
+
to_mask = tf.linalg.set_diag(to_mask, diagonal=diag)
|
644 |
+
|
645 |
+
return tf.broadcast_to(input=to_mask, shape=(batch_size, 1, seq_length, seq_length))
|
646 |
+
|
647 |
+
def build(self, input_shape=None):
|
648 |
+
if self.built:
|
649 |
+
return
|
650 |
+
self.built = True
|
651 |
+
if getattr(self, "embeddings", None) is not None:
|
652 |
+
with tf.name_scope(self.embeddings.name):
|
653 |
+
self.embeddings.build(None)
|
654 |
+
if getattr(self, "encoder", None) is not None:
|
655 |
+
with tf.name_scope(self.encoder.name):
|
656 |
+
self.encoder.build(None)
|
657 |
+
if getattr(self, "final_layer_norm", None) is not None:
|
658 |
+
with tf.name_scope(self.final_layer_norm.name):
|
659 |
+
self.final_layer_norm.build([None, None, self.embed_dim])
|
660 |
+
|
661 |
+
|
662 |
+
@keras_serializable
|
663 |
+
class TFCLIPTextMainLayer(keras.layers.Layer):
|
664 |
+
config_class = CLIPTextConfig
|
665 |
+
|
666 |
+
def __init__(self, config: CLIPTextConfig, **kwargs):
|
667 |
+
super().__init__(**kwargs)
|
668 |
+
self.config = config
|
669 |
+
self.text_model = TFCLIPTextTransformer(config, name="text_model")
|
670 |
+
|
671 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
672 |
+
return self.text_model.embeddings
|
673 |
+
|
674 |
+
def set_input_embeddings(self, value: tf.Variable):
|
675 |
+
self.text_model.embeddings.weight = value
|
676 |
+
self.text_model.embeddings.vocab_size = shape_list(value)[0]
|
677 |
+
|
678 |
+
@unpack_inputs
|
679 |
+
def call(
|
680 |
+
self,
|
681 |
+
input_ids: TFModelInputType | None = None,
|
682 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
683 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
684 |
+
output_attentions: Optional[bool] = None,
|
685 |
+
output_hidden_states: Optional[bool] = None,
|
686 |
+
return_dict: Optional[bool] = None,
|
687 |
+
training: bool = False,
|
688 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
689 |
+
if input_ids is None:
|
690 |
+
raise ValueError("You have to specify input_ids")
|
691 |
+
|
692 |
+
input_shape = shape_list(input_ids)
|
693 |
+
|
694 |
+
if attention_mask is None:
|
695 |
+
attention_mask = tf.fill(dims=input_shape, value=1)
|
696 |
+
|
697 |
+
text_model_outputs = self.text_model(
|
698 |
+
input_ids=input_ids,
|
699 |
+
attention_mask=attention_mask,
|
700 |
+
position_ids=position_ids,
|
701 |
+
output_attentions=output_attentions,
|
702 |
+
output_hidden_states=output_hidden_states,
|
703 |
+
return_dict=return_dict,
|
704 |
+
training=training,
|
705 |
+
)
|
706 |
+
|
707 |
+
return text_model_outputs
|
708 |
+
|
709 |
+
def build(self, input_shape=None):
|
710 |
+
if self.built:
|
711 |
+
return
|
712 |
+
self.built = True
|
713 |
+
if getattr(self, "text_model", None) is not None:
|
714 |
+
with tf.name_scope(self.text_model.name):
|
715 |
+
self.text_model.build(None)
|
716 |
+
|
717 |
+
|
718 |
+
class TFCLIPVisionTransformer(keras.layers.Layer):
|
719 |
+
def __init__(self, config: CLIPVisionConfig, **kwargs):
|
720 |
+
super().__init__(**kwargs)
|
721 |
+
|
722 |
+
self.embeddings = TFCLIPVisionEmbeddings(config, name="embeddings")
|
723 |
+
self.pre_layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="pre_layrnorm")
|
724 |
+
self.encoder = TFCLIPEncoder(config, name="encoder")
|
725 |
+
self.post_layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="post_layernorm")
|
726 |
+
self.embed_dim = config.hidden_size
|
727 |
+
|
728 |
+
def call(
|
729 |
+
self,
|
730 |
+
pixel_values: TFModelInputType,
|
731 |
+
output_attentions: bool,
|
732 |
+
output_hidden_states: bool,
|
733 |
+
return_dict: bool,
|
734 |
+
training: bool = False,
|
735 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
736 |
+
embedding_output = self.embeddings(pixel_values=pixel_values)
|
737 |
+
embedding_output = self.pre_layernorm(inputs=embedding_output)
|
738 |
+
|
739 |
+
encoder_outputs = self.encoder(
|
740 |
+
hidden_states=embedding_output,
|
741 |
+
attention_mask=None,
|
742 |
+
causal_attention_mask=None,
|
743 |
+
output_attentions=output_attentions,
|
744 |
+
output_hidden_states=output_hidden_states,
|
745 |
+
return_dict=return_dict,
|
746 |
+
training=training,
|
747 |
+
)
|
748 |
+
|
749 |
+
sequence_output = encoder_outputs[0]
|
750 |
+
pooled_output = sequence_output[:, 0, :]
|
751 |
+
pooled_output = self.post_layernorm(inputs=pooled_output)
|
752 |
+
|
753 |
+
if not return_dict:
|
754 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
755 |
+
|
756 |
+
return TFBaseModelOutputWithPooling(
|
757 |
+
last_hidden_state=sequence_output,
|
758 |
+
pooler_output=pooled_output,
|
759 |
+
hidden_states=encoder_outputs.hidden_states,
|
760 |
+
attentions=encoder_outputs.attentions,
|
761 |
+
)
|
762 |
+
|
763 |
+
def build(self, input_shape=None):
|
764 |
+
if self.built:
|
765 |
+
return
|
766 |
+
self.built = True
|
767 |
+
if getattr(self, "embeddings", None) is not None:
|
768 |
+
with tf.name_scope(self.embeddings.name):
|
769 |
+
self.embeddings.build(None)
|
770 |
+
if getattr(self, "pre_layernorm", None) is not None:
|
771 |
+
with tf.name_scope(self.pre_layernorm.name):
|
772 |
+
self.pre_layernorm.build([None, None, self.embed_dim])
|
773 |
+
if getattr(self, "encoder", None) is not None:
|
774 |
+
with tf.name_scope(self.encoder.name):
|
775 |
+
self.encoder.build(None)
|
776 |
+
if getattr(self, "post_layernorm", None) is not None:
|
777 |
+
with tf.name_scope(self.post_layernorm.name):
|
778 |
+
self.post_layernorm.build([None, self.embed_dim])
|
779 |
+
|
780 |
+
|
781 |
+
@keras_serializable
|
782 |
+
class TFCLIPVisionMainLayer(keras.layers.Layer):
|
783 |
+
config_class = CLIPVisionConfig
|
784 |
+
|
785 |
+
def __init__(self, config: CLIPVisionConfig, **kwargs):
|
786 |
+
super().__init__(**kwargs)
|
787 |
+
self.config = config
|
788 |
+
self.vision_model = TFCLIPVisionTransformer(config, name="vision_model")
|
789 |
+
|
790 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
791 |
+
return self.vision_model.embeddings
|
792 |
+
|
793 |
+
@unpack_inputs
|
794 |
+
def call(
|
795 |
+
self,
|
796 |
+
pixel_values: TFModelInputType | None = None,
|
797 |
+
output_attentions: Optional[bool] = None,
|
798 |
+
output_hidden_states: Optional[bool] = None,
|
799 |
+
return_dict: Optional[bool] = None,
|
800 |
+
training: bool = False,
|
801 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
802 |
+
if pixel_values is None:
|
803 |
+
raise ValueError("You have to specify pixel_values")
|
804 |
+
|
805 |
+
vision_model_outputs = self.vision_model(
|
806 |
+
pixel_values=pixel_values,
|
807 |
+
output_attentions=output_attentions,
|
808 |
+
output_hidden_states=output_hidden_states,
|
809 |
+
return_dict=return_dict,
|
810 |
+
training=training,
|
811 |
+
)
|
812 |
+
|
813 |
+
return vision_model_outputs
|
814 |
+
|
815 |
+
def build(self, input_shape=None):
|
816 |
+
if self.built:
|
817 |
+
return
|
818 |
+
self.built = True
|
819 |
+
if getattr(self, "vision_model", None) is not None:
|
820 |
+
with tf.name_scope(self.vision_model.name):
|
821 |
+
self.vision_model.build(None)
|
822 |
+
|
823 |
+
|
824 |
+
@keras_serializable
|
825 |
+
class TFCLIPMainLayer(keras.layers.Layer):
|
826 |
+
config_class = CLIPConfig
|
827 |
+
|
828 |
+
def __init__(self, config: CLIPConfig, **kwargs):
|
829 |
+
super().__init__(**kwargs)
|
830 |
+
|
831 |
+
if not isinstance(config.text_config, CLIPTextConfig):
|
832 |
+
raise ValueError(
|
833 |
+
"config.text_config is expected to be of type CLIPTextConfig but is of type"
|
834 |
+
f" {type(config.text_config)}."
|
835 |
+
)
|
836 |
+
|
837 |
+
if not isinstance(config.vision_config, CLIPVisionConfig):
|
838 |
+
raise ValueError(
|
839 |
+
"config.vision_config is expected to be of type CLIPVisionConfig but is of type"
|
840 |
+
f" {type(config.vision_config)}."
|
841 |
+
)
|
842 |
+
|
843 |
+
self.config = config
|
844 |
+
|
845 |
+
text_config = config.text_config
|
846 |
+
vision_config = config.vision_config
|
847 |
+
|
848 |
+
self.projection_dim = config.projection_dim
|
849 |
+
|
850 |
+
self.text_model = TFCLIPTextTransformer(text_config, name="text_model")
|
851 |
+
self.vision_model = TFCLIPVisionTransformer(vision_config, name="vision_model")
|
852 |
+
|
853 |
+
self.visual_projection = keras.layers.Dense(
|
854 |
+
units=self.projection_dim,
|
855 |
+
kernel_initializer=get_initializer(vision_config.hidden_size**-0.5 * self.config.initializer_factor),
|
856 |
+
use_bias=False,
|
857 |
+
name="visual_projection",
|
858 |
+
)
|
859 |
+
|
860 |
+
self.text_projection = keras.layers.Dense(
|
861 |
+
units=self.projection_dim,
|
862 |
+
kernel_initializer=get_initializer(text_config.hidden_size**-0.5 * self.config.initializer_factor),
|
863 |
+
use_bias=False,
|
864 |
+
name="text_projection",
|
865 |
+
)
|
866 |
+
self.text_embed_dim = text_config.hidden_size
|
867 |
+
self.vision_embed_dim = vision_config.hidden_size
|
868 |
+
|
869 |
+
def build(self, input_shape: tf.TensorShape = None):
|
870 |
+
self.logit_scale = self.add_weight(
|
871 |
+
shape=(1,),
|
872 |
+
initializer=keras.initializers.Constant(self.config.logit_scale_init_value),
|
873 |
+
trainable=True,
|
874 |
+
name="logit_scale",
|
875 |
+
)
|
876 |
+
|
877 |
+
if self.built:
|
878 |
+
return
|
879 |
+
self.built = True
|
880 |
+
if getattr(self, "text_model", None) is not None:
|
881 |
+
with tf.name_scope(self.text_model.name):
|
882 |
+
self.text_model.build(None)
|
883 |
+
if getattr(self, "vision_model", None) is not None:
|
884 |
+
with tf.name_scope(self.vision_model.name):
|
885 |
+
self.vision_model.build(None)
|
886 |
+
if getattr(self, "visual_projection", None) is not None:
|
887 |
+
with tf.name_scope(self.visual_projection.name):
|
888 |
+
self.visual_projection.build([None, None, self.vision_embed_dim])
|
889 |
+
if getattr(self, "text_projection", None) is not None:
|
890 |
+
with tf.name_scope(self.text_projection.name):
|
891 |
+
self.text_projection.build([None, None, self.text_embed_dim])
|
892 |
+
|
893 |
+
@unpack_inputs
|
894 |
+
def get_text_features(
|
895 |
+
self,
|
896 |
+
input_ids: TFModelInputType | None = None,
|
897 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
898 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
899 |
+
output_attentions: Optional[bool] = None,
|
900 |
+
output_hidden_states: Optional[bool] = None,
|
901 |
+
return_dict: Optional[bool] = None,
|
902 |
+
training: bool = False,
|
903 |
+
) -> tf.Tensor:
|
904 |
+
if input_ids is None:
|
905 |
+
raise ValueError("You have to specify either input_ids")
|
906 |
+
|
907 |
+
input_shape = shape_list(input_ids)
|
908 |
+
|
909 |
+
if attention_mask is None:
|
910 |
+
attention_mask = tf.fill(dims=input_shape, value=1)
|
911 |
+
|
912 |
+
text_outputs = self.text_model(
|
913 |
+
input_ids=input_ids,
|
914 |
+
attention_mask=attention_mask,
|
915 |
+
position_ids=position_ids,
|
916 |
+
output_attentions=output_attentions,
|
917 |
+
output_hidden_states=output_hidden_states,
|
918 |
+
return_dict=return_dict,
|
919 |
+
training=training,
|
920 |
+
)
|
921 |
+
|
922 |
+
pooled_output = text_outputs[1]
|
923 |
+
text_features = self.text_projection(inputs=pooled_output)
|
924 |
+
|
925 |
+
return text_features
|
926 |
+
|
927 |
+
@unpack_inputs
|
928 |
+
def get_image_features(
|
929 |
+
self,
|
930 |
+
pixel_values: TFModelInputType | None = None,
|
931 |
+
output_attentions: Optional[bool] = None,
|
932 |
+
output_hidden_states: Optional[bool] = None,
|
933 |
+
return_dict: Optional[bool] = None,
|
934 |
+
training: bool = False,
|
935 |
+
) -> tf.Tensor:
|
936 |
+
if pixel_values is None:
|
937 |
+
raise ValueError("You have to specify pixel_values")
|
938 |
+
|
939 |
+
vision_outputs = self.vision_model(
|
940 |
+
pixel_values=pixel_values,
|
941 |
+
output_attentions=output_attentions,
|
942 |
+
output_hidden_states=output_hidden_states,
|
943 |
+
return_dict=return_dict,
|
944 |
+
training=training,
|
945 |
+
)
|
946 |
+
|
947 |
+
pooled_output = vision_outputs[1] # pooled_output
|
948 |
+
image_features = self.visual_projection(inputs=pooled_output)
|
949 |
+
|
950 |
+
return image_features
|
951 |
+
|
952 |
+
@unpack_inputs
|
953 |
+
def call(
|
954 |
+
self,
|
955 |
+
input_ids: TFModelInputType | None = None,
|
956 |
+
pixel_values: TFModelInputType | None = None,
|
957 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
958 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
959 |
+
return_loss: Optional[bool] = None,
|
960 |
+
output_attentions: Optional[bool] = None,
|
961 |
+
output_hidden_states: Optional[bool] = None,
|
962 |
+
return_dict: Optional[bool] = None,
|
963 |
+
training: bool = False,
|
964 |
+
) -> Union[TFCLIPOutput, Tuple[tf.Tensor]]:
|
965 |
+
if input_ids is None:
|
966 |
+
raise ValueError("You have to specify either input_ids")
|
967 |
+
if pixel_values is None:
|
968 |
+
raise ValueError("You have to specify pixel_values")
|
969 |
+
|
970 |
+
input_shape = shape_list(input_ids)
|
971 |
+
|
972 |
+
if attention_mask is None:
|
973 |
+
attention_mask = tf.fill(dims=input_shape, value=1)
|
974 |
+
|
975 |
+
vision_outputs = self.vision_model(
|
976 |
+
pixel_values=pixel_values,
|
977 |
+
output_attentions=output_attentions,
|
978 |
+
output_hidden_states=output_hidden_states,
|
979 |
+
return_dict=return_dict,
|
980 |
+
training=training,
|
981 |
+
)
|
982 |
+
|
983 |
+
text_outputs = self.text_model(
|
984 |
+
input_ids=input_ids,
|
985 |
+
attention_mask=attention_mask,
|
986 |
+
position_ids=position_ids,
|
987 |
+
output_attentions=output_attentions,
|
988 |
+
output_hidden_states=output_hidden_states,
|
989 |
+
return_dict=return_dict,
|
990 |
+
training=training,
|
991 |
+
)
|
992 |
+
|
993 |
+
image_embeds = vision_outputs[1]
|
994 |
+
image_embeds = self.visual_projection(inputs=image_embeds)
|
995 |
+
|
996 |
+
text_embeds = text_outputs[1]
|
997 |
+
text_embeds = self.text_projection(inputs=text_embeds)
|
998 |
+
|
999 |
+
# normalized features
|
1000 |
+
image_embeds = image_embeds / tf.norm(tensor=image_embeds, ord="euclidean", axis=-1, keepdims=True)
|
1001 |
+
text_embeds = text_embeds / tf.norm(tensor=text_embeds, ord="euclidean", axis=-1, keepdims=True)
|
1002 |
+
|
1003 |
+
# cosine similarity as logits
|
1004 |
+
logit_scale = tf.math.exp(self.logit_scale)
|
1005 |
+
logits_per_text = tf.matmul(text_embeds, image_embeds, transpose_b=True) * logit_scale
|
1006 |
+
logits_per_image = tf.transpose(logits_per_text)
|
1007 |
+
|
1008 |
+
loss = None
|
1009 |
+
if return_loss:
|
1010 |
+
loss = clip_loss(logits_per_text)
|
1011 |
+
loss = tf.reshape(loss, (1,))
|
1012 |
+
|
1013 |
+
if not return_dict:
|
1014 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
1015 |
+
return (loss,) + output if loss is not None else output
|
1016 |
+
|
1017 |
+
return TFCLIPOutput(
|
1018 |
+
loss=loss,
|
1019 |
+
logits_per_image=logits_per_image,
|
1020 |
+
logits_per_text=logits_per_text,
|
1021 |
+
text_embeds=text_embeds,
|
1022 |
+
image_embeds=image_embeds,
|
1023 |
+
text_model_output=text_outputs,
|
1024 |
+
vision_model_output=vision_outputs,
|
1025 |
+
)
|
1026 |
+
|
1027 |
+
|
1028 |
+
class TFCLIPPreTrainedModel(TFPreTrainedModel):
|
1029 |
+
"""
|
1030 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
1031 |
+
models.
|
1032 |
+
"""
|
1033 |
+
|
1034 |
+
config_class = CLIPConfig
|
1035 |
+
base_model_prefix = "clip"
|
1036 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
1037 |
+
_keys_to_ignore_on_load_unexpected = [r"position_ids"]
|
1038 |
+
|
1039 |
+
|
1040 |
+
CLIP_START_DOCSTRING = r"""
|
1041 |
+
|
1042 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
1043 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
1044 |
+
etc.)
|
1045 |
+
|
1046 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
1047 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
1048 |
+
behavior.
|
1049 |
+
|
1050 |
+
<Tip>
|
1051 |
+
|
1052 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
1053 |
+
|
1054 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
1055 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
1056 |
+
|
1057 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
1058 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
1059 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
1060 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
1061 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
1062 |
+
positional argument:
|
1063 |
+
|
1064 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
1065 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
1066 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
1067 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
1068 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
1069 |
+
|
1070 |
+
Note that when creating models and layers with
|
1071 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
1072 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
1073 |
+
|
1074 |
+
</Tip>
|
1075 |
+
|
1076 |
+
Args:
|
1077 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
1078 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
1079 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
1080 |
+
"""
|
1081 |
+
|
1082 |
+
CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
1083 |
+
Args:
|
1084 |
+
input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
|
1085 |
+
Indices of input sequence tokens in the vocabulary.
|
1086 |
+
|
1087 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
1088 |
+
[`PreTrainedTokenizer.encode`] for details.
|
1089 |
+
|
1090 |
+
[What are input IDs?](../glossary#input-ids)
|
1091 |
+
attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
1092 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1093 |
+
|
1094 |
+
- 1 for tokens that are **not masked**,
|
1095 |
+
- 0 for tokens that are **masked**.
|
1096 |
+
|
1097 |
+
[What are attention masks?](../glossary#attention-mask)
|
1098 |
+
position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
1099 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1100 |
+
config.max_position_embeddings - 1]`.
|
1101 |
+
|
1102 |
+
[What are position IDs?](../glossary#position-ids)
|
1103 |
+
output_attentions (`bool`, *optional*):
|
1104 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1105 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
1106 |
+
config will be used instead.
|
1107 |
+
output_hidden_states (`bool`, *optional*):
|
1108 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1109 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
1110 |
+
used instead.
|
1111 |
+
return_dict (`bool`, *optional*):
|
1112 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
1113 |
+
eager mode, in graph mode the value will always be set to True.
|
1114 |
+
training (`bool`, *optional*, defaults to `False``):
|
1115 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
1116 |
+
behaviors between training and evaluation).
|
1117 |
+
"""
|
1118 |
+
|
1119 |
+
CLIP_VISION_INPUTS_DOCSTRING = r"""
|
1120 |
+
Args:
|
1121 |
+
pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
|
1122 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
1123 |
+
[`CLIPImageProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to
|
1124 |
+
return the attentions tensors of all attention layers. See `attentions` under returned tensors for more
|
1125 |
+
detail. This argument can be used only in eager mode, in graph mode the value in the config will be used
|
1126 |
+
instead.
|
1127 |
+
output_hidden_states (`bool`, *optional*):
|
1128 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1129 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
1130 |
+
used instead.
|
1131 |
+
return_dict (`bool`, *optional*):
|
1132 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
1133 |
+
eager mode, in graph mode the value will always be set to True.
|
1134 |
+
training (`bool`, *optional*, defaults to `False``):
|
1135 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
1136 |
+
behaviors between training and evaluation).
|
1137 |
+
"""
|
1138 |
+
|
1139 |
+
CLIP_INPUTS_DOCSTRING = r"""
|
1140 |
+
Args:
|
1141 |
+
input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
|
1142 |
+
Indices of input sequence tokens in the vocabulary.
|
1143 |
+
|
1144 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
1145 |
+
[`PreTrainedTokenizer.encode`] for details.
|
1146 |
+
|
1147 |
+
[What are input IDs?](../glossary#input-ids)
|
1148 |
+
pixel_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` `Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `(batch_size, num_channels, height, width)`):
|
1149 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
1150 |
+
[`CLIPImageProcessor.__call__`] for details.
|
1151 |
+
attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
1152 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1153 |
+
|
1154 |
+
- 1 for tokens that are **not masked**,
|
1155 |
+
- 0 for tokens that are **masked**.
|
1156 |
+
|
1157 |
+
[What are attention masks?](../glossary#attention-mask)
|
1158 |
+
position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
1159 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1160 |
+
config.max_position_embeddings - 1]`.
|
1161 |
+
|
1162 |
+
[What are position IDs?](../glossary#position-ids)
|
1163 |
+
return_loss (`bool`, *optional*):
|
1164 |
+
Whether or not to return the contrastive loss.
|
1165 |
+
output_attentions (`bool`, *optional*):
|
1166 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1167 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
1168 |
+
config will be used instead.
|
1169 |
+
output_hidden_states (`bool`, *optional*):
|
1170 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1171 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
1172 |
+
used instead.
|
1173 |
+
return_dict (`bool`, *optional*):
|
1174 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
1175 |
+
eager mode, in graph mode the value will always be set to True.
|
1176 |
+
training (`bool`, *optional*, defaults to `False``):
|
1177 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
1178 |
+
behaviors between training and evaluation).
|
1179 |
+
"""
|
1180 |
+
|
1181 |
+
|
1182 |
+
class TFCLIPTextModel(TFCLIPPreTrainedModel):
|
1183 |
+
config_class = CLIPTextConfig
|
1184 |
+
|
1185 |
+
def __init__(self, config: CLIPTextConfig, *inputs, **kwargs):
|
1186 |
+
super().__init__(config, *inputs, **kwargs)
|
1187 |
+
|
1188 |
+
self.clip = TFCLIPTextMainLayer(config, name="clip")
|
1189 |
+
|
1190 |
+
@unpack_inputs
|
1191 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1192 |
+
@replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=CLIPTextConfig)
|
1193 |
+
def call(
|
1194 |
+
self,
|
1195 |
+
input_ids: TFModelInputType | None = None,
|
1196 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1197 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1198 |
+
output_attentions: Optional[bool] = None,
|
1199 |
+
output_hidden_states: Optional[bool] = None,
|
1200 |
+
return_dict: Optional[bool] = None,
|
1201 |
+
training: Optional[bool] = False,
|
1202 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
1203 |
+
r"""
|
1204 |
+
Returns:
|
1205 |
+
|
1206 |
+
Examples:
|
1207 |
+
|
1208 |
+
```python
|
1209 |
+
>>> from transformers import AutoTokenizer, TFCLIPTextModel
|
1210 |
+
|
1211 |
+
>>> model = TFCLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
|
1212 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
1213 |
+
|
1214 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")
|
1215 |
+
|
1216 |
+
>>> outputs = model(**inputs)
|
1217 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
1218 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
1219 |
+
```"""
|
1220 |
+
|
1221 |
+
outputs = self.clip(
|
1222 |
+
input_ids=input_ids,
|
1223 |
+
attention_mask=attention_mask,
|
1224 |
+
position_ids=position_ids,
|
1225 |
+
output_attentions=output_attentions,
|
1226 |
+
output_hidden_states=output_hidden_states,
|
1227 |
+
return_dict=return_dict,
|
1228 |
+
training=training,
|
1229 |
+
)
|
1230 |
+
|
1231 |
+
return outputs
|
1232 |
+
|
1233 |
+
def build(self, input_shape=None):
|
1234 |
+
if self.built:
|
1235 |
+
return
|
1236 |
+
self.built = True
|
1237 |
+
if getattr(self, "clip", None) is not None:
|
1238 |
+
with tf.name_scope(self.clip.name):
|
1239 |
+
self.clip.build(None)
|
1240 |
+
|
1241 |
+
|
1242 |
+
class TFCLIPVisionModel(TFCLIPPreTrainedModel):
|
1243 |
+
config_class = CLIPVisionConfig
|
1244 |
+
main_input_name = "pixel_values"
|
1245 |
+
|
1246 |
+
def __init__(self, config: CLIPVisionConfig, *inputs, **kwargs):
|
1247 |
+
super().__init__(config, *inputs, **kwargs)
|
1248 |
+
|
1249 |
+
self.clip = TFCLIPVisionMainLayer(config, name="clip")
|
1250 |
+
|
1251 |
+
@unpack_inputs
|
1252 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
1253 |
+
@replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=CLIPVisionConfig)
|
1254 |
+
def call(
|
1255 |
+
self,
|
1256 |
+
pixel_values: TFModelInputType | None = None,
|
1257 |
+
output_attentions: Optional[bool] = None,
|
1258 |
+
output_hidden_states: Optional[bool] = None,
|
1259 |
+
return_dict: Optional[bool] = None,
|
1260 |
+
training: Optional[bool] = False,
|
1261 |
+
) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]:
|
1262 |
+
r"""
|
1263 |
+
Returns:
|
1264 |
+
|
1265 |
+
Examples:
|
1266 |
+
|
1267 |
+
```python
|
1268 |
+
>>> from PIL import Image
|
1269 |
+
>>> import requests
|
1270 |
+
>>> from transformers import AutoProcessor, TFCLIPVisionModel
|
1271 |
+
|
1272 |
+
>>> model = TFCLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
|
1273 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1274 |
+
|
1275 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1276 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1277 |
+
|
1278 |
+
>>> inputs = processor(images=image, return_tensors="tf")
|
1279 |
+
|
1280 |
+
>>> outputs = model(**inputs)
|
1281 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
1282 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
1283 |
+
```"""
|
1284 |
+
|
1285 |
+
outputs = self.clip(
|
1286 |
+
pixel_values=pixel_values,
|
1287 |
+
output_attentions=output_attentions,
|
1288 |
+
output_hidden_states=output_hidden_states,
|
1289 |
+
return_dict=return_dict,
|
1290 |
+
training=training,
|
1291 |
+
)
|
1292 |
+
|
1293 |
+
return outputs
|
1294 |
+
|
1295 |
+
def build(self, input_shape=None):
|
1296 |
+
if self.built:
|
1297 |
+
return
|
1298 |
+
self.built = True
|
1299 |
+
if getattr(self, "clip", None) is not None:
|
1300 |
+
with tf.name_scope(self.clip.name):
|
1301 |
+
self.clip.build(None)
|
1302 |
+
|
1303 |
+
|
1304 |
+
@add_start_docstrings(CLIP_START_DOCSTRING)
|
1305 |
+
class TFCLIPModel(TFCLIPPreTrainedModel):
|
1306 |
+
config_class = CLIPConfig
|
1307 |
+
|
1308 |
+
def __init__(self, config: CLIPConfig, *inputs, **kwargs):
|
1309 |
+
super().__init__(config, *inputs, **kwargs)
|
1310 |
+
|
1311 |
+
self.clip = TFCLIPMainLayer(config, name="clip")
|
1312 |
+
|
1313 |
+
@unpack_inputs
|
1314 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1315 |
+
def get_text_features(
|
1316 |
+
self,
|
1317 |
+
input_ids: TFModelInputType | None = None,
|
1318 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1319 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1320 |
+
output_attentions: Optional[bool] = None,
|
1321 |
+
output_hidden_states: Optional[bool] = None,
|
1322 |
+
return_dict: Optional[bool] = None,
|
1323 |
+
training: bool = False,
|
1324 |
+
) -> tf.Tensor:
|
1325 |
+
r"""
|
1326 |
+
Returns:
|
1327 |
+
text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
|
1328 |
+
the projection layer to the pooled output of [`TFCLIPTextModel`].
|
1329 |
+
|
1330 |
+
Examples:
|
1331 |
+
|
1332 |
+
```python
|
1333 |
+
>>> from transformers import AutoTokenizer, TFCLIPModel
|
1334 |
+
|
1335 |
+
>>> model = TFCLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1336 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
1337 |
+
|
1338 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")
|
1339 |
+
>>> text_features = model.get_text_features(**inputs)
|
1340 |
+
```"""
|
1341 |
+
|
1342 |
+
text_features = self.clip.get_text_features(
|
1343 |
+
input_ids=input_ids,
|
1344 |
+
attention_mask=attention_mask,
|
1345 |
+
position_ids=position_ids,
|
1346 |
+
output_attentions=output_attentions,
|
1347 |
+
output_hidden_states=output_hidden_states,
|
1348 |
+
return_dict=return_dict,
|
1349 |
+
)
|
1350 |
+
|
1351 |
+
return text_features
|
1352 |
+
|
1353 |
+
@unpack_inputs
|
1354 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
1355 |
+
def get_image_features(
|
1356 |
+
self,
|
1357 |
+
pixel_values: TFModelInputType | None = None,
|
1358 |
+
output_attentions: Optional[bool] = None,
|
1359 |
+
output_hidden_states: Optional[bool] = None,
|
1360 |
+
return_dict: Optional[bool] = None,
|
1361 |
+
training: bool = False,
|
1362 |
+
) -> tf.Tensor:
|
1363 |
+
r"""
|
1364 |
+
Returns:
|
1365 |
+
image_features (`tf.Tensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying
|
1366 |
+
the projection layer to the pooled output of [`TFCLIPVisionModel`].
|
1367 |
+
|
1368 |
+
Examples:
|
1369 |
+
|
1370 |
+
```python
|
1371 |
+
>>> from PIL import Image
|
1372 |
+
>>> import requests
|
1373 |
+
>>> from transformers import AutoProcessor, TFCLIPModel
|
1374 |
+
|
1375 |
+
>>> model = TFCLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1376 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1377 |
+
|
1378 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1379 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1380 |
+
|
1381 |
+
>>> inputs = processor(images=image, return_tensors="tf")
|
1382 |
+
|
1383 |
+
>>> image_features = model.get_image_features(**inputs)
|
1384 |
+
```"""
|
1385 |
+
|
1386 |
+
image_features = self.clip.get_image_features(
|
1387 |
+
pixel_values=pixel_values,
|
1388 |
+
output_attentions=output_attentions,
|
1389 |
+
output_hidden_states=output_hidden_states,
|
1390 |
+
return_dict=return_dict,
|
1391 |
+
)
|
1392 |
+
|
1393 |
+
return image_features
|
1394 |
+
|
1395 |
+
@unpack_inputs
|
1396 |
+
@add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1397 |
+
@replace_return_docstrings(output_type=TFCLIPOutput, config_class=CLIPConfig)
|
1398 |
+
def call(
|
1399 |
+
self,
|
1400 |
+
input_ids: TFModelInputType | None = None,
|
1401 |
+
pixel_values: TFModelInputType | None = None,
|
1402 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1403 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1404 |
+
return_loss: Optional[bool] = None,
|
1405 |
+
output_attentions: Optional[bool] = None,
|
1406 |
+
output_hidden_states: Optional[bool] = None,
|
1407 |
+
return_dict: Optional[bool] = None,
|
1408 |
+
training: bool = False,
|
1409 |
+
) -> Union[TFCLIPOutput, Tuple[tf.Tensor]]:
|
1410 |
+
r"""
|
1411 |
+
Returns:
|
1412 |
+
|
1413 |
+
Examples:
|
1414 |
+
|
1415 |
+
```python
|
1416 |
+
>>> import tensorflow as tf
|
1417 |
+
>>> from PIL import Image
|
1418 |
+
>>> import requests
|
1419 |
+
>>> from transformers import AutoProcessor, TFCLIPModel
|
1420 |
+
|
1421 |
+
>>> model = TFCLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
1422 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
1423 |
+
|
1424 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
1425 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
1426 |
+
|
1427 |
+
>>> inputs = processor(
|
1428 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="tf", padding=True
|
1429 |
+
... )
|
1430 |
+
|
1431 |
+
>>> outputs = model(**inputs)
|
1432 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
1433 |
+
>>> probs = tf.nn.softmax(logits_per_image, axis=1) # we can take the softmax to get the label probabilities
|
1434 |
+
```"""
|
1435 |
+
|
1436 |
+
outputs = self.clip(
|
1437 |
+
input_ids=input_ids,
|
1438 |
+
pixel_values=pixel_values,
|
1439 |
+
attention_mask=attention_mask,
|
1440 |
+
position_ids=position_ids,
|
1441 |
+
return_loss=return_loss,
|
1442 |
+
output_attentions=output_attentions,
|
1443 |
+
output_hidden_states=output_hidden_states,
|
1444 |
+
return_dict=return_dict,
|
1445 |
+
)
|
1446 |
+
|
1447 |
+
return outputs
|
1448 |
+
|
1449 |
+
def serving_output(self, output: TFCLIPOutput) -> TFCLIPOutput:
|
1450 |
+
# TODO: As is this currently fails with saved_model=True, because
|
1451 |
+
# TensorFlow cannot trace through nested dataclasses. Reference:
|
1452 |
+
# https://github.com/huggingface/transformers/pull/16886
|
1453 |
+
return output
|
1454 |
+
|
1455 |
+
def build(self, input_shape=None):
|
1456 |
+
if self.built:
|
1457 |
+
return
|
1458 |
+
self.built = True
|
1459 |
+
if getattr(self, "clip", None) is not None:
|
1460 |
+
with tf.name_scope(self.clip.name):
|
1461 |
+
self.clip.build(None)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/processing_clip.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""
|
16 |
+
Image/Text processor class for CLIP
|
17 |
+
"""
|
18 |
+
|
19 |
+
import warnings
|
20 |
+
|
21 |
+
from ...processing_utils import ProcessorMixin
|
22 |
+
from ...tokenization_utils_base import BatchEncoding
|
23 |
+
|
24 |
+
|
25 |
+
class CLIPProcessor(ProcessorMixin):
|
26 |
+
r"""
|
27 |
+
Constructs a CLIP processor which wraps a CLIP image processor and a CLIP tokenizer into a single processor.
|
28 |
+
|
29 |
+
[`CLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`CLIPTokenizerFast`]. See the
|
30 |
+
[`~CLIPProcessor.__call__`] and [`~CLIPProcessor.decode`] for more information.
|
31 |
+
|
32 |
+
Args:
|
33 |
+
image_processor ([`CLIPImageProcessor`], *optional*):
|
34 |
+
The image processor is a required input.
|
35 |
+
tokenizer ([`CLIPTokenizerFast`], *optional*):
|
36 |
+
The tokenizer is a required input.
|
37 |
+
"""
|
38 |
+
|
39 |
+
attributes = ["image_processor", "tokenizer"]
|
40 |
+
image_processor_class = "CLIPImageProcessor"
|
41 |
+
tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")
|
42 |
+
|
43 |
+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
|
44 |
+
feature_extractor = None
|
45 |
+
if "feature_extractor" in kwargs:
|
46 |
+
warnings.warn(
|
47 |
+
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
|
48 |
+
" instead.",
|
49 |
+
FutureWarning,
|
50 |
+
)
|
51 |
+
feature_extractor = kwargs.pop("feature_extractor")
|
52 |
+
|
53 |
+
image_processor = image_processor if image_processor is not None else feature_extractor
|
54 |
+
if image_processor is None:
|
55 |
+
raise ValueError("You need to specify an `image_processor`.")
|
56 |
+
if tokenizer is None:
|
57 |
+
raise ValueError("You need to specify a `tokenizer`.")
|
58 |
+
|
59 |
+
super().__init__(image_processor, tokenizer)
|
60 |
+
|
61 |
+
def __call__(self, text=None, images=None, return_tensors=None, **kwargs):
|
62 |
+
"""
|
63 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
64 |
+
and `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode
|
65 |
+
the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
66 |
+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
|
67 |
+
of the above two methods for more information.
|
68 |
+
|
69 |
+
Args:
|
70 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
71 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
72 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
73 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
74 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
75 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
76 |
+
tensor. Both channels-first and channels-last formats are supported.
|
77 |
+
|
78 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
79 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
80 |
+
|
81 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
82 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
83 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
84 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
85 |
+
|
86 |
+
Returns:
|
87 |
+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
|
88 |
+
|
89 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
90 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
91 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
92 |
+
`None`).
|
93 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
94 |
+
"""
|
95 |
+
tokenizer_kwargs, image_processor_kwargs = {}, {}
|
96 |
+
if kwargs:
|
97 |
+
tokenizer_kwargs = {k: v for k, v in kwargs.items() if k not in self.image_processor._valid_processor_keys}
|
98 |
+
image_processor_kwargs = {
|
99 |
+
k: v for k, v in kwargs.items() if k in self.image_processor._valid_processor_keys
|
100 |
+
}
|
101 |
+
|
102 |
+
if text is None and images is None:
|
103 |
+
raise ValueError("You have to specify either text or images. Both cannot be none.")
|
104 |
+
|
105 |
+
if text is not None:
|
106 |
+
encoding = self.tokenizer(text, return_tensors=return_tensors, **tokenizer_kwargs)
|
107 |
+
|
108 |
+
if images is not None:
|
109 |
+
image_features = self.image_processor(images, return_tensors=return_tensors, **image_processor_kwargs)
|
110 |
+
|
111 |
+
if text is not None and images is not None:
|
112 |
+
encoding["pixel_values"] = image_features.pixel_values
|
113 |
+
return encoding
|
114 |
+
elif text is not None:
|
115 |
+
return encoding
|
116 |
+
else:
|
117 |
+
return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
|
118 |
+
|
119 |
+
def batch_decode(self, *args, **kwargs):
|
120 |
+
"""
|
121 |
+
This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
122 |
+
refer to the docstring of this method for more information.
|
123 |
+
"""
|
124 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
125 |
+
|
126 |
+
def decode(self, *args, **kwargs):
|
127 |
+
"""
|
128 |
+
This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
129 |
+
the docstring of this method for more information.
|
130 |
+
"""
|
131 |
+
return self.tokenizer.decode(*args, **kwargs)
|
132 |
+
|
133 |
+
@property
|
134 |
+
def model_input_names(self):
|
135 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
136 |
+
image_processor_input_names = self.image_processor.model_input_names
|
137 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
138 |
+
|
139 |
+
@property
|
140 |
+
def feature_extractor_class(self):
|
141 |
+
warnings.warn(
|
142 |
+
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
|
143 |
+
FutureWarning,
|
144 |
+
)
|
145 |
+
return self.image_processor_class
|
146 |
+
|
147 |
+
@property
|
148 |
+
def feature_extractor(self):
|
149 |
+
warnings.warn(
|
150 |
+
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
|
151 |
+
FutureWarning,
|
152 |
+
)
|
153 |
+
return self.image_processor
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/tokenization_clip.py
ADDED
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The Open AI Team 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 CLIP."""
|
16 |
+
|
17 |
+
import json
|
18 |
+
import os
|
19 |
+
import unicodedata
|
20 |
+
from functools import lru_cache
|
21 |
+
from typing import List, Optional, Tuple
|
22 |
+
|
23 |
+
import regex as re
|
24 |
+
|
25 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
|
26 |
+
from ...utils import logging
|
27 |
+
|
28 |
+
|
29 |
+
logger = logging.get_logger(__name__)
|
30 |
+
|
31 |
+
VOCAB_FILES_NAMES = {
|
32 |
+
"vocab_file": "vocab.json",
|
33 |
+
"merges_file": "merges.txt",
|
34 |
+
}
|
35 |
+
|
36 |
+
|
37 |
+
@lru_cache()
|
38 |
+
def bytes_to_unicode():
|
39 |
+
"""
|
40 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
41 |
+
characters the bpe code barfs on.
|
42 |
+
|
43 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
44 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
45 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
46 |
+
tables between utf-8 bytes and unicode strings.
|
47 |
+
"""
|
48 |
+
bs = (
|
49 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
50 |
+
)
|
51 |
+
cs = bs[:]
|
52 |
+
n = 0
|
53 |
+
for b in range(2**8):
|
54 |
+
if b not in bs:
|
55 |
+
bs.append(b)
|
56 |
+
cs.append(2**8 + n)
|
57 |
+
n += 1
|
58 |
+
cs = [chr(n) for n in cs]
|
59 |
+
return dict(zip(bs, cs))
|
60 |
+
|
61 |
+
|
62 |
+
def get_pairs(word):
|
63 |
+
"""
|
64 |
+
Return set of symbol pairs in a word.
|
65 |
+
|
66 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
67 |
+
"""
|
68 |
+
pairs = set()
|
69 |
+
prev_char = word[0]
|
70 |
+
for char in word[1:]:
|
71 |
+
pairs.add((prev_char, char))
|
72 |
+
prev_char = char
|
73 |
+
return pairs
|
74 |
+
|
75 |
+
|
76 |
+
def whitespace_clean(text):
|
77 |
+
text = re.sub(r"\s+", " ", text)
|
78 |
+
text = text.strip()
|
79 |
+
return text
|
80 |
+
|
81 |
+
|
82 |
+
# Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
|
83 |
+
def whitespace_tokenize(text):
|
84 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
85 |
+
text = text.strip()
|
86 |
+
if not text:
|
87 |
+
return []
|
88 |
+
tokens = text.split()
|
89 |
+
return tokens
|
90 |
+
|
91 |
+
|
92 |
+
# Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
|
93 |
+
class BasicTokenizer(object):
|
94 |
+
"""
|
95 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
96 |
+
|
97 |
+
Args:
|
98 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
99 |
+
Whether or not to lowercase the input when tokenizing.
|
100 |
+
never_split (`Iterable`, *optional*):
|
101 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
102 |
+
`do_basic_tokenize=True`
|
103 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
104 |
+
Whether or not to tokenize Chinese characters.
|
105 |
+
|
106 |
+
This should likely be deactivated for Japanese (see this
|
107 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
108 |
+
strip_accents (`bool`, *optional*):
|
109 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
110 |
+
value for `lowercase` (as in the original BERT).
|
111 |
+
do_split_on_punc (`bool`, *optional*, defaults to `True`):
|
112 |
+
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
|
113 |
+
the full context of the words, such as contractions.
|
114 |
+
"""
|
115 |
+
|
116 |
+
def __init__(
|
117 |
+
self,
|
118 |
+
do_lower_case=True,
|
119 |
+
never_split=None,
|
120 |
+
tokenize_chinese_chars=True,
|
121 |
+
strip_accents=None,
|
122 |
+
do_split_on_punc=True,
|
123 |
+
):
|
124 |
+
if never_split is None:
|
125 |
+
never_split = []
|
126 |
+
self.do_lower_case = do_lower_case
|
127 |
+
self.never_split = set(never_split)
|
128 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
129 |
+
self.strip_accents = strip_accents
|
130 |
+
self.do_split_on_punc = do_split_on_punc
|
131 |
+
|
132 |
+
def tokenize(self, text, never_split=None):
|
133 |
+
"""
|
134 |
+
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
|
135 |
+
|
136 |
+
Args:
|
137 |
+
never_split (`List[str]`, *optional*)
|
138 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
139 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
140 |
+
"""
|
141 |
+
# union() returns a new set by concatenating the two sets.
|
142 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
143 |
+
text = self._clean_text(text)
|
144 |
+
|
145 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
146 |
+
# models. This is also applied to the English models now, but it doesn't
|
147 |
+
# matter since the English models were not trained on any Chinese data
|
148 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
149 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
150 |
+
# words in the English Wikipedia.).
|
151 |
+
if self.tokenize_chinese_chars:
|
152 |
+
text = self._tokenize_chinese_chars(text)
|
153 |
+
# prevents treating the same character with different unicode codepoints as different characters
|
154 |
+
unicode_normalized_text = unicodedata.normalize("NFC", text)
|
155 |
+
orig_tokens = whitespace_tokenize(unicode_normalized_text)
|
156 |
+
split_tokens = []
|
157 |
+
for token in orig_tokens:
|
158 |
+
if token not in never_split:
|
159 |
+
if self.do_lower_case:
|
160 |
+
token = token.lower()
|
161 |
+
if self.strip_accents is not False:
|
162 |
+
token = self._run_strip_accents(token)
|
163 |
+
elif self.strip_accents:
|
164 |
+
token = self._run_strip_accents(token)
|
165 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
166 |
+
|
167 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
168 |
+
return output_tokens
|
169 |
+
|
170 |
+
def _run_strip_accents(self, text):
|
171 |
+
"""Strips accents from a piece of text."""
|
172 |
+
text = unicodedata.normalize("NFD", text)
|
173 |
+
output = []
|
174 |
+
for char in text:
|
175 |
+
cat = unicodedata.category(char)
|
176 |
+
if cat == "Mn":
|
177 |
+
continue
|
178 |
+
output.append(char)
|
179 |
+
return "".join(output)
|
180 |
+
|
181 |
+
def _run_split_on_punc(self, text, never_split=None):
|
182 |
+
"""Splits punctuation on a piece of text."""
|
183 |
+
if not self.do_split_on_punc or (never_split is not None and text in never_split):
|
184 |
+
return [text]
|
185 |
+
chars = list(text)
|
186 |
+
i = 0
|
187 |
+
start_new_word = True
|
188 |
+
output = []
|
189 |
+
while i < len(chars):
|
190 |
+
char = chars[i]
|
191 |
+
if _is_punctuation(char):
|
192 |
+
output.append([char])
|
193 |
+
start_new_word = True
|
194 |
+
else:
|
195 |
+
if start_new_word:
|
196 |
+
output.append([])
|
197 |
+
start_new_word = False
|
198 |
+
output[-1].append(char)
|
199 |
+
i += 1
|
200 |
+
|
201 |
+
return ["".join(x) for x in output]
|
202 |
+
|
203 |
+
def _tokenize_chinese_chars(self, text):
|
204 |
+
"""Adds whitespace around any CJK character."""
|
205 |
+
output = []
|
206 |
+
for char in text:
|
207 |
+
cp = ord(char)
|
208 |
+
if self._is_chinese_char(cp):
|
209 |
+
output.append(" ")
|
210 |
+
output.append(char)
|
211 |
+
output.append(" ")
|
212 |
+
else:
|
213 |
+
output.append(char)
|
214 |
+
return "".join(output)
|
215 |
+
|
216 |
+
def _is_chinese_char(self, cp):
|
217 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
218 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
219 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
220 |
+
#
|
221 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
222 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
223 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
224 |
+
# space-separated words, so they are not treated specially and handled
|
225 |
+
# like the all of the other languages.
|
226 |
+
if (
|
227 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
228 |
+
or (cp >= 0x3400 and cp <= 0x4DBF) #
|
229 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF) #
|
230 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F) #
|
231 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F) #
|
232 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
|
233 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
234 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
|
235 |
+
): #
|
236 |
+
return True
|
237 |
+
|
238 |
+
return False
|
239 |
+
|
240 |
+
def _clean_text(self, text):
|
241 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
242 |
+
output = []
|
243 |
+
for char in text:
|
244 |
+
cp = ord(char)
|
245 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
246 |
+
continue
|
247 |
+
if _is_whitespace(char):
|
248 |
+
output.append(" ")
|
249 |
+
else:
|
250 |
+
output.append(char)
|
251 |
+
return "".join(output)
|
252 |
+
|
253 |
+
|
254 |
+
class CLIPTokenizer(PreTrainedTokenizer):
|
255 |
+
"""
|
256 |
+
Construct a CLIP tokenizer. Based on byte-level Byte-Pair-Encoding.
|
257 |
+
|
258 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
259 |
+
this superclass for more information regarding those methods.
|
260 |
+
|
261 |
+
Args:
|
262 |
+
vocab_file (`str`):
|
263 |
+
Path to the vocabulary file.
|
264 |
+
merges_file (`str`):
|
265 |
+
Path to the merges file.
|
266 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
267 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
268 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
269 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
270 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
271 |
+
token instead.
|
272 |
+
bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
|
273 |
+
The beginning of sequence token.
|
274 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
275 |
+
The end of sequence token.
|
276 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
277 |
+
The token used for padding, for example when batching sequences of different lengths.
|
278 |
+
"""
|
279 |
+
|
280 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
281 |
+
model_input_names = ["input_ids", "attention_mask"]
|
282 |
+
|
283 |
+
def __init__(
|
284 |
+
self,
|
285 |
+
vocab_file,
|
286 |
+
merges_file,
|
287 |
+
errors="replace",
|
288 |
+
unk_token="<|endoftext|>",
|
289 |
+
bos_token="<|startoftext|>",
|
290 |
+
eos_token="<|endoftext|>",
|
291 |
+
pad_token="<|endoftext|>", # hack to enable padding
|
292 |
+
**kwargs,
|
293 |
+
):
|
294 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
295 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
296 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
297 |
+
try:
|
298 |
+
import ftfy
|
299 |
+
|
300 |
+
self.fix_text = ftfy.fix_text
|
301 |
+
except ImportError:
|
302 |
+
logger.info("ftfy or spacy is not installed using custom BasicTokenizer instead of ftfy.")
|
303 |
+
self.nlp = BasicTokenizer(strip_accents=False, do_split_on_punc=False)
|
304 |
+
self.fix_text = None
|
305 |
+
|
306 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
307 |
+
self.encoder = json.load(vocab_handle)
|
308 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
309 |
+
self.errors = errors # how to handle errors in decoding
|
310 |
+
self.byte_encoder = bytes_to_unicode()
|
311 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
312 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
313 |
+
bpe_merges = merges_handle.read().strip().split("\n")[1 : 49152 - 256 - 2 + 1]
|
314 |
+
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
|
315 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
316 |
+
self.cache = {"<|startoftext|>": "<|startoftext|>", "<|endoftext|>": "<|endoftext|>"}
|
317 |
+
|
318 |
+
self.pat = re.compile(
|
319 |
+
r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
|
320 |
+
re.IGNORECASE,
|
321 |
+
)
|
322 |
+
|
323 |
+
super().__init__(
|
324 |
+
errors=errors,
|
325 |
+
unk_token=unk_token,
|
326 |
+
bos_token=bos_token,
|
327 |
+
eos_token=eos_token,
|
328 |
+
pad_token=pad_token,
|
329 |
+
**kwargs,
|
330 |
+
)
|
331 |
+
|
332 |
+
@property
|
333 |
+
def vocab_size(self):
|
334 |
+
return len(self.encoder)
|
335 |
+
|
336 |
+
def get_vocab(self):
|
337 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
338 |
+
|
339 |
+
def build_inputs_with_special_tokens(
|
340 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
341 |
+
) -> List[int]:
|
342 |
+
"""
|
343 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
344 |
+
adding special tokens. A CLIP sequence has the following format:
|
345 |
+
|
346 |
+
- single sequence: `<|startoftext|> X <|endoftext|>`
|
347 |
+
|
348 |
+
Pairs of sequences are not the expected use case, but they will be handled without a separator.
|
349 |
+
|
350 |
+
Args:
|
351 |
+
token_ids_0 (`List[int]`):
|
352 |
+
List of IDs to which the special tokens will be added.
|
353 |
+
token_ids_1 (`List[int]`, *optional*):
|
354 |
+
Optional second list of IDs for sequence pairs.
|
355 |
+
|
356 |
+
Returns:
|
357 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
358 |
+
"""
|
359 |
+
bos_token = [self.bos_token_id]
|
360 |
+
eos_token = [self.eos_token_id]
|
361 |
+
|
362 |
+
if token_ids_1 is None:
|
363 |
+
return bos_token + token_ids_0 + eos_token
|
364 |
+
return bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token
|
365 |
+
|
366 |
+
def get_special_tokens_mask(
|
367 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
368 |
+
) -> List[int]:
|
369 |
+
"""
|
370 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
371 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
372 |
+
|
373 |
+
Args:
|
374 |
+
token_ids_0 (`List[int]`):
|
375 |
+
List of IDs.
|
376 |
+
token_ids_1 (`List[int]`, *optional*):
|
377 |
+
Optional second list of IDs for sequence pairs.
|
378 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
379 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
380 |
+
|
381 |
+
Returns:
|
382 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
383 |
+
"""
|
384 |
+
|
385 |
+
if already_has_special_tokens:
|
386 |
+
return super().get_special_tokens_mask(
|
387 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
388 |
+
)
|
389 |
+
|
390 |
+
if token_ids_1 is None:
|
391 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
392 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + [1] + ([0] * len(token_ids_1)) + [1]
|
393 |
+
|
394 |
+
def create_token_type_ids_from_sequences(
|
395 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
396 |
+
) -> List[int]:
|
397 |
+
"""
|
398 |
+
Create a mask from the two sequences passed. CLIP does not make use of token type ids, therefore a list of
|
399 |
+
zeros is returned.
|
400 |
+
|
401 |
+
Args:
|
402 |
+
token_ids_0 (`List[int]`):
|
403 |
+
List of IDs.
|
404 |
+
token_ids_1 (`List[int]`, *optional*):
|
405 |
+
Optional second list of IDs for sequence pairs.
|
406 |
+
|
407 |
+
Returns:
|
408 |
+
`List[int]`: List of zeros.
|
409 |
+
"""
|
410 |
+
bos_token = [self.bos_token_id]
|
411 |
+
eos_token = [self.eos_token_id]
|
412 |
+
|
413 |
+
if token_ids_1 is None:
|
414 |
+
return len(bos_token + token_ids_0 + eos_token) * [0]
|
415 |
+
return len(bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token) * [0]
|
416 |
+
|
417 |
+
def bpe(self, token):
|
418 |
+
if token in self.cache:
|
419 |
+
return self.cache[token]
|
420 |
+
word = tuple(token[:-1]) + (token[-1] + "</w>",)
|
421 |
+
pairs = get_pairs(word)
|
422 |
+
|
423 |
+
if not pairs:
|
424 |
+
return token + "</w>"
|
425 |
+
|
426 |
+
while True:
|
427 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
428 |
+
if bigram not in self.bpe_ranks:
|
429 |
+
break
|
430 |
+
first, second = bigram
|
431 |
+
new_word = []
|
432 |
+
i = 0
|
433 |
+
while i < len(word):
|
434 |
+
try:
|
435 |
+
j = word.index(first, i)
|
436 |
+
except ValueError:
|
437 |
+
new_word.extend(word[i:])
|
438 |
+
break
|
439 |
+
else:
|
440 |
+
new_word.extend(word[i:j])
|
441 |
+
i = j
|
442 |
+
|
443 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
444 |
+
new_word.append(first + second)
|
445 |
+
i += 2
|
446 |
+
else:
|
447 |
+
new_word.append(word[i])
|
448 |
+
i += 1
|
449 |
+
new_word = tuple(new_word)
|
450 |
+
word = new_word
|
451 |
+
if len(word) == 1:
|
452 |
+
break
|
453 |
+
else:
|
454 |
+
pairs = get_pairs(word)
|
455 |
+
word = " ".join(word)
|
456 |
+
self.cache[token] = word
|
457 |
+
return word
|
458 |
+
|
459 |
+
def _tokenize(self, text):
|
460 |
+
"""Tokenize a string."""
|
461 |
+
bpe_tokens = []
|
462 |
+
if self.fix_text is None:
|
463 |
+
text = " ".join(self.nlp.tokenize(text))
|
464 |
+
else:
|
465 |
+
text = whitespace_clean(self.fix_text(text)).lower()
|
466 |
+
|
467 |
+
for token in re.findall(self.pat, text):
|
468 |
+
token = "".join(
|
469 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
470 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
471 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
472 |
+
return bpe_tokens
|
473 |
+
|
474 |
+
def _convert_token_to_id(self, token):
|
475 |
+
"""Converts a token (str) in an id using the vocab."""
|
476 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
477 |
+
|
478 |
+
def _convert_id_to_token(self, index):
|
479 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
480 |
+
return self.decoder.get(index)
|
481 |
+
|
482 |
+
def convert_tokens_to_string(self, tokens):
|
483 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
484 |
+
text = "".join(tokens)
|
485 |
+
byte_array = bytearray([self.byte_decoder[c] for c in text])
|
486 |
+
text = byte_array.decode("utf-8", errors=self.errors).replace("</w>", " ").strip()
|
487 |
+
return text
|
488 |
+
|
489 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
490 |
+
if not os.path.isdir(save_directory):
|
491 |
+
logger.error("Vocabulary path ({}) should be a directory".format(save_directory))
|
492 |
+
return
|
493 |
+
vocab_file = os.path.join(
|
494 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
495 |
+
)
|
496 |
+
merge_file = os.path.join(
|
497 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
498 |
+
)
|
499 |
+
|
500 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
501 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
502 |
+
|
503 |
+
index = 0
|
504 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
505 |
+
writer.write("#version: 0.2\n")
|
506 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
507 |
+
if index != token_index:
|
508 |
+
logger.warning(
|
509 |
+
"Saving vocabulary to {}: BPE merge indices are not consecutive."
|
510 |
+
" Please check that the tokenizer is not corrupted!".format(merge_file)
|
511 |
+
)
|
512 |
+
index = token_index
|
513 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
514 |
+
index += 1
|
515 |
+
|
516 |
+
return vocab_file, merge_file
|
llmeval-env/lib/python3.10/site-packages/transformers/models/clip/tokenization_clip_fast.py
ADDED
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 The Open AI Team 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 OpenAI GPT."""
|
16 |
+
|
17 |
+
|
18 |
+
from typing import List, Optional, Tuple
|
19 |
+
|
20 |
+
from tokenizers import pre_tokenizers
|
21 |
+
|
22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
23 |
+
from ...utils import logging
|
24 |
+
from .tokenization_clip import CLIPTokenizer
|
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 |
+
|
32 |
+
class CLIPTokenizerFast(PreTrainedTokenizerFast):
|
33 |
+
"""
|
34 |
+
Construct a "fast" CLIP tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
|
35 |
+
Byte-Pair-Encoding.
|
36 |
+
|
37 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
38 |
+
refer to this superclass for more information regarding those methods.
|
39 |
+
|
40 |
+
Args:
|
41 |
+
vocab_file (`str`, *optional*):
|
42 |
+
Path to the vocabulary file.
|
43 |
+
merges_file (`str`, *optional*):
|
44 |
+
Path to the merges file.
|
45 |
+
tokenizer_file (`str`, *optional*):
|
46 |
+
The path to a tokenizer file to use instead of the vocab file.
|
47 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
48 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
49 |
+
token instead.
|
50 |
+
bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
|
51 |
+
The beginning of sequence token.
|
52 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
53 |
+
The end of sequence token.
|
54 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
55 |
+
The token used for padding, for example when batching sequences of different lengths.
|
56 |
+
"""
|
57 |
+
|
58 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
59 |
+
model_input_names = ["input_ids", "attention_mask"]
|
60 |
+
slow_tokenizer_class = CLIPTokenizer
|
61 |
+
|
62 |
+
def __init__(
|
63 |
+
self,
|
64 |
+
vocab_file=None,
|
65 |
+
merges_file=None,
|
66 |
+
tokenizer_file=None,
|
67 |
+
unk_token="<|endoftext|>",
|
68 |
+
bos_token="<|startoftext|>",
|
69 |
+
eos_token="<|endoftext|>",
|
70 |
+
pad_token="<|endoftext|>", # hack to enable padding
|
71 |
+
**kwargs,
|
72 |
+
):
|
73 |
+
super().__init__(
|
74 |
+
vocab_file,
|
75 |
+
merges_file,
|
76 |
+
tokenizer_file=tokenizer_file,
|
77 |
+
unk_token=unk_token,
|
78 |
+
bos_token=bos_token,
|
79 |
+
eos_token=eos_token,
|
80 |
+
pad_token=pad_token,
|
81 |
+
**kwargs,
|
82 |
+
)
|
83 |
+
|
84 |
+
if not isinstance(self.backend_tokenizer.pre_tokenizer, pre_tokenizers.Sequence):
|
85 |
+
raise ValueError(
|
86 |
+
"The `backend_tokenizer` provided does not match the expected format. The CLIP tokenizer has been"
|
87 |
+
" heavily modified from transformers version 4.17.0. You need to convert the tokenizer you are using"
|
88 |
+
" to be compatible with this version.The easiest way to do so is"
|
89 |
+
' `CLIPTokenizerFast.from_pretrained("path_to_local_folder_or_hub_repo, from_slow=True)`. If you want'
|
90 |
+
" to use your existing tokenizer, you will have to revert to a version prior to 4.17.0 of"
|
91 |
+
" transformers."
|
92 |
+
)
|
93 |
+
|
94 |
+
self._wrap_decode_method_backend_tokenizer()
|
95 |
+
|
96 |
+
# Very ugly hack to enable padding to have a correct decoding see https://github.com/huggingface/tokenizers/issues/872
|
97 |
+
def _wrap_decode_method_backend_tokenizer(self):
|
98 |
+
orig_decode_method = self.backend_tokenizer.decode
|
99 |
+
|
100 |
+
def new_decode_method(*args, **kwargs):
|
101 |
+
text = orig_decode_method(*args, **kwargs)
|
102 |
+
text = text.replace(self.backend_tokenizer.model.end_of_word_suffix, " ").strip()
|
103 |
+
return text
|
104 |
+
|
105 |
+
self.backend_tokenizer.decode = new_decode_method
|
106 |
+
|
107 |
+
def build_inputs_with_special_tokens(
|
108 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
109 |
+
) -> List[int]:
|
110 |
+
"""
|
111 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
112 |
+
adding special tokens. A CLIP sequence has the following format:
|
113 |
+
|
114 |
+
- single sequence: `<|startoftext|> X <|endoftext|>`
|
115 |
+
|
116 |
+
Pairs of sequences are not the expected use case, but they will be handled without a separator.
|
117 |
+
|
118 |
+
Args:
|
119 |
+
token_ids_0 (`List[int]`):
|
120 |
+
List of IDs to which the special tokens will be added.
|
121 |
+
token_ids_1 (`List[int]`, *optional*):
|
122 |
+
Optional second list of IDs for sequence pairs.
|
123 |
+
|
124 |
+
Returns:
|
125 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
126 |
+
"""
|
127 |
+
bos_token = [self.bos_token_id]
|
128 |
+
eos_token = [self.eos_token_id]
|
129 |
+
|
130 |
+
if token_ids_1 is None:
|
131 |
+
return bos_token + token_ids_0 + eos_token
|
132 |
+
return bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token
|
133 |
+
|
134 |
+
def create_token_type_ids_from_sequences(
|
135 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
136 |
+
) -> List[int]:
|
137 |
+
"""
|
138 |
+
Create a mask from the two sequences passed. CLIP does not make use of token type ids, therefore a list of
|
139 |
+
zeros is returned.
|
140 |
+
|
141 |
+
Args:
|
142 |
+
token_ids_0 (`List[int]`):
|
143 |
+
List of IDs.
|
144 |
+
token_ids_1 (`List[int]`, *optional*):
|
145 |
+
Optional second list of IDs for sequence pairs.
|
146 |
+
|
147 |
+
Returns:
|
148 |
+
`List[int]`: List of zeros.
|
149 |
+
"""
|
150 |
+
bos_token = [self.bos_token_id]
|
151 |
+
eos_token = [self.eos_token_id]
|
152 |
+
|
153 |
+
if token_ids_1 is None:
|
154 |
+
return len(bos_token + token_ids_0 + eos_token) * [0]
|
155 |
+
return len(bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token) * [0]
|
156 |
+
|
157 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
158 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
159 |
+
return tuple(files)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__init__.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_deberta_v2": ["DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaV2Config", "DebertaV2OnnxConfig"],
|
28 |
+
"tokenization_deberta_v2": ["DebertaV2Tokenizer"],
|
29 |
+
}
|
30 |
+
|
31 |
+
try:
|
32 |
+
if not is_tokenizers_available():
|
33 |
+
raise OptionalDependencyNotAvailable()
|
34 |
+
except OptionalDependencyNotAvailable:
|
35 |
+
pass
|
36 |
+
else:
|
37 |
+
_import_structure["tokenization_deberta_v2_fast"] = ["DebertaV2TokenizerFast"]
|
38 |
+
|
39 |
+
try:
|
40 |
+
if not is_tf_available():
|
41 |
+
raise OptionalDependencyNotAvailable()
|
42 |
+
except OptionalDependencyNotAvailable:
|
43 |
+
pass
|
44 |
+
else:
|
45 |
+
_import_structure["modeling_tf_deberta_v2"] = [
|
46 |
+
"TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST",
|
47 |
+
"TFDebertaV2ForMaskedLM",
|
48 |
+
"TFDebertaV2ForQuestionAnswering",
|
49 |
+
"TFDebertaV2ForMultipleChoice",
|
50 |
+
"TFDebertaV2ForSequenceClassification",
|
51 |
+
"TFDebertaV2ForTokenClassification",
|
52 |
+
"TFDebertaV2Model",
|
53 |
+
"TFDebertaV2PreTrainedModel",
|
54 |
+
]
|
55 |
+
|
56 |
+
try:
|
57 |
+
if not is_torch_available():
|
58 |
+
raise OptionalDependencyNotAvailable()
|
59 |
+
except OptionalDependencyNotAvailable:
|
60 |
+
pass
|
61 |
+
else:
|
62 |
+
_import_structure["modeling_deberta_v2"] = [
|
63 |
+
"DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST",
|
64 |
+
"DebertaV2ForMaskedLM",
|
65 |
+
"DebertaV2ForMultipleChoice",
|
66 |
+
"DebertaV2ForQuestionAnswering",
|
67 |
+
"DebertaV2ForSequenceClassification",
|
68 |
+
"DebertaV2ForTokenClassification",
|
69 |
+
"DebertaV2Model",
|
70 |
+
"DebertaV2PreTrainedModel",
|
71 |
+
]
|
72 |
+
|
73 |
+
|
74 |
+
if TYPE_CHECKING:
|
75 |
+
from .configuration_deberta_v2 import (
|
76 |
+
DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP,
|
77 |
+
DebertaV2Config,
|
78 |
+
DebertaV2OnnxConfig,
|
79 |
+
)
|
80 |
+
from .tokenization_deberta_v2 import DebertaV2Tokenizer
|
81 |
+
|
82 |
+
try:
|
83 |
+
if not is_tokenizers_available():
|
84 |
+
raise OptionalDependencyNotAvailable()
|
85 |
+
except OptionalDependencyNotAvailable:
|
86 |
+
pass
|
87 |
+
else:
|
88 |
+
from .tokenization_deberta_v2_fast import DebertaV2TokenizerFast
|
89 |
+
|
90 |
+
try:
|
91 |
+
if not is_tf_available():
|
92 |
+
raise OptionalDependencyNotAvailable()
|
93 |
+
except OptionalDependencyNotAvailable:
|
94 |
+
pass
|
95 |
+
else:
|
96 |
+
from .modeling_tf_deberta_v2 import (
|
97 |
+
TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
|
98 |
+
TFDebertaV2ForMaskedLM,
|
99 |
+
TFDebertaV2ForMultipleChoice,
|
100 |
+
TFDebertaV2ForQuestionAnswering,
|
101 |
+
TFDebertaV2ForSequenceClassification,
|
102 |
+
TFDebertaV2ForTokenClassification,
|
103 |
+
TFDebertaV2Model,
|
104 |
+
TFDebertaV2PreTrainedModel,
|
105 |
+
)
|
106 |
+
|
107 |
+
try:
|
108 |
+
if not is_torch_available():
|
109 |
+
raise OptionalDependencyNotAvailable()
|
110 |
+
except OptionalDependencyNotAvailable:
|
111 |
+
pass
|
112 |
+
else:
|
113 |
+
from .modeling_deberta_v2 import (
|
114 |
+
DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
|
115 |
+
DebertaV2ForMaskedLM,
|
116 |
+
DebertaV2ForMultipleChoice,
|
117 |
+
DebertaV2ForQuestionAnswering,
|
118 |
+
DebertaV2ForSequenceClassification,
|
119 |
+
DebertaV2ForTokenClassification,
|
120 |
+
DebertaV2Model,
|
121 |
+
DebertaV2PreTrainedModel,
|
122 |
+
)
|
123 |
+
|
124 |
+
else:
|
125 |
+
import sys
|
126 |
+
|
127 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.99 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/configuration_deberta_v2.cpython-310.pyc
ADDED
Binary file (7.99 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/modeling_deberta_v2.cpython-310.pyc
ADDED
Binary file (45.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/modeling_tf_deberta_v2.cpython-310.pyc
ADDED
Binary file (56.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2.cpython-310.pyc
ADDED
Binary file (19.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2_fast.cpython-310.pyc
ADDED
Binary file (8.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/configuration_deberta_v2.py
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2020, Microsoft 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 |
+
""" DeBERTa-v2 model configuration"""
|
16 |
+
from collections import OrderedDict
|
17 |
+
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union
|
18 |
+
|
19 |
+
from ...configuration_utils import PretrainedConfig
|
20 |
+
from ...onnx import OnnxConfig
|
21 |
+
from ...utils import logging
|
22 |
+
|
23 |
+
|
24 |
+
if TYPE_CHECKING:
|
25 |
+
from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType
|
26 |
+
|
27 |
+
|
28 |
+
logger = logging.get_logger(__name__)
|
29 |
+
|
30 |
+
|
31 |
+
from ..deprecated._archive_maps import DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP # noqa: F401, E402
|
32 |
+
|
33 |
+
|
34 |
+
class DebertaV2Config(PretrainedConfig):
|
35 |
+
r"""
|
36 |
+
This is the configuration class to store the configuration of a [`DebertaV2Model`]. It is used to instantiate a
|
37 |
+
DeBERTa-v2 model according to the specified arguments, defining the model architecture. Instantiating a
|
38 |
+
configuration with the defaults will yield a similar configuration to that of the DeBERTa
|
39 |
+
[microsoft/deberta-v2-xlarge](https://huggingface.co/microsoft/deberta-v2-xlarge) architecture.
|
40 |
+
|
41 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
42 |
+
documentation from [`PretrainedConfig`] for more information.
|
43 |
+
|
44 |
+
Arguments:
|
45 |
+
vocab_size (`int`, *optional*, defaults to 128100):
|
46 |
+
Vocabulary size of the DeBERTa-v2 model. Defines the number of different tokens that can be represented by
|
47 |
+
the `inputs_ids` passed when calling [`DebertaV2Model`].
|
48 |
+
hidden_size (`int`, *optional*, defaults to 1536):
|
49 |
+
Dimensionality of the encoder layers and the pooler layer.
|
50 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
51 |
+
Number of hidden layers in the Transformer encoder.
|
52 |
+
num_attention_heads (`int`, *optional*, defaults to 24):
|
53 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
54 |
+
intermediate_size (`int`, *optional*, defaults to 6144):
|
55 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
56 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
57 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
58 |
+
`"relu"`, `"silu"`, `"gelu"`, `"tanh"`, `"gelu_fast"`, `"mish"`, `"linear"`, `"sigmoid"` and `"gelu_new"`
|
59 |
+
are supported.
|
60 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
61 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
62 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
63 |
+
The dropout ratio for the attention probabilities.
|
64 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
65 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
66 |
+
just in case (e.g., 512 or 1024 or 2048).
|
67 |
+
type_vocab_size (`int`, *optional*, defaults to 0):
|
68 |
+
The vocabulary size of the `token_type_ids` passed when calling [`DebertaModel`] or [`TFDebertaModel`].
|
69 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
70 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
71 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-7):
|
72 |
+
The epsilon used by the layer normalization layers.
|
73 |
+
relative_attention (`bool`, *optional*, defaults to `True`):
|
74 |
+
Whether use relative position encoding.
|
75 |
+
max_relative_positions (`int`, *optional*, defaults to -1):
|
76 |
+
The range of relative positions `[-max_position_embeddings, max_position_embeddings]`. Use the same value
|
77 |
+
as `max_position_embeddings`.
|
78 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
79 |
+
The value used to pad input_ids.
|
80 |
+
position_biased_input (`bool`, *optional*, defaults to `True`):
|
81 |
+
Whether add absolute position embedding to content embedding.
|
82 |
+
pos_att_type (`List[str]`, *optional*):
|
83 |
+
The type of relative position attention, it can be a combination of `["p2c", "c2p"]`, e.g. `["p2c"]`,
|
84 |
+
`["p2c", "c2p"]`, `["p2c", "c2p"]`.
|
85 |
+
layer_norm_eps (`float`, optional, defaults to 1e-12):
|
86 |
+
The epsilon used by the layer normalization layers.
|
87 |
+
|
88 |
+
Example:
|
89 |
+
|
90 |
+
```python
|
91 |
+
>>> from transformers import DebertaV2Config, DebertaV2Model
|
92 |
+
|
93 |
+
>>> # Initializing a DeBERTa-v2 microsoft/deberta-v2-xlarge style configuration
|
94 |
+
>>> configuration = DebertaV2Config()
|
95 |
+
|
96 |
+
>>> # Initializing a model (with random weights) from the microsoft/deberta-v2-xlarge style configuration
|
97 |
+
>>> model = DebertaV2Model(configuration)
|
98 |
+
|
99 |
+
>>> # Accessing the model configuration
|
100 |
+
>>> configuration = model.config
|
101 |
+
```"""
|
102 |
+
|
103 |
+
model_type = "deberta-v2"
|
104 |
+
|
105 |
+
def __init__(
|
106 |
+
self,
|
107 |
+
vocab_size=128100,
|
108 |
+
hidden_size=1536,
|
109 |
+
num_hidden_layers=24,
|
110 |
+
num_attention_heads=24,
|
111 |
+
intermediate_size=6144,
|
112 |
+
hidden_act="gelu",
|
113 |
+
hidden_dropout_prob=0.1,
|
114 |
+
attention_probs_dropout_prob=0.1,
|
115 |
+
max_position_embeddings=512,
|
116 |
+
type_vocab_size=0,
|
117 |
+
initializer_range=0.02,
|
118 |
+
layer_norm_eps=1e-7,
|
119 |
+
relative_attention=False,
|
120 |
+
max_relative_positions=-1,
|
121 |
+
pad_token_id=0,
|
122 |
+
position_biased_input=True,
|
123 |
+
pos_att_type=None,
|
124 |
+
pooler_dropout=0,
|
125 |
+
pooler_hidden_act="gelu",
|
126 |
+
**kwargs,
|
127 |
+
):
|
128 |
+
super().__init__(**kwargs)
|
129 |
+
|
130 |
+
self.hidden_size = hidden_size
|
131 |
+
self.num_hidden_layers = num_hidden_layers
|
132 |
+
self.num_attention_heads = num_attention_heads
|
133 |
+
self.intermediate_size = intermediate_size
|
134 |
+
self.hidden_act = hidden_act
|
135 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
136 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
137 |
+
self.max_position_embeddings = max_position_embeddings
|
138 |
+
self.type_vocab_size = type_vocab_size
|
139 |
+
self.initializer_range = initializer_range
|
140 |
+
self.relative_attention = relative_attention
|
141 |
+
self.max_relative_positions = max_relative_positions
|
142 |
+
self.pad_token_id = pad_token_id
|
143 |
+
self.position_biased_input = position_biased_input
|
144 |
+
|
145 |
+
# Backwards compatibility
|
146 |
+
if isinstance(pos_att_type, str):
|
147 |
+
pos_att_type = [x.strip() for x in pos_att_type.lower().split("|")]
|
148 |
+
|
149 |
+
self.pos_att_type = pos_att_type
|
150 |
+
self.vocab_size = vocab_size
|
151 |
+
self.layer_norm_eps = layer_norm_eps
|
152 |
+
|
153 |
+
self.pooler_hidden_size = kwargs.get("pooler_hidden_size", hidden_size)
|
154 |
+
self.pooler_dropout = pooler_dropout
|
155 |
+
self.pooler_hidden_act = pooler_hidden_act
|
156 |
+
|
157 |
+
|
158 |
+
class DebertaV2OnnxConfig(OnnxConfig):
|
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 |
+
if self._config.type_vocab_size > 0:
|
166 |
+
return OrderedDict(
|
167 |
+
[("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis)]
|
168 |
+
)
|
169 |
+
else:
|
170 |
+
return OrderedDict([("input_ids", dynamic_axis), ("attention_mask", dynamic_axis)])
|
171 |
+
|
172 |
+
@property
|
173 |
+
def default_onnx_opset(self) -> int:
|
174 |
+
return 12
|
175 |
+
|
176 |
+
def generate_dummy_inputs(
|
177 |
+
self,
|
178 |
+
preprocessor: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],
|
179 |
+
batch_size: int = -1,
|
180 |
+
seq_length: int = -1,
|
181 |
+
num_choices: int = -1,
|
182 |
+
is_pair: bool = False,
|
183 |
+
framework: Optional["TensorType"] = None,
|
184 |
+
num_channels: int = 3,
|
185 |
+
image_width: int = 40,
|
186 |
+
image_height: int = 40,
|
187 |
+
tokenizer: "PreTrainedTokenizerBase" = None,
|
188 |
+
) -> Mapping[str, Any]:
|
189 |
+
dummy_inputs = super().generate_dummy_inputs(preprocessor=preprocessor, framework=framework)
|
190 |
+
if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
|
191 |
+
del dummy_inputs["token_type_ids"]
|
192 |
+
return dummy_inputs
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/modeling_deberta_v2.py
ADDED
@@ -0,0 +1,1629 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2020 Microsoft and the Hugging Face Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" PyTorch DeBERTa-v2 model."""
|
16 |
+
|
17 |
+
from collections.abc import Sequence
|
18 |
+
from typing import Optional, Tuple, Union
|
19 |
+
|
20 |
+
import torch
|
21 |
+
import torch.utils.checkpoint
|
22 |
+
from torch import nn
|
23 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
|
24 |
+
|
25 |
+
from ...activations import ACT2FN
|
26 |
+
from ...modeling_outputs import (
|
27 |
+
BaseModelOutput,
|
28 |
+
MaskedLMOutput,
|
29 |
+
MultipleChoiceModelOutput,
|
30 |
+
QuestionAnsweringModelOutput,
|
31 |
+
SequenceClassifierOutput,
|
32 |
+
TokenClassifierOutput,
|
33 |
+
)
|
34 |
+
from ...modeling_utils import PreTrainedModel
|
35 |
+
from ...pytorch_utils import softmax_backward_data
|
36 |
+
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
37 |
+
from .configuration_deberta_v2 import DebertaV2Config
|
38 |
+
|
39 |
+
|
40 |
+
logger = logging.get_logger(__name__)
|
41 |
+
|
42 |
+
_CONFIG_FOR_DOC = "DebertaV2Config"
|
43 |
+
_CHECKPOINT_FOR_DOC = "microsoft/deberta-v2-xlarge"
|
44 |
+
_QA_TARGET_START_INDEX = 2
|
45 |
+
_QA_TARGET_END_INDEX = 9
|
46 |
+
|
47 |
+
|
48 |
+
from ..deprecated._archive_maps import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
49 |
+
|
50 |
+
|
51 |
+
# Copied from transformers.models.deberta.modeling_deberta.ContextPooler
|
52 |
+
class ContextPooler(nn.Module):
|
53 |
+
def __init__(self, config):
|
54 |
+
super().__init__()
|
55 |
+
self.dense = nn.Linear(config.pooler_hidden_size, config.pooler_hidden_size)
|
56 |
+
self.dropout = StableDropout(config.pooler_dropout)
|
57 |
+
self.config = config
|
58 |
+
|
59 |
+
def forward(self, hidden_states):
|
60 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
61 |
+
# to the first token.
|
62 |
+
|
63 |
+
context_token = hidden_states[:, 0]
|
64 |
+
context_token = self.dropout(context_token)
|
65 |
+
pooled_output = self.dense(context_token)
|
66 |
+
pooled_output = ACT2FN[self.config.pooler_hidden_act](pooled_output)
|
67 |
+
return pooled_output
|
68 |
+
|
69 |
+
@property
|
70 |
+
def output_dim(self):
|
71 |
+
return self.config.hidden_size
|
72 |
+
|
73 |
+
|
74 |
+
# Copied from transformers.models.deberta.modeling_deberta.XSoftmax with deberta->deberta_v2
|
75 |
+
class XSoftmax(torch.autograd.Function):
|
76 |
+
"""
|
77 |
+
Masked Softmax which is optimized for saving memory
|
78 |
+
|
79 |
+
Args:
|
80 |
+
input (`torch.tensor`): The input tensor that will apply softmax.
|
81 |
+
mask (`torch.IntTensor`):
|
82 |
+
The mask matrix where 0 indicate that element will be ignored in the softmax calculation.
|
83 |
+
dim (int): The dimension that will apply softmax
|
84 |
+
|
85 |
+
Example:
|
86 |
+
|
87 |
+
```python
|
88 |
+
>>> import torch
|
89 |
+
>>> from transformers.models.deberta_v2.modeling_deberta_v2 import XSoftmax
|
90 |
+
|
91 |
+
>>> # Make a tensor
|
92 |
+
>>> x = torch.randn([4, 20, 100])
|
93 |
+
|
94 |
+
>>> # Create a mask
|
95 |
+
>>> mask = (x > 0).int()
|
96 |
+
|
97 |
+
>>> # Specify the dimension to apply softmax
|
98 |
+
>>> dim = -1
|
99 |
+
|
100 |
+
>>> y = XSoftmax.apply(x, mask, dim)
|
101 |
+
```"""
|
102 |
+
|
103 |
+
@staticmethod
|
104 |
+
def forward(self, input, mask, dim):
|
105 |
+
self.dim = dim
|
106 |
+
rmask = ~(mask.to(torch.bool))
|
107 |
+
|
108 |
+
output = input.masked_fill(rmask, torch.tensor(torch.finfo(input.dtype).min))
|
109 |
+
output = torch.softmax(output, self.dim)
|
110 |
+
output.masked_fill_(rmask, 0)
|
111 |
+
self.save_for_backward(output)
|
112 |
+
return output
|
113 |
+
|
114 |
+
@staticmethod
|
115 |
+
def backward(self, grad_output):
|
116 |
+
(output,) = self.saved_tensors
|
117 |
+
inputGrad = softmax_backward_data(self, grad_output, output, self.dim, output)
|
118 |
+
return inputGrad, None, None
|
119 |
+
|
120 |
+
@staticmethod
|
121 |
+
def symbolic(g, self, mask, dim):
|
122 |
+
import torch.onnx.symbolic_helper as sym_help
|
123 |
+
from torch.onnx.symbolic_opset9 import masked_fill, softmax
|
124 |
+
|
125 |
+
mask_cast_value = g.op("Cast", mask, to_i=sym_help.cast_pytorch_to_onnx["Long"])
|
126 |
+
r_mask = g.op(
|
127 |
+
"Cast",
|
128 |
+
g.op("Sub", g.op("Constant", value_t=torch.tensor(1, dtype=torch.int64)), mask_cast_value),
|
129 |
+
to_i=sym_help.cast_pytorch_to_onnx["Bool"],
|
130 |
+
)
|
131 |
+
output = masked_fill(
|
132 |
+
g, self, r_mask, g.op("Constant", value_t=torch.tensor(torch.finfo(self.type().dtype()).min))
|
133 |
+
)
|
134 |
+
output = softmax(g, output, dim)
|
135 |
+
return masked_fill(g, output, r_mask, g.op("Constant", value_t=torch.tensor(0, dtype=torch.bool)))
|
136 |
+
|
137 |
+
|
138 |
+
# Copied from transformers.models.deberta.modeling_deberta.DropoutContext
|
139 |
+
class DropoutContext(object):
|
140 |
+
def __init__(self):
|
141 |
+
self.dropout = 0
|
142 |
+
self.mask = None
|
143 |
+
self.scale = 1
|
144 |
+
self.reuse_mask = True
|
145 |
+
|
146 |
+
|
147 |
+
# Copied from transformers.models.deberta.modeling_deberta.get_mask
|
148 |
+
def get_mask(input, local_context):
|
149 |
+
if not isinstance(local_context, DropoutContext):
|
150 |
+
dropout = local_context
|
151 |
+
mask = None
|
152 |
+
else:
|
153 |
+
dropout = local_context.dropout
|
154 |
+
dropout *= local_context.scale
|
155 |
+
mask = local_context.mask if local_context.reuse_mask else None
|
156 |
+
|
157 |
+
if dropout > 0 and mask is None:
|
158 |
+
mask = (1 - torch.empty_like(input).bernoulli_(1 - dropout)).to(torch.bool)
|
159 |
+
|
160 |
+
if isinstance(local_context, DropoutContext):
|
161 |
+
if local_context.mask is None:
|
162 |
+
local_context.mask = mask
|
163 |
+
|
164 |
+
return mask, dropout
|
165 |
+
|
166 |
+
|
167 |
+
# Copied from transformers.models.deberta.modeling_deberta.XDropout
|
168 |
+
class XDropout(torch.autograd.Function):
|
169 |
+
"""Optimized dropout function to save computation and memory by using mask operation instead of multiplication."""
|
170 |
+
|
171 |
+
@staticmethod
|
172 |
+
def forward(ctx, input, local_ctx):
|
173 |
+
mask, dropout = get_mask(input, local_ctx)
|
174 |
+
ctx.scale = 1.0 / (1 - dropout)
|
175 |
+
if dropout > 0:
|
176 |
+
ctx.save_for_backward(mask)
|
177 |
+
return input.masked_fill(mask, 0) * ctx.scale
|
178 |
+
else:
|
179 |
+
return input
|
180 |
+
|
181 |
+
@staticmethod
|
182 |
+
def backward(ctx, grad_output):
|
183 |
+
if ctx.scale > 1:
|
184 |
+
(mask,) = ctx.saved_tensors
|
185 |
+
return grad_output.masked_fill(mask, 0) * ctx.scale, None
|
186 |
+
else:
|
187 |
+
return grad_output, None
|
188 |
+
|
189 |
+
@staticmethod
|
190 |
+
def symbolic(g: torch._C.Graph, input: torch._C.Value, local_ctx: Union[float, DropoutContext]) -> torch._C.Value:
|
191 |
+
from torch.onnx import symbolic_opset12
|
192 |
+
|
193 |
+
dropout_p = local_ctx
|
194 |
+
if isinstance(local_ctx, DropoutContext):
|
195 |
+
dropout_p = local_ctx.dropout
|
196 |
+
# StableDropout only calls this function when training.
|
197 |
+
train = True
|
198 |
+
# TODO: We should check if the opset_version being used to export
|
199 |
+
# is > 12 here, but there's no good way to do that. As-is, if the
|
200 |
+
# opset_version < 12, export will fail with a CheckerError.
|
201 |
+
# Once https://github.com/pytorch/pytorch/issues/78391 is fixed, do something like:
|
202 |
+
# if opset_version < 12:
|
203 |
+
# return torch.onnx.symbolic_opset9.dropout(g, input, dropout_p, train)
|
204 |
+
return symbolic_opset12.dropout(g, input, dropout_p, train)
|
205 |
+
|
206 |
+
|
207 |
+
# Copied from transformers.models.deberta.modeling_deberta.StableDropout
|
208 |
+
class StableDropout(nn.Module):
|
209 |
+
"""
|
210 |
+
Optimized dropout module for stabilizing the training
|
211 |
+
|
212 |
+
Args:
|
213 |
+
drop_prob (float): the dropout probabilities
|
214 |
+
"""
|
215 |
+
|
216 |
+
def __init__(self, drop_prob):
|
217 |
+
super().__init__()
|
218 |
+
self.drop_prob = drop_prob
|
219 |
+
self.count = 0
|
220 |
+
self.context_stack = None
|
221 |
+
|
222 |
+
def forward(self, x):
|
223 |
+
"""
|
224 |
+
Call the module
|
225 |
+
|
226 |
+
Args:
|
227 |
+
x (`torch.tensor`): The input tensor to apply dropout
|
228 |
+
"""
|
229 |
+
if self.training and self.drop_prob > 0:
|
230 |
+
return XDropout.apply(x, self.get_context())
|
231 |
+
return x
|
232 |
+
|
233 |
+
def clear_context(self):
|
234 |
+
self.count = 0
|
235 |
+
self.context_stack = None
|
236 |
+
|
237 |
+
def init_context(self, reuse_mask=True, scale=1):
|
238 |
+
if self.context_stack is None:
|
239 |
+
self.context_stack = []
|
240 |
+
self.count = 0
|
241 |
+
for c in self.context_stack:
|
242 |
+
c.reuse_mask = reuse_mask
|
243 |
+
c.scale = scale
|
244 |
+
|
245 |
+
def get_context(self):
|
246 |
+
if self.context_stack is not None:
|
247 |
+
if self.count >= len(self.context_stack):
|
248 |
+
self.context_stack.append(DropoutContext())
|
249 |
+
ctx = self.context_stack[self.count]
|
250 |
+
ctx.dropout = self.drop_prob
|
251 |
+
self.count += 1
|
252 |
+
return ctx
|
253 |
+
else:
|
254 |
+
return self.drop_prob
|
255 |
+
|
256 |
+
|
257 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaSelfOutput with DebertaLayerNorm->LayerNorm
|
258 |
+
class DebertaV2SelfOutput(nn.Module):
|
259 |
+
def __init__(self, config):
|
260 |
+
super().__init__()
|
261 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
262 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
263 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
264 |
+
|
265 |
+
def forward(self, hidden_states, input_tensor):
|
266 |
+
hidden_states = self.dense(hidden_states)
|
267 |
+
hidden_states = self.dropout(hidden_states)
|
268 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
269 |
+
return hidden_states
|
270 |
+
|
271 |
+
|
272 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaAttention with Deberta->DebertaV2
|
273 |
+
class DebertaV2Attention(nn.Module):
|
274 |
+
def __init__(self, config):
|
275 |
+
super().__init__()
|
276 |
+
self.self = DisentangledSelfAttention(config)
|
277 |
+
self.output = DebertaV2SelfOutput(config)
|
278 |
+
self.config = config
|
279 |
+
|
280 |
+
def forward(
|
281 |
+
self,
|
282 |
+
hidden_states,
|
283 |
+
attention_mask,
|
284 |
+
output_attentions=False,
|
285 |
+
query_states=None,
|
286 |
+
relative_pos=None,
|
287 |
+
rel_embeddings=None,
|
288 |
+
):
|
289 |
+
self_output = self.self(
|
290 |
+
hidden_states,
|
291 |
+
attention_mask,
|
292 |
+
output_attentions,
|
293 |
+
query_states=query_states,
|
294 |
+
relative_pos=relative_pos,
|
295 |
+
rel_embeddings=rel_embeddings,
|
296 |
+
)
|
297 |
+
if output_attentions:
|
298 |
+
self_output, att_matrix = self_output
|
299 |
+
if query_states is None:
|
300 |
+
query_states = hidden_states
|
301 |
+
attention_output = self.output(self_output, query_states)
|
302 |
+
|
303 |
+
if output_attentions:
|
304 |
+
return (attention_output, att_matrix)
|
305 |
+
else:
|
306 |
+
return attention_output
|
307 |
+
|
308 |
+
|
309 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->DebertaV2
|
310 |
+
class DebertaV2Intermediate(nn.Module):
|
311 |
+
def __init__(self, config):
|
312 |
+
super().__init__()
|
313 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
314 |
+
if isinstance(config.hidden_act, str):
|
315 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
316 |
+
else:
|
317 |
+
self.intermediate_act_fn = config.hidden_act
|
318 |
+
|
319 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
320 |
+
hidden_states = self.dense(hidden_states)
|
321 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
322 |
+
return hidden_states
|
323 |
+
|
324 |
+
|
325 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaOutput with DebertaLayerNorm->LayerNorm
|
326 |
+
class DebertaV2Output(nn.Module):
|
327 |
+
def __init__(self, config):
|
328 |
+
super().__init__()
|
329 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
330 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
331 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
332 |
+
self.config = config
|
333 |
+
|
334 |
+
def forward(self, hidden_states, input_tensor):
|
335 |
+
hidden_states = self.dense(hidden_states)
|
336 |
+
hidden_states = self.dropout(hidden_states)
|
337 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
338 |
+
return hidden_states
|
339 |
+
|
340 |
+
|
341 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaLayer with Deberta->DebertaV2
|
342 |
+
class DebertaV2Layer(nn.Module):
|
343 |
+
def __init__(self, config):
|
344 |
+
super().__init__()
|
345 |
+
self.attention = DebertaV2Attention(config)
|
346 |
+
self.intermediate = DebertaV2Intermediate(config)
|
347 |
+
self.output = DebertaV2Output(config)
|
348 |
+
|
349 |
+
def forward(
|
350 |
+
self,
|
351 |
+
hidden_states,
|
352 |
+
attention_mask,
|
353 |
+
query_states=None,
|
354 |
+
relative_pos=None,
|
355 |
+
rel_embeddings=None,
|
356 |
+
output_attentions=False,
|
357 |
+
):
|
358 |
+
attention_output = self.attention(
|
359 |
+
hidden_states,
|
360 |
+
attention_mask,
|
361 |
+
output_attentions=output_attentions,
|
362 |
+
query_states=query_states,
|
363 |
+
relative_pos=relative_pos,
|
364 |
+
rel_embeddings=rel_embeddings,
|
365 |
+
)
|
366 |
+
if output_attentions:
|
367 |
+
attention_output, att_matrix = attention_output
|
368 |
+
intermediate_output = self.intermediate(attention_output)
|
369 |
+
layer_output = self.output(intermediate_output, attention_output)
|
370 |
+
if output_attentions:
|
371 |
+
return (layer_output, att_matrix)
|
372 |
+
else:
|
373 |
+
return layer_output
|
374 |
+
|
375 |
+
|
376 |
+
class ConvLayer(nn.Module):
|
377 |
+
def __init__(self, config):
|
378 |
+
super().__init__()
|
379 |
+
kernel_size = getattr(config, "conv_kernel_size", 3)
|
380 |
+
groups = getattr(config, "conv_groups", 1)
|
381 |
+
self.conv_act = getattr(config, "conv_act", "tanh")
|
382 |
+
self.conv = nn.Conv1d(
|
383 |
+
config.hidden_size, config.hidden_size, kernel_size, padding=(kernel_size - 1) // 2, groups=groups
|
384 |
+
)
|
385 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
386 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
387 |
+
self.config = config
|
388 |
+
|
389 |
+
def forward(self, hidden_states, residual_states, input_mask):
|
390 |
+
out = self.conv(hidden_states.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous()
|
391 |
+
rmask = (1 - input_mask).bool()
|
392 |
+
out.masked_fill_(rmask.unsqueeze(-1).expand(out.size()), 0)
|
393 |
+
out = ACT2FN[self.conv_act](self.dropout(out))
|
394 |
+
|
395 |
+
layer_norm_input = residual_states + out
|
396 |
+
output = self.LayerNorm(layer_norm_input).to(layer_norm_input)
|
397 |
+
|
398 |
+
if input_mask is None:
|
399 |
+
output_states = output
|
400 |
+
else:
|
401 |
+
if input_mask.dim() != layer_norm_input.dim():
|
402 |
+
if input_mask.dim() == 4:
|
403 |
+
input_mask = input_mask.squeeze(1).squeeze(1)
|
404 |
+
input_mask = input_mask.unsqueeze(2)
|
405 |
+
|
406 |
+
input_mask = input_mask.to(output.dtype)
|
407 |
+
output_states = output * input_mask
|
408 |
+
|
409 |
+
return output_states
|
410 |
+
|
411 |
+
|
412 |
+
class DebertaV2Encoder(nn.Module):
|
413 |
+
"""Modified BertEncoder with relative position bias support"""
|
414 |
+
|
415 |
+
def __init__(self, config):
|
416 |
+
super().__init__()
|
417 |
+
|
418 |
+
self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)])
|
419 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
420 |
+
|
421 |
+
if self.relative_attention:
|
422 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
423 |
+
if self.max_relative_positions < 1:
|
424 |
+
self.max_relative_positions = config.max_position_embeddings
|
425 |
+
|
426 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
427 |
+
pos_ebd_size = self.max_relative_positions * 2
|
428 |
+
|
429 |
+
if self.position_buckets > 0:
|
430 |
+
pos_ebd_size = self.position_buckets * 2
|
431 |
+
|
432 |
+
self.rel_embeddings = nn.Embedding(pos_ebd_size, config.hidden_size)
|
433 |
+
|
434 |
+
self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")]
|
435 |
+
|
436 |
+
if "layer_norm" in self.norm_rel_ebd:
|
437 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=True)
|
438 |
+
|
439 |
+
self.conv = ConvLayer(config) if getattr(config, "conv_kernel_size", 0) > 0 else None
|
440 |
+
self.gradient_checkpointing = False
|
441 |
+
|
442 |
+
def get_rel_embedding(self):
|
443 |
+
rel_embeddings = self.rel_embeddings.weight if self.relative_attention else None
|
444 |
+
if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd):
|
445 |
+
rel_embeddings = self.LayerNorm(rel_embeddings)
|
446 |
+
return rel_embeddings
|
447 |
+
|
448 |
+
def get_attention_mask(self, attention_mask):
|
449 |
+
if attention_mask.dim() <= 2:
|
450 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
451 |
+
attention_mask = extended_attention_mask * extended_attention_mask.squeeze(-2).unsqueeze(-1)
|
452 |
+
elif attention_mask.dim() == 3:
|
453 |
+
attention_mask = attention_mask.unsqueeze(1)
|
454 |
+
|
455 |
+
return attention_mask
|
456 |
+
|
457 |
+
def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None):
|
458 |
+
if self.relative_attention and relative_pos is None:
|
459 |
+
q = query_states.size(-2) if query_states is not None else hidden_states.size(-2)
|
460 |
+
relative_pos = build_relative_position(
|
461 |
+
q,
|
462 |
+
hidden_states.size(-2),
|
463 |
+
bucket_size=self.position_buckets,
|
464 |
+
max_position=self.max_relative_positions,
|
465 |
+
device=hidden_states.device,
|
466 |
+
)
|
467 |
+
return relative_pos
|
468 |
+
|
469 |
+
def forward(
|
470 |
+
self,
|
471 |
+
hidden_states,
|
472 |
+
attention_mask,
|
473 |
+
output_hidden_states=True,
|
474 |
+
output_attentions=False,
|
475 |
+
query_states=None,
|
476 |
+
relative_pos=None,
|
477 |
+
return_dict=True,
|
478 |
+
):
|
479 |
+
if attention_mask.dim() <= 2:
|
480 |
+
input_mask = attention_mask
|
481 |
+
else:
|
482 |
+
input_mask = attention_mask.sum(-2) > 0
|
483 |
+
attention_mask = self.get_attention_mask(attention_mask)
|
484 |
+
relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos)
|
485 |
+
|
486 |
+
all_hidden_states = () if output_hidden_states else None
|
487 |
+
all_attentions = () if output_attentions else None
|
488 |
+
|
489 |
+
if isinstance(hidden_states, Sequence):
|
490 |
+
next_kv = hidden_states[0]
|
491 |
+
else:
|
492 |
+
next_kv = hidden_states
|
493 |
+
rel_embeddings = self.get_rel_embedding()
|
494 |
+
output_states = next_kv
|
495 |
+
for i, layer_module in enumerate(self.layer):
|
496 |
+
if output_hidden_states:
|
497 |
+
all_hidden_states = all_hidden_states + (output_states,)
|
498 |
+
|
499 |
+
if self.gradient_checkpointing and self.training:
|
500 |
+
output_states = self._gradient_checkpointing_func(
|
501 |
+
layer_module.__call__,
|
502 |
+
next_kv,
|
503 |
+
attention_mask,
|
504 |
+
query_states,
|
505 |
+
relative_pos,
|
506 |
+
rel_embeddings,
|
507 |
+
output_attentions,
|
508 |
+
)
|
509 |
+
else:
|
510 |
+
output_states = layer_module(
|
511 |
+
next_kv,
|
512 |
+
attention_mask,
|
513 |
+
query_states=query_states,
|
514 |
+
relative_pos=relative_pos,
|
515 |
+
rel_embeddings=rel_embeddings,
|
516 |
+
output_attentions=output_attentions,
|
517 |
+
)
|
518 |
+
|
519 |
+
if output_attentions:
|
520 |
+
output_states, att_m = output_states
|
521 |
+
|
522 |
+
if i == 0 and self.conv is not None:
|
523 |
+
output_states = self.conv(hidden_states, output_states, input_mask)
|
524 |
+
|
525 |
+
if query_states is not None:
|
526 |
+
query_states = output_states
|
527 |
+
if isinstance(hidden_states, Sequence):
|
528 |
+
next_kv = hidden_states[i + 1] if i + 1 < len(self.layer) else None
|
529 |
+
else:
|
530 |
+
next_kv = output_states
|
531 |
+
|
532 |
+
if output_attentions:
|
533 |
+
all_attentions = all_attentions + (att_m,)
|
534 |
+
|
535 |
+
if output_hidden_states:
|
536 |
+
all_hidden_states = all_hidden_states + (output_states,)
|
537 |
+
|
538 |
+
if not return_dict:
|
539 |
+
return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None)
|
540 |
+
return BaseModelOutput(
|
541 |
+
last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions
|
542 |
+
)
|
543 |
+
|
544 |
+
|
545 |
+
def make_log_bucket_position(relative_pos, bucket_size, max_position):
|
546 |
+
sign = torch.sign(relative_pos)
|
547 |
+
mid = bucket_size // 2
|
548 |
+
abs_pos = torch.where(
|
549 |
+
(relative_pos < mid) & (relative_pos > -mid),
|
550 |
+
torch.tensor(mid - 1).type_as(relative_pos),
|
551 |
+
torch.abs(relative_pos),
|
552 |
+
)
|
553 |
+
log_pos = (
|
554 |
+
torch.ceil(torch.log(abs_pos / mid) / torch.log(torch.tensor((max_position - 1) / mid)) * (mid - 1)) + mid
|
555 |
+
)
|
556 |
+
bucket_pos = torch.where(abs_pos <= mid, relative_pos.type_as(log_pos), log_pos * sign)
|
557 |
+
return bucket_pos
|
558 |
+
|
559 |
+
|
560 |
+
def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1, device=None):
|
561 |
+
"""
|
562 |
+
Build relative position according to the query and key
|
563 |
+
|
564 |
+
We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key
|
565 |
+
\\(P_k\\) is range from (0, key_size), The relative positions from query to key is \\(R_{q \\rightarrow k} = P_q -
|
566 |
+
P_k\\)
|
567 |
+
|
568 |
+
Args:
|
569 |
+
query_size (int): the length of query
|
570 |
+
key_size (int): the length of key
|
571 |
+
bucket_size (int): the size of position bucket
|
572 |
+
max_position (int): the maximum allowed absolute position
|
573 |
+
device (`torch.device`): the device on which tensors will be created.
|
574 |
+
|
575 |
+
Return:
|
576 |
+
`torch.LongTensor`: A tensor with shape [1, query_size, key_size]
|
577 |
+
"""
|
578 |
+
|
579 |
+
q_ids = torch.arange(0, query_size, device=device)
|
580 |
+
k_ids = torch.arange(0, key_size, device=device)
|
581 |
+
rel_pos_ids = q_ids[:, None] - k_ids[None, :]
|
582 |
+
if bucket_size > 0 and max_position > 0:
|
583 |
+
rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
|
584 |
+
rel_pos_ids = rel_pos_ids.to(torch.long)
|
585 |
+
rel_pos_ids = rel_pos_ids[:query_size, :]
|
586 |
+
rel_pos_ids = rel_pos_ids.unsqueeze(0)
|
587 |
+
return rel_pos_ids
|
588 |
+
|
589 |
+
|
590 |
+
@torch.jit.script
|
591 |
+
# Copied from transformers.models.deberta.modeling_deberta.c2p_dynamic_expand
|
592 |
+
def c2p_dynamic_expand(c2p_pos, query_layer, relative_pos):
|
593 |
+
return c2p_pos.expand([query_layer.size(0), query_layer.size(1), query_layer.size(2), relative_pos.size(-1)])
|
594 |
+
|
595 |
+
|
596 |
+
@torch.jit.script
|
597 |
+
# Copied from transformers.models.deberta.modeling_deberta.p2c_dynamic_expand
|
598 |
+
def p2c_dynamic_expand(c2p_pos, query_layer, key_layer):
|
599 |
+
return c2p_pos.expand([query_layer.size(0), query_layer.size(1), key_layer.size(-2), key_layer.size(-2)])
|
600 |
+
|
601 |
+
|
602 |
+
@torch.jit.script
|
603 |
+
# Copied from transformers.models.deberta.modeling_deberta.pos_dynamic_expand
|
604 |
+
def pos_dynamic_expand(pos_index, p2c_att, key_layer):
|
605 |
+
return pos_index.expand(p2c_att.size()[:2] + (pos_index.size(-2), key_layer.size(-2)))
|
606 |
+
|
607 |
+
|
608 |
+
class DisentangledSelfAttention(nn.Module):
|
609 |
+
"""
|
610 |
+
Disentangled self-attention module
|
611 |
+
|
612 |
+
Parameters:
|
613 |
+
config (`DebertaV2Config`):
|
614 |
+
A model config class instance with the configuration to build a new model. The schema is similar to
|
615 |
+
*BertConfig*, for more details, please refer [`DebertaV2Config`]
|
616 |
+
|
617 |
+
"""
|
618 |
+
|
619 |
+
def __init__(self, config):
|
620 |
+
super().__init__()
|
621 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
622 |
+
raise ValueError(
|
623 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
624 |
+
f"heads ({config.num_attention_heads})"
|
625 |
+
)
|
626 |
+
self.num_attention_heads = config.num_attention_heads
|
627 |
+
_attention_head_size = config.hidden_size // config.num_attention_heads
|
628 |
+
self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size)
|
629 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
630 |
+
self.query_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
631 |
+
self.key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
632 |
+
self.value_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
633 |
+
|
634 |
+
self.share_att_key = getattr(config, "share_att_key", False)
|
635 |
+
self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else []
|
636 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
637 |
+
|
638 |
+
if self.relative_attention:
|
639 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
640 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
641 |
+
if self.max_relative_positions < 1:
|
642 |
+
self.max_relative_positions = config.max_position_embeddings
|
643 |
+
self.pos_ebd_size = self.max_relative_positions
|
644 |
+
if self.position_buckets > 0:
|
645 |
+
self.pos_ebd_size = self.position_buckets
|
646 |
+
|
647 |
+
self.pos_dropout = StableDropout(config.hidden_dropout_prob)
|
648 |
+
|
649 |
+
if not self.share_att_key:
|
650 |
+
if "c2p" in self.pos_att_type:
|
651 |
+
self.pos_key_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
|
652 |
+
if "p2c" in self.pos_att_type:
|
653 |
+
self.pos_query_proj = nn.Linear(config.hidden_size, self.all_head_size)
|
654 |
+
|
655 |
+
self.dropout = StableDropout(config.attention_probs_dropout_prob)
|
656 |
+
|
657 |
+
def transpose_for_scores(self, x, attention_heads):
|
658 |
+
new_x_shape = x.size()[:-1] + (attention_heads, -1)
|
659 |
+
x = x.view(new_x_shape)
|
660 |
+
return x.permute(0, 2, 1, 3).contiguous().view(-1, x.size(1), x.size(-1))
|
661 |
+
|
662 |
+
def forward(
|
663 |
+
self,
|
664 |
+
hidden_states,
|
665 |
+
attention_mask,
|
666 |
+
output_attentions=False,
|
667 |
+
query_states=None,
|
668 |
+
relative_pos=None,
|
669 |
+
rel_embeddings=None,
|
670 |
+
):
|
671 |
+
"""
|
672 |
+
Call the module
|
673 |
+
|
674 |
+
Args:
|
675 |
+
hidden_states (`torch.FloatTensor`):
|
676 |
+
Input states to the module usually the output from previous layer, it will be the Q,K and V in
|
677 |
+
*Attention(Q,K,V)*
|
678 |
+
|
679 |
+
attention_mask (`torch.BoolTensor`):
|
680 |
+
An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum
|
681 |
+
sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j*
|
682 |
+
th token.
|
683 |
+
|
684 |
+
output_attentions (`bool`, optional):
|
685 |
+
Whether return the attention matrix.
|
686 |
+
|
687 |
+
query_states (`torch.FloatTensor`, optional):
|
688 |
+
The *Q* state in *Attention(Q,K,V)*.
|
689 |
+
|
690 |
+
relative_pos (`torch.LongTensor`):
|
691 |
+
The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with
|
692 |
+
values ranging in [*-max_relative_positions*, *max_relative_positions*].
|
693 |
+
|
694 |
+
rel_embeddings (`torch.FloatTensor`):
|
695 |
+
The embedding of relative distances. It's a tensor of shape [\\(2 \\times
|
696 |
+
\\text{max_relative_positions}\\), *hidden_size*].
|
697 |
+
|
698 |
+
|
699 |
+
"""
|
700 |
+
if query_states is None:
|
701 |
+
query_states = hidden_states
|
702 |
+
query_layer = self.transpose_for_scores(self.query_proj(query_states), self.num_attention_heads)
|
703 |
+
key_layer = self.transpose_for_scores(self.key_proj(hidden_states), self.num_attention_heads)
|
704 |
+
value_layer = self.transpose_for_scores(self.value_proj(hidden_states), self.num_attention_heads)
|
705 |
+
|
706 |
+
rel_att = None
|
707 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
708 |
+
scale_factor = 1
|
709 |
+
if "c2p" in self.pos_att_type:
|
710 |
+
scale_factor += 1
|
711 |
+
if "p2c" in self.pos_att_type:
|
712 |
+
scale_factor += 1
|
713 |
+
scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
|
714 |
+
attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2) / scale.to(dtype=query_layer.dtype))
|
715 |
+
if self.relative_attention:
|
716 |
+
rel_embeddings = self.pos_dropout(rel_embeddings)
|
717 |
+
rel_att = self.disentangled_attention_bias(
|
718 |
+
query_layer, key_layer, relative_pos, rel_embeddings, scale_factor
|
719 |
+
)
|
720 |
+
|
721 |
+
if rel_att is not None:
|
722 |
+
attention_scores = attention_scores + rel_att
|
723 |
+
attention_scores = attention_scores
|
724 |
+
attention_scores = attention_scores.view(
|
725 |
+
-1, self.num_attention_heads, attention_scores.size(-2), attention_scores.size(-1)
|
726 |
+
)
|
727 |
+
|
728 |
+
# bsz x height x length x dimension
|
729 |
+
attention_probs = XSoftmax.apply(attention_scores, attention_mask, -1)
|
730 |
+
attention_probs = self.dropout(attention_probs)
|
731 |
+
context_layer = torch.bmm(
|
732 |
+
attention_probs.view(-1, attention_probs.size(-2), attention_probs.size(-1)), value_layer
|
733 |
+
)
|
734 |
+
context_layer = (
|
735 |
+
context_layer.view(-1, self.num_attention_heads, context_layer.size(-2), context_layer.size(-1))
|
736 |
+
.permute(0, 2, 1, 3)
|
737 |
+
.contiguous()
|
738 |
+
)
|
739 |
+
new_context_layer_shape = context_layer.size()[:-2] + (-1,)
|
740 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
741 |
+
if output_attentions:
|
742 |
+
return (context_layer, attention_probs)
|
743 |
+
else:
|
744 |
+
return context_layer
|
745 |
+
|
746 |
+
def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor):
|
747 |
+
if relative_pos is None:
|
748 |
+
q = query_layer.size(-2)
|
749 |
+
relative_pos = build_relative_position(
|
750 |
+
q,
|
751 |
+
key_layer.size(-2),
|
752 |
+
bucket_size=self.position_buckets,
|
753 |
+
max_position=self.max_relative_positions,
|
754 |
+
device=query_layer.device,
|
755 |
+
)
|
756 |
+
if relative_pos.dim() == 2:
|
757 |
+
relative_pos = relative_pos.unsqueeze(0).unsqueeze(0)
|
758 |
+
elif relative_pos.dim() == 3:
|
759 |
+
relative_pos = relative_pos.unsqueeze(1)
|
760 |
+
# bsz x height x query x key
|
761 |
+
elif relative_pos.dim() != 4:
|
762 |
+
raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}")
|
763 |
+
|
764 |
+
att_span = self.pos_ebd_size
|
765 |
+
relative_pos = relative_pos.long().to(query_layer.device)
|
766 |
+
|
767 |
+
rel_embeddings = rel_embeddings[0 : att_span * 2, :].unsqueeze(0)
|
768 |
+
if self.share_att_key:
|
769 |
+
pos_query_layer = self.transpose_for_scores(
|
770 |
+
self.query_proj(rel_embeddings), self.num_attention_heads
|
771 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1)
|
772 |
+
pos_key_layer = self.transpose_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads).repeat(
|
773 |
+
query_layer.size(0) // self.num_attention_heads, 1, 1
|
774 |
+
)
|
775 |
+
else:
|
776 |
+
if "c2p" in self.pos_att_type:
|
777 |
+
pos_key_layer = self.transpose_for_scores(
|
778 |
+
self.pos_key_proj(rel_embeddings), self.num_attention_heads
|
779 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) # .split(self.all_head_size, dim=-1)
|
780 |
+
if "p2c" in self.pos_att_type:
|
781 |
+
pos_query_layer = self.transpose_for_scores(
|
782 |
+
self.pos_query_proj(rel_embeddings), self.num_attention_heads
|
783 |
+
).repeat(query_layer.size(0) // self.num_attention_heads, 1, 1) # .split(self.all_head_size, dim=-1)
|
784 |
+
|
785 |
+
score = 0
|
786 |
+
# content->position
|
787 |
+
if "c2p" in self.pos_att_type:
|
788 |
+
scale = torch.sqrt(torch.tensor(pos_key_layer.size(-1), dtype=torch.float) * scale_factor)
|
789 |
+
c2p_att = torch.bmm(query_layer, pos_key_layer.transpose(-1, -2))
|
790 |
+
c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1)
|
791 |
+
c2p_att = torch.gather(
|
792 |
+
c2p_att,
|
793 |
+
dim=-1,
|
794 |
+
index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]),
|
795 |
+
)
|
796 |
+
score += c2p_att / scale.to(dtype=c2p_att.dtype)
|
797 |
+
|
798 |
+
# position->content
|
799 |
+
if "p2c" in self.pos_att_type:
|
800 |
+
scale = torch.sqrt(torch.tensor(pos_query_layer.size(-1), dtype=torch.float) * scale_factor)
|
801 |
+
if key_layer.size(-2) != query_layer.size(-2):
|
802 |
+
r_pos = build_relative_position(
|
803 |
+
key_layer.size(-2),
|
804 |
+
key_layer.size(-2),
|
805 |
+
bucket_size=self.position_buckets,
|
806 |
+
max_position=self.max_relative_positions,
|
807 |
+
device=query_layer.device,
|
808 |
+
)
|
809 |
+
r_pos = r_pos.unsqueeze(0)
|
810 |
+
else:
|
811 |
+
r_pos = relative_pos
|
812 |
+
|
813 |
+
p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1)
|
814 |
+
p2c_att = torch.bmm(key_layer, pos_query_layer.transpose(-1, -2))
|
815 |
+
p2c_att = torch.gather(
|
816 |
+
p2c_att,
|
817 |
+
dim=-1,
|
818 |
+
index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]),
|
819 |
+
).transpose(-1, -2)
|
820 |
+
score += p2c_att / scale.to(dtype=p2c_att.dtype)
|
821 |
+
|
822 |
+
return score
|
823 |
+
|
824 |
+
|
825 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaEmbeddings with DebertaLayerNorm->LayerNorm
|
826 |
+
class DebertaV2Embeddings(nn.Module):
|
827 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
828 |
+
|
829 |
+
def __init__(self, config):
|
830 |
+
super().__init__()
|
831 |
+
pad_token_id = getattr(config, "pad_token_id", 0)
|
832 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
833 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, self.embedding_size, padding_idx=pad_token_id)
|
834 |
+
|
835 |
+
self.position_biased_input = getattr(config, "position_biased_input", True)
|
836 |
+
if not self.position_biased_input:
|
837 |
+
self.position_embeddings = None
|
838 |
+
else:
|
839 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.embedding_size)
|
840 |
+
|
841 |
+
if config.type_vocab_size > 0:
|
842 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, self.embedding_size)
|
843 |
+
|
844 |
+
if self.embedding_size != config.hidden_size:
|
845 |
+
self.embed_proj = nn.Linear(self.embedding_size, config.hidden_size, bias=False)
|
846 |
+
self.LayerNorm = LayerNorm(config.hidden_size, config.layer_norm_eps)
|
847 |
+
self.dropout = StableDropout(config.hidden_dropout_prob)
|
848 |
+
self.config = config
|
849 |
+
|
850 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
851 |
+
self.register_buffer(
|
852 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
853 |
+
)
|
854 |
+
|
855 |
+
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, mask=None, inputs_embeds=None):
|
856 |
+
if input_ids is not None:
|
857 |
+
input_shape = input_ids.size()
|
858 |
+
else:
|
859 |
+
input_shape = inputs_embeds.size()[:-1]
|
860 |
+
|
861 |
+
seq_length = input_shape[1]
|
862 |
+
|
863 |
+
if position_ids is None:
|
864 |
+
position_ids = self.position_ids[:, :seq_length]
|
865 |
+
|
866 |
+
if token_type_ids is None:
|
867 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
868 |
+
|
869 |
+
if inputs_embeds is None:
|
870 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
871 |
+
|
872 |
+
if self.position_embeddings is not None:
|
873 |
+
position_embeddings = self.position_embeddings(position_ids.long())
|
874 |
+
else:
|
875 |
+
position_embeddings = torch.zeros_like(inputs_embeds)
|
876 |
+
|
877 |
+
embeddings = inputs_embeds
|
878 |
+
if self.position_biased_input:
|
879 |
+
embeddings += position_embeddings
|
880 |
+
if self.config.type_vocab_size > 0:
|
881 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
882 |
+
embeddings += token_type_embeddings
|
883 |
+
|
884 |
+
if self.embedding_size != self.config.hidden_size:
|
885 |
+
embeddings = self.embed_proj(embeddings)
|
886 |
+
|
887 |
+
embeddings = self.LayerNorm(embeddings)
|
888 |
+
|
889 |
+
if mask is not None:
|
890 |
+
if mask.dim() != embeddings.dim():
|
891 |
+
if mask.dim() == 4:
|
892 |
+
mask = mask.squeeze(1).squeeze(1)
|
893 |
+
mask = mask.unsqueeze(2)
|
894 |
+
mask = mask.to(embeddings.dtype)
|
895 |
+
|
896 |
+
embeddings = embeddings * mask
|
897 |
+
|
898 |
+
embeddings = self.dropout(embeddings)
|
899 |
+
return embeddings
|
900 |
+
|
901 |
+
|
902 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaPreTrainedModel with Deberta->DebertaV2
|
903 |
+
class DebertaV2PreTrainedModel(PreTrainedModel):
|
904 |
+
"""
|
905 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
906 |
+
models.
|
907 |
+
"""
|
908 |
+
|
909 |
+
config_class = DebertaV2Config
|
910 |
+
base_model_prefix = "deberta"
|
911 |
+
_keys_to_ignore_on_load_unexpected = ["position_embeddings"]
|
912 |
+
supports_gradient_checkpointing = True
|
913 |
+
|
914 |
+
def _init_weights(self, module):
|
915 |
+
"""Initialize the weights."""
|
916 |
+
if isinstance(module, nn.Linear):
|
917 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
918 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
919 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
920 |
+
if module.bias is not None:
|
921 |
+
module.bias.data.zero_()
|
922 |
+
elif isinstance(module, nn.Embedding):
|
923 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
924 |
+
if module.padding_idx is not None:
|
925 |
+
module.weight.data[module.padding_idx].zero_()
|
926 |
+
|
927 |
+
|
928 |
+
DEBERTA_START_DOCSTRING = r"""
|
929 |
+
The DeBERTa model was proposed in [DeBERTa: Decoding-enhanced BERT with Disentangled
|
930 |
+
Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. It's build
|
931 |
+
on top of BERT/RoBERTa with two improvements, i.e. disentangled attention and enhanced mask decoder. With those two
|
932 |
+
improvements, it out perform BERT/RoBERTa on a majority of tasks with 80GB pretraining data.
|
933 |
+
|
934 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
935 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
936 |
+
and behavior.
|
937 |
+
|
938 |
+
|
939 |
+
Parameters:
|
940 |
+
config ([`DebertaV2Config`]): Model configuration class with all the parameters of the model.
|
941 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
942 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
943 |
+
"""
|
944 |
+
|
945 |
+
DEBERTA_INPUTS_DOCSTRING = r"""
|
946 |
+
Args:
|
947 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
948 |
+
Indices of input sequence tokens in the vocabulary.
|
949 |
+
|
950 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
951 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
952 |
+
|
953 |
+
[What are input IDs?](../glossary#input-ids)
|
954 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
955 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
956 |
+
|
957 |
+
- 1 for tokens that are **not masked**,
|
958 |
+
- 0 for tokens that are **masked**.
|
959 |
+
|
960 |
+
[What are attention masks?](../glossary#attention-mask)
|
961 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
962 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
963 |
+
1]`:
|
964 |
+
|
965 |
+
- 0 corresponds to a *sentence A* token,
|
966 |
+
- 1 corresponds to a *sentence B* token.
|
967 |
+
|
968 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
969 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
970 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
971 |
+
config.max_position_embeddings - 1]`.
|
972 |
+
|
973 |
+
[What are position IDs?](../glossary#position-ids)
|
974 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
975 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
976 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
977 |
+
model's internal embedding lookup matrix.
|
978 |
+
output_attentions (`bool`, *optional*):
|
979 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
980 |
+
tensors for more detail.
|
981 |
+
output_hidden_states (`bool`, *optional*):
|
982 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
983 |
+
more detail.
|
984 |
+
return_dict (`bool`, *optional*):
|
985 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
986 |
+
"""
|
987 |
+
|
988 |
+
|
989 |
+
@add_start_docstrings(
|
990 |
+
"The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.",
|
991 |
+
DEBERTA_START_DOCSTRING,
|
992 |
+
)
|
993 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaModel with Deberta->DebertaV2
|
994 |
+
class DebertaV2Model(DebertaV2PreTrainedModel):
|
995 |
+
def __init__(self, config):
|
996 |
+
super().__init__(config)
|
997 |
+
|
998 |
+
self.embeddings = DebertaV2Embeddings(config)
|
999 |
+
self.encoder = DebertaV2Encoder(config)
|
1000 |
+
self.z_steps = 0
|
1001 |
+
self.config = config
|
1002 |
+
# Initialize weights and apply final processing
|
1003 |
+
self.post_init()
|
1004 |
+
|
1005 |
+
def get_input_embeddings(self):
|
1006 |
+
return self.embeddings.word_embeddings
|
1007 |
+
|
1008 |
+
def set_input_embeddings(self, new_embeddings):
|
1009 |
+
self.embeddings.word_embeddings = new_embeddings
|
1010 |
+
|
1011 |
+
def _prune_heads(self, heads_to_prune):
|
1012 |
+
"""
|
1013 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
1014 |
+
class PreTrainedModel
|
1015 |
+
"""
|
1016 |
+
raise NotImplementedError("The prune function is not implemented in DeBERTa model.")
|
1017 |
+
|
1018 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1019 |
+
@add_code_sample_docstrings(
|
1020 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1021 |
+
output_type=BaseModelOutput,
|
1022 |
+
config_class=_CONFIG_FOR_DOC,
|
1023 |
+
)
|
1024 |
+
def forward(
|
1025 |
+
self,
|
1026 |
+
input_ids: Optional[torch.Tensor] = None,
|
1027 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1028 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1029 |
+
position_ids: Optional[torch.Tensor] = None,
|
1030 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1031 |
+
output_attentions: Optional[bool] = None,
|
1032 |
+
output_hidden_states: Optional[bool] = None,
|
1033 |
+
return_dict: Optional[bool] = None,
|
1034 |
+
) -> Union[Tuple, BaseModelOutput]:
|
1035 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1036 |
+
output_hidden_states = (
|
1037 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1038 |
+
)
|
1039 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1040 |
+
|
1041 |
+
if input_ids is not None and inputs_embeds is not None:
|
1042 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1043 |
+
elif input_ids is not None:
|
1044 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
1045 |
+
input_shape = input_ids.size()
|
1046 |
+
elif inputs_embeds is not None:
|
1047 |
+
input_shape = inputs_embeds.size()[:-1]
|
1048 |
+
else:
|
1049 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1050 |
+
|
1051 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1052 |
+
|
1053 |
+
if attention_mask is None:
|
1054 |
+
attention_mask = torch.ones(input_shape, device=device)
|
1055 |
+
if token_type_ids is None:
|
1056 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
1057 |
+
|
1058 |
+
embedding_output = self.embeddings(
|
1059 |
+
input_ids=input_ids,
|
1060 |
+
token_type_ids=token_type_ids,
|
1061 |
+
position_ids=position_ids,
|
1062 |
+
mask=attention_mask,
|
1063 |
+
inputs_embeds=inputs_embeds,
|
1064 |
+
)
|
1065 |
+
|
1066 |
+
encoder_outputs = self.encoder(
|
1067 |
+
embedding_output,
|
1068 |
+
attention_mask,
|
1069 |
+
output_hidden_states=True,
|
1070 |
+
output_attentions=output_attentions,
|
1071 |
+
return_dict=return_dict,
|
1072 |
+
)
|
1073 |
+
encoded_layers = encoder_outputs[1]
|
1074 |
+
|
1075 |
+
if self.z_steps > 1:
|
1076 |
+
hidden_states = encoded_layers[-2]
|
1077 |
+
layers = [self.encoder.layer[-1] for _ in range(self.z_steps)]
|
1078 |
+
query_states = encoded_layers[-1]
|
1079 |
+
rel_embeddings = self.encoder.get_rel_embedding()
|
1080 |
+
attention_mask = self.encoder.get_attention_mask(attention_mask)
|
1081 |
+
rel_pos = self.encoder.get_rel_pos(embedding_output)
|
1082 |
+
for layer in layers[1:]:
|
1083 |
+
query_states = layer(
|
1084 |
+
hidden_states,
|
1085 |
+
attention_mask,
|
1086 |
+
output_attentions=False,
|
1087 |
+
query_states=query_states,
|
1088 |
+
relative_pos=rel_pos,
|
1089 |
+
rel_embeddings=rel_embeddings,
|
1090 |
+
)
|
1091 |
+
encoded_layers.append(query_states)
|
1092 |
+
|
1093 |
+
sequence_output = encoded_layers[-1]
|
1094 |
+
|
1095 |
+
if not return_dict:
|
1096 |
+
return (sequence_output,) + encoder_outputs[(1 if output_hidden_states else 2) :]
|
1097 |
+
|
1098 |
+
return BaseModelOutput(
|
1099 |
+
last_hidden_state=sequence_output,
|
1100 |
+
hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
|
1101 |
+
attentions=encoder_outputs.attentions,
|
1102 |
+
)
|
1103 |
+
|
1104 |
+
|
1105 |
+
@add_start_docstrings("""DeBERTa Model with a `language modeling` head on top.""", DEBERTA_START_DOCSTRING)
|
1106 |
+
class DebertaV2ForMaskedLM(DebertaV2PreTrainedModel):
|
1107 |
+
_tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
|
1108 |
+
|
1109 |
+
def __init__(self, config):
|
1110 |
+
super().__init__(config)
|
1111 |
+
|
1112 |
+
self.deberta = DebertaV2Model(config)
|
1113 |
+
self.cls = DebertaV2OnlyMLMHead(config)
|
1114 |
+
|
1115 |
+
# Initialize weights and apply final processing
|
1116 |
+
self.post_init()
|
1117 |
+
|
1118 |
+
def get_output_embeddings(self):
|
1119 |
+
return self.cls.predictions.decoder
|
1120 |
+
|
1121 |
+
def set_output_embeddings(self, new_embeddings):
|
1122 |
+
self.cls.predictions.decoder = new_embeddings
|
1123 |
+
|
1124 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1125 |
+
@add_code_sample_docstrings(
|
1126 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1127 |
+
output_type=MaskedLMOutput,
|
1128 |
+
config_class=_CONFIG_FOR_DOC,
|
1129 |
+
mask="[MASK]",
|
1130 |
+
)
|
1131 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForMaskedLM.forward with Deberta->DebertaV2
|
1132 |
+
def forward(
|
1133 |
+
self,
|
1134 |
+
input_ids: Optional[torch.Tensor] = None,
|
1135 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1136 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1137 |
+
position_ids: Optional[torch.Tensor] = None,
|
1138 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1139 |
+
labels: Optional[torch.Tensor] = None,
|
1140 |
+
output_attentions: Optional[bool] = None,
|
1141 |
+
output_hidden_states: Optional[bool] = None,
|
1142 |
+
return_dict: Optional[bool] = None,
|
1143 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
1144 |
+
r"""
|
1145 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1146 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
1147 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
1148 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1149 |
+
"""
|
1150 |
+
|
1151 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1152 |
+
|
1153 |
+
outputs = self.deberta(
|
1154 |
+
input_ids,
|
1155 |
+
attention_mask=attention_mask,
|
1156 |
+
token_type_ids=token_type_ids,
|
1157 |
+
position_ids=position_ids,
|
1158 |
+
inputs_embeds=inputs_embeds,
|
1159 |
+
output_attentions=output_attentions,
|
1160 |
+
output_hidden_states=output_hidden_states,
|
1161 |
+
return_dict=return_dict,
|
1162 |
+
)
|
1163 |
+
|
1164 |
+
sequence_output = outputs[0]
|
1165 |
+
prediction_scores = self.cls(sequence_output)
|
1166 |
+
|
1167 |
+
masked_lm_loss = None
|
1168 |
+
if labels is not None:
|
1169 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
1170 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1171 |
+
|
1172 |
+
if not return_dict:
|
1173 |
+
output = (prediction_scores,) + outputs[1:]
|
1174 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
1175 |
+
|
1176 |
+
return MaskedLMOutput(
|
1177 |
+
loss=masked_lm_loss,
|
1178 |
+
logits=prediction_scores,
|
1179 |
+
hidden_states=outputs.hidden_states,
|
1180 |
+
attentions=outputs.attentions,
|
1181 |
+
)
|
1182 |
+
|
1183 |
+
|
1184 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaPredictionHeadTransform with Deberta->DebertaV2
|
1185 |
+
class DebertaV2PredictionHeadTransform(nn.Module):
|
1186 |
+
def __init__(self, config):
|
1187 |
+
super().__init__()
|
1188 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
1189 |
+
|
1190 |
+
self.dense = nn.Linear(config.hidden_size, self.embedding_size)
|
1191 |
+
if isinstance(config.hidden_act, str):
|
1192 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
1193 |
+
else:
|
1194 |
+
self.transform_act_fn = config.hidden_act
|
1195 |
+
self.LayerNorm = nn.LayerNorm(self.embedding_size, eps=config.layer_norm_eps)
|
1196 |
+
|
1197 |
+
def forward(self, hidden_states):
|
1198 |
+
hidden_states = self.dense(hidden_states)
|
1199 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
1200 |
+
hidden_states = self.LayerNorm(hidden_states)
|
1201 |
+
return hidden_states
|
1202 |
+
|
1203 |
+
|
1204 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaLMPredictionHead with Deberta->DebertaV2
|
1205 |
+
class DebertaV2LMPredictionHead(nn.Module):
|
1206 |
+
def __init__(self, config):
|
1207 |
+
super().__init__()
|
1208 |
+
self.transform = DebertaV2PredictionHeadTransform(config)
|
1209 |
+
|
1210 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
1211 |
+
# The output weights are the same as the input embeddings, but there is
|
1212 |
+
# an output-only bias for each token.
|
1213 |
+
self.decoder = nn.Linear(self.embedding_size, config.vocab_size, bias=False)
|
1214 |
+
|
1215 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
1216 |
+
|
1217 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
1218 |
+
self.decoder.bias = self.bias
|
1219 |
+
|
1220 |
+
def forward(self, hidden_states):
|
1221 |
+
hidden_states = self.transform(hidden_states)
|
1222 |
+
hidden_states = self.decoder(hidden_states)
|
1223 |
+
return hidden_states
|
1224 |
+
|
1225 |
+
|
1226 |
+
# copied from transformers.models.bert.BertOnlyMLMHead with bert -> deberta
|
1227 |
+
class DebertaV2OnlyMLMHead(nn.Module):
|
1228 |
+
def __init__(self, config):
|
1229 |
+
super().__init__()
|
1230 |
+
self.predictions = DebertaV2LMPredictionHead(config)
|
1231 |
+
|
1232 |
+
def forward(self, sequence_output):
|
1233 |
+
prediction_scores = self.predictions(sequence_output)
|
1234 |
+
return prediction_scores
|
1235 |
+
|
1236 |
+
|
1237 |
+
@add_start_docstrings(
|
1238 |
+
"""
|
1239 |
+
DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
1240 |
+
pooled output) e.g. for GLUE tasks.
|
1241 |
+
""",
|
1242 |
+
DEBERTA_START_DOCSTRING,
|
1243 |
+
)
|
1244 |
+
class DebertaV2ForSequenceClassification(DebertaV2PreTrainedModel):
|
1245 |
+
def __init__(self, config):
|
1246 |
+
super().__init__(config)
|
1247 |
+
|
1248 |
+
num_labels = getattr(config, "num_labels", 2)
|
1249 |
+
self.num_labels = num_labels
|
1250 |
+
|
1251 |
+
self.deberta = DebertaV2Model(config)
|
1252 |
+
self.pooler = ContextPooler(config)
|
1253 |
+
output_dim = self.pooler.output_dim
|
1254 |
+
|
1255 |
+
self.classifier = nn.Linear(output_dim, num_labels)
|
1256 |
+
drop_out = getattr(config, "cls_dropout", None)
|
1257 |
+
drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out
|
1258 |
+
self.dropout = StableDropout(drop_out)
|
1259 |
+
|
1260 |
+
# Initialize weights and apply final processing
|
1261 |
+
self.post_init()
|
1262 |
+
|
1263 |
+
def get_input_embeddings(self):
|
1264 |
+
return self.deberta.get_input_embeddings()
|
1265 |
+
|
1266 |
+
def set_input_embeddings(self, new_embeddings):
|
1267 |
+
self.deberta.set_input_embeddings(new_embeddings)
|
1268 |
+
|
1269 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1270 |
+
@add_code_sample_docstrings(
|
1271 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1272 |
+
output_type=SequenceClassifierOutput,
|
1273 |
+
config_class=_CONFIG_FOR_DOC,
|
1274 |
+
)
|
1275 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForSequenceClassification.forward with Deberta->DebertaV2
|
1276 |
+
def forward(
|
1277 |
+
self,
|
1278 |
+
input_ids: Optional[torch.Tensor] = None,
|
1279 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1280 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1281 |
+
position_ids: Optional[torch.Tensor] = None,
|
1282 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1283 |
+
labels: Optional[torch.Tensor] = None,
|
1284 |
+
output_attentions: Optional[bool] = None,
|
1285 |
+
output_hidden_states: Optional[bool] = None,
|
1286 |
+
return_dict: Optional[bool] = None,
|
1287 |
+
) -> Union[Tuple, SequenceClassifierOutput]:
|
1288 |
+
r"""
|
1289 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1290 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1291 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1292 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1293 |
+
"""
|
1294 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1295 |
+
|
1296 |
+
outputs = self.deberta(
|
1297 |
+
input_ids,
|
1298 |
+
token_type_ids=token_type_ids,
|
1299 |
+
attention_mask=attention_mask,
|
1300 |
+
position_ids=position_ids,
|
1301 |
+
inputs_embeds=inputs_embeds,
|
1302 |
+
output_attentions=output_attentions,
|
1303 |
+
output_hidden_states=output_hidden_states,
|
1304 |
+
return_dict=return_dict,
|
1305 |
+
)
|
1306 |
+
|
1307 |
+
encoder_layer = outputs[0]
|
1308 |
+
pooled_output = self.pooler(encoder_layer)
|
1309 |
+
pooled_output = self.dropout(pooled_output)
|
1310 |
+
logits = self.classifier(pooled_output)
|
1311 |
+
|
1312 |
+
loss = None
|
1313 |
+
if labels is not None:
|
1314 |
+
if self.config.problem_type is None:
|
1315 |
+
if self.num_labels == 1:
|
1316 |
+
# regression task
|
1317 |
+
loss_fn = nn.MSELoss()
|
1318 |
+
logits = logits.view(-1).to(labels.dtype)
|
1319 |
+
loss = loss_fn(logits, labels.view(-1))
|
1320 |
+
elif labels.dim() == 1 or labels.size(-1) == 1:
|
1321 |
+
label_index = (labels >= 0).nonzero()
|
1322 |
+
labels = labels.long()
|
1323 |
+
if label_index.size(0) > 0:
|
1324 |
+
labeled_logits = torch.gather(
|
1325 |
+
logits, 0, label_index.expand(label_index.size(0), logits.size(1))
|
1326 |
+
)
|
1327 |
+
labels = torch.gather(labels, 0, label_index.view(-1))
|
1328 |
+
loss_fct = CrossEntropyLoss()
|
1329 |
+
loss = loss_fct(labeled_logits.view(-1, self.num_labels).float(), labels.view(-1))
|
1330 |
+
else:
|
1331 |
+
loss = torch.tensor(0).to(logits)
|
1332 |
+
else:
|
1333 |
+
log_softmax = nn.LogSoftmax(-1)
|
1334 |
+
loss = -((log_softmax(logits) * labels).sum(-1)).mean()
|
1335 |
+
elif self.config.problem_type == "regression":
|
1336 |
+
loss_fct = MSELoss()
|
1337 |
+
if self.num_labels == 1:
|
1338 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
1339 |
+
else:
|
1340 |
+
loss = loss_fct(logits, labels)
|
1341 |
+
elif self.config.problem_type == "single_label_classification":
|
1342 |
+
loss_fct = CrossEntropyLoss()
|
1343 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1344 |
+
elif self.config.problem_type == "multi_label_classification":
|
1345 |
+
loss_fct = BCEWithLogitsLoss()
|
1346 |
+
loss = loss_fct(logits, labels)
|
1347 |
+
if not return_dict:
|
1348 |
+
output = (logits,) + outputs[1:]
|
1349 |
+
return ((loss,) + output) if loss is not None else output
|
1350 |
+
|
1351 |
+
return SequenceClassifierOutput(
|
1352 |
+
loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
1353 |
+
)
|
1354 |
+
|
1355 |
+
|
1356 |
+
@add_start_docstrings(
|
1357 |
+
"""
|
1358 |
+
DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
1359 |
+
Named-Entity-Recognition (NER) tasks.
|
1360 |
+
""",
|
1361 |
+
DEBERTA_START_DOCSTRING,
|
1362 |
+
)
|
1363 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForTokenClassification with Deberta->DebertaV2
|
1364 |
+
class DebertaV2ForTokenClassification(DebertaV2PreTrainedModel):
|
1365 |
+
def __init__(self, config):
|
1366 |
+
super().__init__(config)
|
1367 |
+
self.num_labels = config.num_labels
|
1368 |
+
|
1369 |
+
self.deberta = DebertaV2Model(config)
|
1370 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
1371 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1372 |
+
|
1373 |
+
# Initialize weights and apply final processing
|
1374 |
+
self.post_init()
|
1375 |
+
|
1376 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1377 |
+
@add_code_sample_docstrings(
|
1378 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1379 |
+
output_type=TokenClassifierOutput,
|
1380 |
+
config_class=_CONFIG_FOR_DOC,
|
1381 |
+
)
|
1382 |
+
def forward(
|
1383 |
+
self,
|
1384 |
+
input_ids: Optional[torch.Tensor] = None,
|
1385 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1386 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1387 |
+
position_ids: Optional[torch.Tensor] = None,
|
1388 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1389 |
+
labels: Optional[torch.Tensor] = None,
|
1390 |
+
output_attentions: Optional[bool] = None,
|
1391 |
+
output_hidden_states: Optional[bool] = None,
|
1392 |
+
return_dict: Optional[bool] = None,
|
1393 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1394 |
+
r"""
|
1395 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1396 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
1397 |
+
"""
|
1398 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1399 |
+
|
1400 |
+
outputs = self.deberta(
|
1401 |
+
input_ids,
|
1402 |
+
attention_mask=attention_mask,
|
1403 |
+
token_type_ids=token_type_ids,
|
1404 |
+
position_ids=position_ids,
|
1405 |
+
inputs_embeds=inputs_embeds,
|
1406 |
+
output_attentions=output_attentions,
|
1407 |
+
output_hidden_states=output_hidden_states,
|
1408 |
+
return_dict=return_dict,
|
1409 |
+
)
|
1410 |
+
|
1411 |
+
sequence_output = outputs[0]
|
1412 |
+
|
1413 |
+
sequence_output = self.dropout(sequence_output)
|
1414 |
+
logits = self.classifier(sequence_output)
|
1415 |
+
|
1416 |
+
loss = None
|
1417 |
+
if labels is not None:
|
1418 |
+
loss_fct = CrossEntropyLoss()
|
1419 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1420 |
+
|
1421 |
+
if not return_dict:
|
1422 |
+
output = (logits,) + outputs[1:]
|
1423 |
+
return ((loss,) + output) if loss is not None else output
|
1424 |
+
|
1425 |
+
return TokenClassifierOutput(
|
1426 |
+
loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
|
1427 |
+
)
|
1428 |
+
|
1429 |
+
|
1430 |
+
@add_start_docstrings(
|
1431 |
+
"""
|
1432 |
+
DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
1433 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1434 |
+
""",
|
1435 |
+
DEBERTA_START_DOCSTRING,
|
1436 |
+
)
|
1437 |
+
class DebertaV2ForQuestionAnswering(DebertaV2PreTrainedModel):
|
1438 |
+
def __init__(self, config):
|
1439 |
+
super().__init__(config)
|
1440 |
+
self.num_labels = config.num_labels
|
1441 |
+
|
1442 |
+
self.deberta = DebertaV2Model(config)
|
1443 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
1444 |
+
|
1445 |
+
# Initialize weights and apply final processing
|
1446 |
+
self.post_init()
|
1447 |
+
|
1448 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1449 |
+
@add_code_sample_docstrings(
|
1450 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1451 |
+
output_type=QuestionAnsweringModelOutput,
|
1452 |
+
config_class=_CONFIG_FOR_DOC,
|
1453 |
+
qa_target_start_index=_QA_TARGET_START_INDEX,
|
1454 |
+
qa_target_end_index=_QA_TARGET_END_INDEX,
|
1455 |
+
)
|
1456 |
+
# Copied from transformers.models.deberta.modeling_deberta.DebertaForQuestionAnswering.forward with Deberta->DebertaV2
|
1457 |
+
def forward(
|
1458 |
+
self,
|
1459 |
+
input_ids: Optional[torch.Tensor] = None,
|
1460 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1461 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1462 |
+
position_ids: Optional[torch.Tensor] = None,
|
1463 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1464 |
+
start_positions: Optional[torch.Tensor] = None,
|
1465 |
+
end_positions: Optional[torch.Tensor] = None,
|
1466 |
+
output_attentions: Optional[bool] = None,
|
1467 |
+
output_hidden_states: Optional[bool] = None,
|
1468 |
+
return_dict: Optional[bool] = None,
|
1469 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1470 |
+
r"""
|
1471 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1472 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1473 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1474 |
+
are not taken into account for computing the loss.
|
1475 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1476 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1477 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1478 |
+
are not taken into account for computing the loss.
|
1479 |
+
"""
|
1480 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1481 |
+
|
1482 |
+
outputs = self.deberta(
|
1483 |
+
input_ids,
|
1484 |
+
attention_mask=attention_mask,
|
1485 |
+
token_type_ids=token_type_ids,
|
1486 |
+
position_ids=position_ids,
|
1487 |
+
inputs_embeds=inputs_embeds,
|
1488 |
+
output_attentions=output_attentions,
|
1489 |
+
output_hidden_states=output_hidden_states,
|
1490 |
+
return_dict=return_dict,
|
1491 |
+
)
|
1492 |
+
|
1493 |
+
sequence_output = outputs[0]
|
1494 |
+
|
1495 |
+
logits = self.qa_outputs(sequence_output)
|
1496 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1497 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1498 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1499 |
+
|
1500 |
+
total_loss = None
|
1501 |
+
if start_positions is not None and end_positions is not None:
|
1502 |
+
# If we are on multi-GPU, split add a dimension
|
1503 |
+
if len(start_positions.size()) > 1:
|
1504 |
+
start_positions = start_positions.squeeze(-1)
|
1505 |
+
if len(end_positions.size()) > 1:
|
1506 |
+
end_positions = end_positions.squeeze(-1)
|
1507 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1508 |
+
ignored_index = start_logits.size(1)
|
1509 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1510 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1511 |
+
|
1512 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1513 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1514 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1515 |
+
total_loss = (start_loss + end_loss) / 2
|
1516 |
+
|
1517 |
+
if not return_dict:
|
1518 |
+
output = (start_logits, end_logits) + outputs[1:]
|
1519 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1520 |
+
|
1521 |
+
return QuestionAnsweringModelOutput(
|
1522 |
+
loss=total_loss,
|
1523 |
+
start_logits=start_logits,
|
1524 |
+
end_logits=end_logits,
|
1525 |
+
hidden_states=outputs.hidden_states,
|
1526 |
+
attentions=outputs.attentions,
|
1527 |
+
)
|
1528 |
+
|
1529 |
+
|
1530 |
+
@add_start_docstrings(
|
1531 |
+
"""
|
1532 |
+
DeBERTa Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
1533 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
1534 |
+
""",
|
1535 |
+
DEBERTA_START_DOCSTRING,
|
1536 |
+
)
|
1537 |
+
class DebertaV2ForMultipleChoice(DebertaV2PreTrainedModel):
|
1538 |
+
def __init__(self, config):
|
1539 |
+
super().__init__(config)
|
1540 |
+
|
1541 |
+
num_labels = getattr(config, "num_labels", 2)
|
1542 |
+
self.num_labels = num_labels
|
1543 |
+
|
1544 |
+
self.deberta = DebertaV2Model(config)
|
1545 |
+
self.pooler = ContextPooler(config)
|
1546 |
+
output_dim = self.pooler.output_dim
|
1547 |
+
|
1548 |
+
self.classifier = nn.Linear(output_dim, 1)
|
1549 |
+
drop_out = getattr(config, "cls_dropout", None)
|
1550 |
+
drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out
|
1551 |
+
self.dropout = StableDropout(drop_out)
|
1552 |
+
|
1553 |
+
self.init_weights()
|
1554 |
+
|
1555 |
+
def get_input_embeddings(self):
|
1556 |
+
return self.deberta.get_input_embeddings()
|
1557 |
+
|
1558 |
+
def set_input_embeddings(self, new_embeddings):
|
1559 |
+
self.deberta.set_input_embeddings(new_embeddings)
|
1560 |
+
|
1561 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1562 |
+
@add_code_sample_docstrings(
|
1563 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1564 |
+
output_type=MultipleChoiceModelOutput,
|
1565 |
+
config_class=_CONFIG_FOR_DOC,
|
1566 |
+
)
|
1567 |
+
def forward(
|
1568 |
+
self,
|
1569 |
+
input_ids: Optional[torch.Tensor] = None,
|
1570 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1571 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1572 |
+
position_ids: Optional[torch.Tensor] = None,
|
1573 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1574 |
+
labels: Optional[torch.Tensor] = None,
|
1575 |
+
output_attentions: Optional[bool] = None,
|
1576 |
+
output_hidden_states: Optional[bool] = None,
|
1577 |
+
return_dict: Optional[bool] = None,
|
1578 |
+
) -> Union[Tuple, MultipleChoiceModelOutput]:
|
1579 |
+
r"""
|
1580 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1581 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
1582 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
1583 |
+
`input_ids` above)
|
1584 |
+
"""
|
1585 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1586 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
1587 |
+
|
1588 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
1589 |
+
flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
1590 |
+
flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
1591 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
1592 |
+
flat_inputs_embeds = (
|
1593 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
1594 |
+
if inputs_embeds is not None
|
1595 |
+
else None
|
1596 |
+
)
|
1597 |
+
|
1598 |
+
outputs = self.deberta(
|
1599 |
+
flat_input_ids,
|
1600 |
+
position_ids=flat_position_ids,
|
1601 |
+
token_type_ids=flat_token_type_ids,
|
1602 |
+
attention_mask=flat_attention_mask,
|
1603 |
+
inputs_embeds=flat_inputs_embeds,
|
1604 |
+
output_attentions=output_attentions,
|
1605 |
+
output_hidden_states=output_hidden_states,
|
1606 |
+
return_dict=return_dict,
|
1607 |
+
)
|
1608 |
+
|
1609 |
+
encoder_layer = outputs[0]
|
1610 |
+
pooled_output = self.pooler(encoder_layer)
|
1611 |
+
pooled_output = self.dropout(pooled_output)
|
1612 |
+
logits = self.classifier(pooled_output)
|
1613 |
+
reshaped_logits = logits.view(-1, num_choices)
|
1614 |
+
|
1615 |
+
loss = None
|
1616 |
+
if labels is not None:
|
1617 |
+
loss_fct = CrossEntropyLoss()
|
1618 |
+
loss = loss_fct(reshaped_logits, labels)
|
1619 |
+
|
1620 |
+
if not return_dict:
|
1621 |
+
output = (reshaped_logits,) + outputs[1:]
|
1622 |
+
return ((loss,) + output) if loss is not None else output
|
1623 |
+
|
1624 |
+
return MultipleChoiceModelOutput(
|
1625 |
+
loss=loss,
|
1626 |
+
logits=reshaped_logits,
|
1627 |
+
hidden_states=outputs.hidden_states,
|
1628 |
+
attentions=outputs.attentions,
|
1629 |
+
)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/modeling_tf_deberta_v2.py
ADDED
@@ -0,0 +1,1874 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 Microsoft 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 |
+
""" TF 2.0 DeBERTa-v2 model."""
|
16 |
+
|
17 |
+
from __future__ import annotations
|
18 |
+
|
19 |
+
from typing import Dict, Optional, Tuple, Union
|
20 |
+
|
21 |
+
import numpy as np
|
22 |
+
import tensorflow as tf
|
23 |
+
|
24 |
+
from ...activations_tf import get_tf_activation
|
25 |
+
from ...modeling_tf_outputs import (
|
26 |
+
TFBaseModelOutput,
|
27 |
+
TFMaskedLMOutput,
|
28 |
+
TFMultipleChoiceModelOutput,
|
29 |
+
TFQuestionAnsweringModelOutput,
|
30 |
+
TFSequenceClassifierOutput,
|
31 |
+
TFTokenClassifierOutput,
|
32 |
+
)
|
33 |
+
from ...modeling_tf_utils import (
|
34 |
+
TFMaskedLanguageModelingLoss,
|
35 |
+
TFModelInputType,
|
36 |
+
TFMultipleChoiceLoss,
|
37 |
+
TFPreTrainedModel,
|
38 |
+
TFQuestionAnsweringLoss,
|
39 |
+
TFSequenceClassificationLoss,
|
40 |
+
TFTokenClassificationLoss,
|
41 |
+
get_initializer,
|
42 |
+
keras,
|
43 |
+
unpack_inputs,
|
44 |
+
)
|
45 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
46 |
+
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
47 |
+
from .configuration_deberta_v2 import DebertaV2Config
|
48 |
+
|
49 |
+
|
50 |
+
logger = logging.get_logger(__name__)
|
51 |
+
|
52 |
+
_CONFIG_FOR_DOC = "DebertaV2Config"
|
53 |
+
_CHECKPOINT_FOR_DOC = "kamalkraj/deberta-v2-xlarge"
|
54 |
+
|
55 |
+
|
56 |
+
from ..deprecated._archive_maps import TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST # noqa: F401, E402
|
57 |
+
|
58 |
+
|
59 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaContextPooler with Deberta->DebertaV2
|
60 |
+
class TFDebertaV2ContextPooler(keras.layers.Layer):
|
61 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
62 |
+
super().__init__(**kwargs)
|
63 |
+
self.dense = keras.layers.Dense(config.pooler_hidden_size, name="dense")
|
64 |
+
self.dropout = TFDebertaV2StableDropout(config.pooler_dropout, name="dropout")
|
65 |
+
self.config = config
|
66 |
+
|
67 |
+
def call(self, hidden_states, training: bool = False):
|
68 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
69 |
+
# to the first token.
|
70 |
+
context_token = hidden_states[:, 0]
|
71 |
+
context_token = self.dropout(context_token, training=training)
|
72 |
+
pooled_output = self.dense(context_token)
|
73 |
+
pooled_output = get_tf_activation(self.config.pooler_hidden_act)(pooled_output)
|
74 |
+
return pooled_output
|
75 |
+
|
76 |
+
@property
|
77 |
+
def output_dim(self) -> int:
|
78 |
+
return self.config.hidden_size
|
79 |
+
|
80 |
+
def build(self, input_shape=None):
|
81 |
+
if self.built:
|
82 |
+
return
|
83 |
+
self.built = True
|
84 |
+
if getattr(self, "dense", None) is not None:
|
85 |
+
with tf.name_scope(self.dense.name):
|
86 |
+
self.dense.build([None, None, self.config.pooler_hidden_size])
|
87 |
+
if getattr(self, "dropout", None) is not None:
|
88 |
+
with tf.name_scope(self.dropout.name):
|
89 |
+
self.dropout.build(None)
|
90 |
+
|
91 |
+
|
92 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaXSoftmax with Deberta->DebertaV2
|
93 |
+
class TFDebertaV2XSoftmax(keras.layers.Layer):
|
94 |
+
"""
|
95 |
+
Masked Softmax which is optimized for saving memory
|
96 |
+
|
97 |
+
Args:
|
98 |
+
input (`tf.Tensor`): The input tensor that will apply softmax.
|
99 |
+
mask (`tf.Tensor`): The mask matrix where 0 indicate that element will be ignored in the softmax calculation.
|
100 |
+
dim (int): The dimension that will apply softmax
|
101 |
+
"""
|
102 |
+
|
103 |
+
def __init__(self, axis=-1, **kwargs):
|
104 |
+
super().__init__(**kwargs)
|
105 |
+
self.axis = axis
|
106 |
+
|
107 |
+
def call(self, inputs: tf.Tensor, mask: tf.Tensor):
|
108 |
+
rmask = tf.logical_not(tf.cast(mask, tf.bool))
|
109 |
+
output = tf.where(rmask, float("-inf"), inputs)
|
110 |
+
output = stable_softmax(output, self.axis)
|
111 |
+
output = tf.where(rmask, 0.0, output)
|
112 |
+
return output
|
113 |
+
|
114 |
+
|
115 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaStableDropout with Deberta->DebertaV2
|
116 |
+
class TFDebertaV2StableDropout(keras.layers.Layer):
|
117 |
+
"""
|
118 |
+
Optimized dropout module for stabilizing the training
|
119 |
+
|
120 |
+
Args:
|
121 |
+
drop_prob (float): the dropout probabilities
|
122 |
+
"""
|
123 |
+
|
124 |
+
def __init__(self, drop_prob, **kwargs):
|
125 |
+
super().__init__(**kwargs)
|
126 |
+
self.drop_prob = drop_prob
|
127 |
+
|
128 |
+
@tf.custom_gradient
|
129 |
+
def xdropout(self, inputs):
|
130 |
+
"""
|
131 |
+
Applies dropout to the inputs, as vanilla dropout, but also scales the remaining elements up by 1/drop_prob.
|
132 |
+
"""
|
133 |
+
mask = tf.cast(
|
134 |
+
1
|
135 |
+
- tf.compat.v1.distributions.Bernoulli(probs=1.0 - self.drop_prob).sample(sample_shape=shape_list(inputs)),
|
136 |
+
tf.bool,
|
137 |
+
)
|
138 |
+
scale = tf.convert_to_tensor(1.0 / (1 - self.drop_prob), dtype=tf.float32)
|
139 |
+
if self.drop_prob > 0:
|
140 |
+
inputs = tf.where(mask, 0.0, inputs) * scale
|
141 |
+
|
142 |
+
def grad(upstream):
|
143 |
+
if self.drop_prob > 0:
|
144 |
+
return tf.where(mask, 0.0, upstream) * scale
|
145 |
+
else:
|
146 |
+
return upstream
|
147 |
+
|
148 |
+
return inputs, grad
|
149 |
+
|
150 |
+
def call(self, inputs: tf.Tensor, training: tf.Tensor = False):
|
151 |
+
if training:
|
152 |
+
return self.xdropout(inputs)
|
153 |
+
return inputs
|
154 |
+
|
155 |
+
|
156 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaSelfOutput with Deberta->DebertaV2
|
157 |
+
class TFDebertaV2SelfOutput(keras.layers.Layer):
|
158 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
159 |
+
super().__init__(**kwargs)
|
160 |
+
self.dense = keras.layers.Dense(config.hidden_size, name="dense")
|
161 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
162 |
+
self.dropout = TFDebertaV2StableDropout(config.hidden_dropout_prob, name="dropout")
|
163 |
+
self.config = config
|
164 |
+
|
165 |
+
def call(self, hidden_states, input_tensor, training: bool = False):
|
166 |
+
hidden_states = self.dense(hidden_states)
|
167 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
168 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
169 |
+
return hidden_states
|
170 |
+
|
171 |
+
def build(self, input_shape=None):
|
172 |
+
if self.built:
|
173 |
+
return
|
174 |
+
self.built = True
|
175 |
+
if getattr(self, "dense", None) is not None:
|
176 |
+
with tf.name_scope(self.dense.name):
|
177 |
+
self.dense.build([None, None, self.config.hidden_size])
|
178 |
+
if getattr(self, "LayerNorm", None) is not None:
|
179 |
+
with tf.name_scope(self.LayerNorm.name):
|
180 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
181 |
+
if getattr(self, "dropout", None) is not None:
|
182 |
+
with tf.name_scope(self.dropout.name):
|
183 |
+
self.dropout.build(None)
|
184 |
+
|
185 |
+
|
186 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaAttention with Deberta->DebertaV2
|
187 |
+
class TFDebertaV2Attention(keras.layers.Layer):
|
188 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
189 |
+
super().__init__(**kwargs)
|
190 |
+
self.self = TFDebertaV2DisentangledSelfAttention(config, name="self")
|
191 |
+
self.dense_output = TFDebertaV2SelfOutput(config, name="output")
|
192 |
+
self.config = config
|
193 |
+
|
194 |
+
def call(
|
195 |
+
self,
|
196 |
+
input_tensor: tf.Tensor,
|
197 |
+
attention_mask: tf.Tensor,
|
198 |
+
query_states: tf.Tensor = None,
|
199 |
+
relative_pos: tf.Tensor = None,
|
200 |
+
rel_embeddings: tf.Tensor = None,
|
201 |
+
output_attentions: bool = False,
|
202 |
+
training: bool = False,
|
203 |
+
) -> Tuple[tf.Tensor]:
|
204 |
+
self_outputs = self.self(
|
205 |
+
hidden_states=input_tensor,
|
206 |
+
attention_mask=attention_mask,
|
207 |
+
query_states=query_states,
|
208 |
+
relative_pos=relative_pos,
|
209 |
+
rel_embeddings=rel_embeddings,
|
210 |
+
output_attentions=output_attentions,
|
211 |
+
training=training,
|
212 |
+
)
|
213 |
+
if query_states is None:
|
214 |
+
query_states = input_tensor
|
215 |
+
attention_output = self.dense_output(
|
216 |
+
hidden_states=self_outputs[0], input_tensor=query_states, training=training
|
217 |
+
)
|
218 |
+
|
219 |
+
output = (attention_output,) + self_outputs[1:]
|
220 |
+
|
221 |
+
return output
|
222 |
+
|
223 |
+
def build(self, input_shape=None):
|
224 |
+
if self.built:
|
225 |
+
return
|
226 |
+
self.built = True
|
227 |
+
if getattr(self, "self", None) is not None:
|
228 |
+
with tf.name_scope(self.self.name):
|
229 |
+
self.self.build(None)
|
230 |
+
if getattr(self, "dense_output", None) is not None:
|
231 |
+
with tf.name_scope(self.dense_output.name):
|
232 |
+
self.dense_output.build(None)
|
233 |
+
|
234 |
+
|
235 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaIntermediate with Deberta->DebertaV2
|
236 |
+
class TFDebertaV2Intermediate(keras.layers.Layer):
|
237 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
238 |
+
super().__init__(**kwargs)
|
239 |
+
|
240 |
+
self.dense = keras.layers.Dense(
|
241 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
242 |
+
)
|
243 |
+
|
244 |
+
if isinstance(config.hidden_act, str):
|
245 |
+
self.intermediate_act_fn = get_tf_activation(config.hidden_act)
|
246 |
+
else:
|
247 |
+
self.intermediate_act_fn = config.hidden_act
|
248 |
+
self.config = config
|
249 |
+
|
250 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
251 |
+
hidden_states = self.dense(inputs=hidden_states)
|
252 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
253 |
+
|
254 |
+
return hidden_states
|
255 |
+
|
256 |
+
def build(self, input_shape=None):
|
257 |
+
if self.built:
|
258 |
+
return
|
259 |
+
self.built = True
|
260 |
+
if getattr(self, "dense", None) is not None:
|
261 |
+
with tf.name_scope(self.dense.name):
|
262 |
+
self.dense.build([None, None, self.config.hidden_size])
|
263 |
+
|
264 |
+
|
265 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaOutput with Deberta->DebertaV2
|
266 |
+
class TFDebertaV2Output(keras.layers.Layer):
|
267 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
268 |
+
super().__init__(**kwargs)
|
269 |
+
|
270 |
+
self.dense = keras.layers.Dense(
|
271 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
272 |
+
)
|
273 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
274 |
+
self.dropout = TFDebertaV2StableDropout(config.hidden_dropout_prob, name="dropout")
|
275 |
+
self.config = config
|
276 |
+
|
277 |
+
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
278 |
+
hidden_states = self.dense(inputs=hidden_states)
|
279 |
+
hidden_states = self.dropout(hidden_states, training=training)
|
280 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
281 |
+
|
282 |
+
return hidden_states
|
283 |
+
|
284 |
+
def build(self, input_shape=None):
|
285 |
+
if self.built:
|
286 |
+
return
|
287 |
+
self.built = True
|
288 |
+
if getattr(self, "dense", None) is not None:
|
289 |
+
with tf.name_scope(self.dense.name):
|
290 |
+
self.dense.build([None, None, self.config.intermediate_size])
|
291 |
+
if getattr(self, "LayerNorm", None) is not None:
|
292 |
+
with tf.name_scope(self.LayerNorm.name):
|
293 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
294 |
+
if getattr(self, "dropout", None) is not None:
|
295 |
+
with tf.name_scope(self.dropout.name):
|
296 |
+
self.dropout.build(None)
|
297 |
+
|
298 |
+
|
299 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaLayer with Deberta->DebertaV2
|
300 |
+
class TFDebertaV2Layer(keras.layers.Layer):
|
301 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
302 |
+
super().__init__(**kwargs)
|
303 |
+
|
304 |
+
self.attention = TFDebertaV2Attention(config, name="attention")
|
305 |
+
self.intermediate = TFDebertaV2Intermediate(config, name="intermediate")
|
306 |
+
self.bert_output = TFDebertaV2Output(config, name="output")
|
307 |
+
|
308 |
+
def call(
|
309 |
+
self,
|
310 |
+
hidden_states: tf.Tensor,
|
311 |
+
attention_mask: tf.Tensor,
|
312 |
+
query_states: tf.Tensor = None,
|
313 |
+
relative_pos: tf.Tensor = None,
|
314 |
+
rel_embeddings: tf.Tensor = None,
|
315 |
+
output_attentions: bool = False,
|
316 |
+
training: bool = False,
|
317 |
+
) -> Tuple[tf.Tensor]:
|
318 |
+
attention_outputs = self.attention(
|
319 |
+
input_tensor=hidden_states,
|
320 |
+
attention_mask=attention_mask,
|
321 |
+
query_states=query_states,
|
322 |
+
relative_pos=relative_pos,
|
323 |
+
rel_embeddings=rel_embeddings,
|
324 |
+
output_attentions=output_attentions,
|
325 |
+
training=training,
|
326 |
+
)
|
327 |
+
attention_output = attention_outputs[0]
|
328 |
+
intermediate_output = self.intermediate(hidden_states=attention_output)
|
329 |
+
layer_output = self.bert_output(
|
330 |
+
hidden_states=intermediate_output, input_tensor=attention_output, training=training
|
331 |
+
)
|
332 |
+
outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them
|
333 |
+
|
334 |
+
return outputs
|
335 |
+
|
336 |
+
def build(self, input_shape=None):
|
337 |
+
if self.built:
|
338 |
+
return
|
339 |
+
self.built = True
|
340 |
+
if getattr(self, "attention", None) is not None:
|
341 |
+
with tf.name_scope(self.attention.name):
|
342 |
+
self.attention.build(None)
|
343 |
+
if getattr(self, "intermediate", None) is not None:
|
344 |
+
with tf.name_scope(self.intermediate.name):
|
345 |
+
self.intermediate.build(None)
|
346 |
+
if getattr(self, "bert_output", None) is not None:
|
347 |
+
with tf.name_scope(self.bert_output.name):
|
348 |
+
self.bert_output.build(None)
|
349 |
+
|
350 |
+
|
351 |
+
class TFDebertaV2ConvLayer(keras.layers.Layer):
|
352 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
353 |
+
super().__init__(**kwargs)
|
354 |
+
|
355 |
+
self.kernel_size = getattr(config, "conv_kernel_size", 3)
|
356 |
+
# groups = getattr(config, "conv_groups", 1)
|
357 |
+
self.conv_act = get_tf_activation(getattr(config, "conv_act", "tanh"))
|
358 |
+
self.padding = (self.kernel_size - 1) // 2
|
359 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
360 |
+
self.dropout = TFDebertaV2StableDropout(config.hidden_dropout_prob, name="dropout")
|
361 |
+
self.config = config
|
362 |
+
|
363 |
+
def build(self, input_shape=None):
|
364 |
+
if self.built:
|
365 |
+
return
|
366 |
+
self.built = True
|
367 |
+
with tf.name_scope("conv"):
|
368 |
+
self.conv_kernel = self.add_weight(
|
369 |
+
name="kernel",
|
370 |
+
shape=[self.kernel_size, self.config.hidden_size, self.config.hidden_size],
|
371 |
+
initializer=get_initializer(self.config.initializer_range),
|
372 |
+
)
|
373 |
+
self.conv_bias = self.add_weight(
|
374 |
+
name="bias", shape=[self.config.hidden_size], initializer=tf.zeros_initializer()
|
375 |
+
)
|
376 |
+
if getattr(self, "LayerNorm", None) is not None:
|
377 |
+
with tf.name_scope(self.LayerNorm.name):
|
378 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
379 |
+
if getattr(self, "dropout", None) is not None:
|
380 |
+
with tf.name_scope(self.dropout.name):
|
381 |
+
self.dropout.build(None)
|
382 |
+
|
383 |
+
def call(
|
384 |
+
self, hidden_states: tf.Tensor, residual_states: tf.Tensor, input_mask: tf.Tensor, training: bool = False
|
385 |
+
) -> tf.Tensor:
|
386 |
+
out = tf.nn.conv2d(
|
387 |
+
tf.expand_dims(hidden_states, 1),
|
388 |
+
tf.expand_dims(self.conv_kernel, 0),
|
389 |
+
strides=1,
|
390 |
+
padding=[[0, 0], [0, 0], [self.padding, self.padding], [0, 0]],
|
391 |
+
)
|
392 |
+
out = tf.squeeze(tf.nn.bias_add(out, self.conv_bias), 1)
|
393 |
+
rmask = tf.cast(1 - input_mask, tf.bool)
|
394 |
+
out = tf.where(tf.broadcast_to(tf.expand_dims(rmask, -1), shape_list(out)), 0.0, out)
|
395 |
+
out = self.dropout(out, training=training)
|
396 |
+
out = self.conv_act(out)
|
397 |
+
|
398 |
+
layer_norm_input = residual_states + out
|
399 |
+
output = self.LayerNorm(layer_norm_input)
|
400 |
+
|
401 |
+
if input_mask is None:
|
402 |
+
output_states = output
|
403 |
+
else:
|
404 |
+
if len(shape_list(input_mask)) != len(shape_list(layer_norm_input)):
|
405 |
+
if len(shape_list(input_mask)) == 4:
|
406 |
+
input_mask = tf.squeeze(tf.squeeze(input_mask, axis=1), axis=1)
|
407 |
+
input_mask = tf.cast(tf.expand_dims(input_mask, axis=2), tf.float32)
|
408 |
+
|
409 |
+
output_states = output * input_mask
|
410 |
+
|
411 |
+
return output_states
|
412 |
+
|
413 |
+
|
414 |
+
class TFDebertaV2Encoder(keras.layers.Layer):
|
415 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
416 |
+
super().__init__(**kwargs)
|
417 |
+
|
418 |
+
self.layer = [TFDebertaV2Layer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
|
419 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
420 |
+
self.config = config
|
421 |
+
if self.relative_attention:
|
422 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
423 |
+
if self.max_relative_positions < 1:
|
424 |
+
self.max_relative_positions = config.max_position_embeddings
|
425 |
+
|
426 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
427 |
+
self.pos_ebd_size = self.max_relative_positions * 2
|
428 |
+
|
429 |
+
if self.position_buckets > 0:
|
430 |
+
self.pos_ebd_size = self.position_buckets * 2
|
431 |
+
|
432 |
+
self.norm_rel_ebd = [x.strip() for x in getattr(config, "norm_rel_ebd", "none").lower().split("|")]
|
433 |
+
|
434 |
+
if "layer_norm" in self.norm_rel_ebd:
|
435 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
436 |
+
|
437 |
+
self.conv = TFDebertaV2ConvLayer(config, name="conv") if getattr(config, "conv_kernel_size", 0) > 0 else None
|
438 |
+
|
439 |
+
def build(self, input_shape=None):
|
440 |
+
if self.built:
|
441 |
+
return
|
442 |
+
self.built = True
|
443 |
+
if self.relative_attention:
|
444 |
+
self.rel_embeddings = self.add_weight(
|
445 |
+
name="rel_embeddings.weight",
|
446 |
+
shape=[self.pos_ebd_size, self.config.hidden_size],
|
447 |
+
initializer=get_initializer(self.config.initializer_range),
|
448 |
+
)
|
449 |
+
if getattr(self, "conv", None) is not None:
|
450 |
+
with tf.name_scope(self.conv.name):
|
451 |
+
self.conv.build(None)
|
452 |
+
if getattr(self, "LayerNorm", None) is not None:
|
453 |
+
with tf.name_scope(self.LayerNorm.name):
|
454 |
+
self.LayerNorm.build([None, self.config.hidden_size])
|
455 |
+
if getattr(self, "layer", None) is not None:
|
456 |
+
for layer in self.layer:
|
457 |
+
with tf.name_scope(layer.name):
|
458 |
+
layer.build(None)
|
459 |
+
|
460 |
+
def get_rel_embedding(self):
|
461 |
+
rel_embeddings = self.rel_embeddings if self.relative_attention else None
|
462 |
+
if rel_embeddings is not None and ("layer_norm" in self.norm_rel_ebd):
|
463 |
+
rel_embeddings = self.LayerNorm(rel_embeddings)
|
464 |
+
return rel_embeddings
|
465 |
+
|
466 |
+
def get_attention_mask(self, attention_mask):
|
467 |
+
if len(shape_list(attention_mask)) <= 2:
|
468 |
+
extended_attention_mask = tf.expand_dims(tf.expand_dims(attention_mask, 1), 2)
|
469 |
+
attention_mask = extended_attention_mask * tf.expand_dims(tf.squeeze(extended_attention_mask, -2), -1)
|
470 |
+
attention_mask = tf.cast(attention_mask, tf.uint8)
|
471 |
+
elif len(shape_list(attention_mask)) == 3:
|
472 |
+
attention_mask = tf.expand_dims(attention_mask, 1)
|
473 |
+
|
474 |
+
return attention_mask
|
475 |
+
|
476 |
+
def get_rel_pos(self, hidden_states, query_states=None, relative_pos=None):
|
477 |
+
if self.relative_attention and relative_pos is None:
|
478 |
+
q = shape_list(query_states)[-2] if query_states is not None else shape_list(hidden_states)[-2]
|
479 |
+
relative_pos = build_relative_position(
|
480 |
+
q,
|
481 |
+
shape_list(hidden_states)[-2],
|
482 |
+
bucket_size=self.position_buckets,
|
483 |
+
max_position=self.max_relative_positions,
|
484 |
+
)
|
485 |
+
return relative_pos
|
486 |
+
|
487 |
+
def call(
|
488 |
+
self,
|
489 |
+
hidden_states: tf.Tensor,
|
490 |
+
attention_mask: tf.Tensor,
|
491 |
+
query_states: tf.Tensor = None,
|
492 |
+
relative_pos: tf.Tensor = None,
|
493 |
+
output_attentions: bool = False,
|
494 |
+
output_hidden_states: bool = False,
|
495 |
+
return_dict: bool = True,
|
496 |
+
training: bool = False,
|
497 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
498 |
+
if len(shape_list(attention_mask)) <= 2:
|
499 |
+
input_mask = attention_mask
|
500 |
+
else:
|
501 |
+
input_mask = tf.cast(tf.math.reduce_sum(attention_mask, axis=-2) > 0, dtype=tf.uint8)
|
502 |
+
|
503 |
+
all_hidden_states = () if output_hidden_states else None
|
504 |
+
all_attentions = () if output_attentions else None
|
505 |
+
|
506 |
+
attention_mask = self.get_attention_mask(attention_mask)
|
507 |
+
relative_pos = self.get_rel_pos(hidden_states, query_states, relative_pos)
|
508 |
+
|
509 |
+
next_kv = hidden_states
|
510 |
+
|
511 |
+
rel_embeddings = self.get_rel_embedding()
|
512 |
+
output_states = next_kv
|
513 |
+
for i, layer_module in enumerate(self.layer):
|
514 |
+
if output_hidden_states:
|
515 |
+
all_hidden_states = all_hidden_states + (output_states,)
|
516 |
+
|
517 |
+
layer_outputs = layer_module(
|
518 |
+
hidden_states=next_kv,
|
519 |
+
attention_mask=attention_mask,
|
520 |
+
query_states=query_states,
|
521 |
+
relative_pos=relative_pos,
|
522 |
+
rel_embeddings=rel_embeddings,
|
523 |
+
output_attentions=output_attentions,
|
524 |
+
training=training,
|
525 |
+
)
|
526 |
+
output_states = layer_outputs[0]
|
527 |
+
|
528 |
+
if i == 0 and self.conv is not None:
|
529 |
+
output_states = self.conv(hidden_states, output_states, input_mask)
|
530 |
+
|
531 |
+
next_kv = output_states
|
532 |
+
|
533 |
+
if output_attentions:
|
534 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
535 |
+
|
536 |
+
# Add last layer
|
537 |
+
if output_hidden_states:
|
538 |
+
all_hidden_states = all_hidden_states + (output_states,)
|
539 |
+
|
540 |
+
if not return_dict:
|
541 |
+
return tuple(v for v in [output_states, all_hidden_states, all_attentions] if v is not None)
|
542 |
+
|
543 |
+
return TFBaseModelOutput(
|
544 |
+
last_hidden_state=output_states, hidden_states=all_hidden_states, attentions=all_attentions
|
545 |
+
)
|
546 |
+
|
547 |
+
|
548 |
+
def make_log_bucket_position(relative_pos, bucket_size, max_position):
|
549 |
+
sign = tf.math.sign(relative_pos)
|
550 |
+
mid = bucket_size // 2
|
551 |
+
abs_pos = tf.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, tf.math.abs(relative_pos))
|
552 |
+
log_pos = (
|
553 |
+
tf.math.ceil(
|
554 |
+
tf.cast(tf.math.log(abs_pos / mid), tf.float32) / tf.math.log((max_position - 1) / mid) * (mid - 1)
|
555 |
+
)
|
556 |
+
+ mid
|
557 |
+
)
|
558 |
+
bucket_pos = tf.cast(
|
559 |
+
tf.where(abs_pos <= mid, tf.cast(relative_pos, tf.float32), log_pos * tf.cast(sign, tf.float32)), tf.int32
|
560 |
+
)
|
561 |
+
return bucket_pos
|
562 |
+
|
563 |
+
|
564 |
+
def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1):
|
565 |
+
"""
|
566 |
+
Build relative position according to the query and key
|
567 |
+
|
568 |
+
We assume the absolute position of query \\(P_q\\) is range from (0, query_size) and the absolute position of key
|
569 |
+
\\(P_k\\) is range from (0, key_size), The relative positions from query to key is \\(R_{q \\rightarrow k} = P_q -
|
570 |
+
P_k\\)
|
571 |
+
|
572 |
+
Args:
|
573 |
+
query_size (int): the length of query
|
574 |
+
key_size (int): the length of key
|
575 |
+
bucket_size (int): the size of position bucket
|
576 |
+
max_position (int): the maximum allowed absolute position
|
577 |
+
|
578 |
+
Return:
|
579 |
+
`tf.Tensor`: A tensor with shape [1, query_size, key_size]
|
580 |
+
|
581 |
+
"""
|
582 |
+
q_ids = tf.range(query_size, dtype=tf.int32)
|
583 |
+
k_ids = tf.range(key_size, dtype=tf.int32)
|
584 |
+
rel_pos_ids = q_ids[:, None] - tf.tile(tf.expand_dims(k_ids, axis=0), [shape_list(q_ids)[0], 1])
|
585 |
+
if bucket_size > 0 and max_position > 0:
|
586 |
+
rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
|
587 |
+
rel_pos_ids = rel_pos_ids[:query_size, :]
|
588 |
+
rel_pos_ids = tf.expand_dims(rel_pos_ids, axis=0)
|
589 |
+
return tf.cast(rel_pos_ids, tf.int64)
|
590 |
+
|
591 |
+
|
592 |
+
def c2p_dynamic_expand(c2p_pos, query_layer, relative_pos):
|
593 |
+
shapes = [
|
594 |
+
shape_list(query_layer)[0],
|
595 |
+
shape_list(query_layer)[1],
|
596 |
+
shape_list(query_layer)[2],
|
597 |
+
shape_list(relative_pos)[-1],
|
598 |
+
]
|
599 |
+
return tf.broadcast_to(c2p_pos, shapes)
|
600 |
+
|
601 |
+
|
602 |
+
def p2c_dynamic_expand(c2p_pos, query_layer, key_layer):
|
603 |
+
shapes = [
|
604 |
+
shape_list(query_layer)[0],
|
605 |
+
shape_list(query_layer)[1],
|
606 |
+
shape_list(key_layer)[-2],
|
607 |
+
shape_list(key_layer)[-2],
|
608 |
+
]
|
609 |
+
return tf.broadcast_to(c2p_pos, shapes)
|
610 |
+
|
611 |
+
|
612 |
+
def pos_dynamic_expand(pos_index, p2c_att, key_layer):
|
613 |
+
shapes = shape_list(p2c_att)[:2] + [shape_list(pos_index)[-2], shape_list(key_layer)[-2]]
|
614 |
+
return tf.broadcast_to(pos_index, shapes)
|
615 |
+
|
616 |
+
|
617 |
+
def take_along_axis(x, indices):
|
618 |
+
# Only a valid port of np.take_along_axis when the gather axis is -1
|
619 |
+
|
620 |
+
# TPU + gathers and reshapes don't go along well -- see https://github.com/huggingface/transformers/issues/18239
|
621 |
+
if isinstance(tf.distribute.get_strategy(), tf.distribute.TPUStrategy):
|
622 |
+
# [B, S, P] -> [B, S, P, D]
|
623 |
+
one_hot_indices = tf.one_hot(indices, depth=x.shape[-1], dtype=x.dtype)
|
624 |
+
|
625 |
+
# if we ignore the first two dims, this is equivalent to multiplying a matrix (one hot) by a vector (x)
|
626 |
+
# grossly abusing notation: [B, S, P, D] . [B, S, D] = [B, S, P]
|
627 |
+
gathered = tf.einsum("ijkl,ijl->ijk", one_hot_indices, x)
|
628 |
+
|
629 |
+
# GPUs, on the other hand, prefer gathers instead of large one-hot+matmuls
|
630 |
+
else:
|
631 |
+
gathered = tf.gather(x, indices, batch_dims=2)
|
632 |
+
|
633 |
+
return gathered
|
634 |
+
|
635 |
+
|
636 |
+
class TFDebertaV2DisentangledSelfAttention(keras.layers.Layer):
|
637 |
+
"""
|
638 |
+
Disentangled self-attention module
|
639 |
+
|
640 |
+
Parameters:
|
641 |
+
config (`DebertaV2Config`):
|
642 |
+
A model config class instance with the configuration to build a new model. The schema is similar to
|
643 |
+
*BertConfig*, for more details, please refer [`DebertaV2Config`]
|
644 |
+
|
645 |
+
"""
|
646 |
+
|
647 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
648 |
+
super().__init__(**kwargs)
|
649 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
650 |
+
raise ValueError(
|
651 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
652 |
+
f"heads ({config.num_attention_heads})"
|
653 |
+
)
|
654 |
+
self.num_attention_heads = config.num_attention_heads
|
655 |
+
_attention_head_size = config.hidden_size // config.num_attention_heads
|
656 |
+
self.attention_head_size = getattr(config, "attention_head_size", _attention_head_size)
|
657 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
658 |
+
self.query_proj = keras.layers.Dense(
|
659 |
+
self.all_head_size,
|
660 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
661 |
+
name="query_proj",
|
662 |
+
use_bias=True,
|
663 |
+
)
|
664 |
+
self.key_proj = keras.layers.Dense(
|
665 |
+
self.all_head_size,
|
666 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
667 |
+
name="key_proj",
|
668 |
+
use_bias=True,
|
669 |
+
)
|
670 |
+
self.value_proj = keras.layers.Dense(
|
671 |
+
self.all_head_size,
|
672 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
673 |
+
name="value_proj",
|
674 |
+
use_bias=True,
|
675 |
+
)
|
676 |
+
|
677 |
+
self.share_att_key = getattr(config, "share_att_key", False)
|
678 |
+
self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else []
|
679 |
+
self.relative_attention = getattr(config, "relative_attention", False)
|
680 |
+
|
681 |
+
if self.relative_attention:
|
682 |
+
self.position_buckets = getattr(config, "position_buckets", -1)
|
683 |
+
self.max_relative_positions = getattr(config, "max_relative_positions", -1)
|
684 |
+
if self.max_relative_positions < 1:
|
685 |
+
self.max_relative_positions = config.max_position_embeddings
|
686 |
+
self.pos_ebd_size = self.max_relative_positions
|
687 |
+
if self.position_buckets > 0:
|
688 |
+
self.pos_ebd_size = self.position_buckets
|
689 |
+
|
690 |
+
self.pos_dropout = TFDebertaV2StableDropout(config.hidden_dropout_prob, name="pos_dropout")
|
691 |
+
|
692 |
+
if not self.share_att_key:
|
693 |
+
if "c2p" in self.pos_att_type:
|
694 |
+
self.pos_key_proj = keras.layers.Dense(
|
695 |
+
self.all_head_size,
|
696 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
697 |
+
name="pos_proj",
|
698 |
+
use_bias=True,
|
699 |
+
)
|
700 |
+
if "p2c" in self.pos_att_type:
|
701 |
+
self.pos_query_proj = keras.layers.Dense(
|
702 |
+
self.all_head_size,
|
703 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
704 |
+
name="pos_q_proj",
|
705 |
+
)
|
706 |
+
self.softmax = TFDebertaV2XSoftmax(axis=-1)
|
707 |
+
self.dropout = TFDebertaV2StableDropout(config.attention_probs_dropout_prob, name="dropout")
|
708 |
+
self.config = config
|
709 |
+
|
710 |
+
def transpose_for_scores(self, tensor: tf.Tensor, attention_heads: int) -> tf.Tensor:
|
711 |
+
tensor_shape = shape_list(tensor)
|
712 |
+
# In graph mode mode, we can't reshape with -1 as the final dimension if the first dimension (batch size) is None
|
713 |
+
shape = tensor_shape[:-1] + [attention_heads, tensor_shape[-1] // attention_heads]
|
714 |
+
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
|
715 |
+
tensor = tf.reshape(tensor=tensor, shape=shape)
|
716 |
+
tensor = tf.transpose(tensor, perm=[0, 2, 1, 3])
|
717 |
+
x_shape = shape_list(tensor)
|
718 |
+
tensor = tf.reshape(tensor, shape=[-1, x_shape[-2], x_shape[-1]])
|
719 |
+
return tensor
|
720 |
+
|
721 |
+
def call(
|
722 |
+
self,
|
723 |
+
hidden_states: tf.Tensor,
|
724 |
+
attention_mask: tf.Tensor,
|
725 |
+
query_states: tf.Tensor = None,
|
726 |
+
relative_pos: tf.Tensor = None,
|
727 |
+
rel_embeddings: tf.Tensor = None,
|
728 |
+
output_attentions: bool = False,
|
729 |
+
training: bool = False,
|
730 |
+
) -> Tuple[tf.Tensor]:
|
731 |
+
"""
|
732 |
+
Call the module
|
733 |
+
|
734 |
+
Args:
|
735 |
+
hidden_states (`tf.Tensor`):
|
736 |
+
Input states to the module usually the output from previous layer, it will be the Q,K and V in
|
737 |
+
*Attention(Q,K,V)*
|
738 |
+
|
739 |
+
attention_mask (`tf.Tensor`):
|
740 |
+
An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum
|
741 |
+
sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j*
|
742 |
+
th token.
|
743 |
+
|
744 |
+
return_att (`bool`, optional):
|
745 |
+
Whether return the attention matrix.
|
746 |
+
|
747 |
+
query_states (`tf.Tensor`, optional):
|
748 |
+
The *Q* state in *Attention(Q,K,V)*.
|
749 |
+
|
750 |
+
relative_pos (`tf.Tensor`):
|
751 |
+
The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with
|
752 |
+
values ranging in [*-max_relative_positions*, *max_relative_positions*].
|
753 |
+
|
754 |
+
rel_embeddings (`tf.Tensor`):
|
755 |
+
The embedding of relative distances. It's a tensor of shape [\\(2 \\times
|
756 |
+
\\text{max_relative_positions}\\), *hidden_size*].
|
757 |
+
|
758 |
+
|
759 |
+
"""
|
760 |
+
if query_states is None:
|
761 |
+
query_states = hidden_states
|
762 |
+
query_layer = self.transpose_for_scores(self.query_proj(query_states), self.num_attention_heads)
|
763 |
+
key_layer = self.transpose_for_scores(self.key_proj(hidden_states), self.num_attention_heads)
|
764 |
+
value_layer = self.transpose_for_scores(self.value_proj(hidden_states), self.num_attention_heads)
|
765 |
+
|
766 |
+
rel_att = None
|
767 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
768 |
+
scale_factor = 1
|
769 |
+
if "c2p" in self.pos_att_type:
|
770 |
+
scale_factor += 1
|
771 |
+
if "p2c" in self.pos_att_type:
|
772 |
+
scale_factor += 1
|
773 |
+
scale = tf.math.sqrt(tf.cast(shape_list(query_layer)[-1] * scale_factor, tf.float32))
|
774 |
+
attention_scores = tf.matmul(query_layer, tf.transpose(key_layer, [0, 2, 1]) / scale)
|
775 |
+
if self.relative_attention:
|
776 |
+
rel_embeddings = self.pos_dropout(rel_embeddings)
|
777 |
+
rel_att = self.disentangled_att_bias(query_layer, key_layer, relative_pos, rel_embeddings, scale_factor)
|
778 |
+
|
779 |
+
if rel_att is not None:
|
780 |
+
attention_scores = attention_scores + rel_att
|
781 |
+
attention_scores = tf.reshape(
|
782 |
+
attention_scores,
|
783 |
+
(-1, self.num_attention_heads, shape_list(attention_scores)[-2], shape_list(attention_scores)[-1]),
|
784 |
+
)
|
785 |
+
|
786 |
+
# bsz x height x length x dimension
|
787 |
+
attention_probs = self.softmax(attention_scores, attention_mask)
|
788 |
+
attention_probs = self.dropout(attention_probs, training=training)
|
789 |
+
context_layer = tf.matmul(
|
790 |
+
tf.reshape(attention_probs, [-1, shape_list(attention_probs)[-2], shape_list(attention_probs)[-1]]),
|
791 |
+
value_layer,
|
792 |
+
)
|
793 |
+
context_layer = tf.transpose(
|
794 |
+
tf.reshape(
|
795 |
+
context_layer,
|
796 |
+
[-1, self.num_attention_heads, shape_list(context_layer)[-2], shape_list(context_layer)[-1]],
|
797 |
+
),
|
798 |
+
[0, 2, 1, 3],
|
799 |
+
)
|
800 |
+
# Set the final dimension here explicitly.
|
801 |
+
# Calling tf.reshape(context_layer, (*context_layer_shape[:-2], -1)) raises an error when executing
|
802 |
+
# the model in graph mode as context_layer is reshaped to (None, 7, None) and Dense layer in TFDebertaV2SelfOutput
|
803 |
+
# requires final input dimension to be defined
|
804 |
+
context_layer_shape = shape_list(context_layer)
|
805 |
+
new_context_layer_shape = context_layer_shape[:-2] + [context_layer_shape[-2] * context_layer_shape[-1]]
|
806 |
+
context_layer = tf.reshape(context_layer, new_context_layer_shape)
|
807 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
808 |
+
return outputs
|
809 |
+
|
810 |
+
def disentangled_att_bias(self, query_layer, key_layer, relative_pos, rel_embeddings, scale_factor):
|
811 |
+
if relative_pos is None:
|
812 |
+
q = shape_list(query_layer)[-2]
|
813 |
+
relative_pos = build_relative_position(
|
814 |
+
q,
|
815 |
+
shape_list(key_layer)[-2],
|
816 |
+
bucket_size=self.position_buckets,
|
817 |
+
max_position=self.max_relative_positions,
|
818 |
+
)
|
819 |
+
shape_list_pos = shape_list(relative_pos)
|
820 |
+
if len(shape_list_pos) == 2:
|
821 |
+
relative_pos = tf.expand_dims(tf.expand_dims(relative_pos, 0), 0)
|
822 |
+
elif len(shape_list_pos) == 3:
|
823 |
+
relative_pos = tf.expand_dims(relative_pos, 1)
|
824 |
+
# bsz x height x query x key
|
825 |
+
elif len(shape_list_pos) != 4:
|
826 |
+
raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {len(shape_list_pos)}")
|
827 |
+
|
828 |
+
att_span = self.pos_ebd_size
|
829 |
+
rel_embeddings = tf.expand_dims(
|
830 |
+
rel_embeddings[self.pos_ebd_size - att_span : self.pos_ebd_size + att_span, :], 0
|
831 |
+
)
|
832 |
+
if self.share_att_key:
|
833 |
+
pos_query_layer = tf.tile(
|
834 |
+
self.transpose_for_scores(self.query_proj(rel_embeddings), self.num_attention_heads),
|
835 |
+
[shape_list(query_layer)[0] // self.num_attention_heads, 1, 1],
|
836 |
+
)
|
837 |
+
pos_key_layer = tf.tile(
|
838 |
+
self.transpose_for_scores(self.key_proj(rel_embeddings), self.num_attention_heads),
|
839 |
+
[shape_list(query_layer)[0] // self.num_attention_heads, 1, 1],
|
840 |
+
)
|
841 |
+
else:
|
842 |
+
if "c2p" in self.pos_att_type:
|
843 |
+
pos_key_layer = tf.tile(
|
844 |
+
self.transpose_for_scores(self.pos_key_proj(rel_embeddings), self.num_attention_heads),
|
845 |
+
[shape_list(query_layer)[0] // self.num_attention_heads, 1, 1],
|
846 |
+
) # .split(self.all_head_size, dim=-1)
|
847 |
+
if "p2c" in self.pos_att_type:
|
848 |
+
pos_query_layer = tf.tile(
|
849 |
+
self.transpose_for_scores(self.pos_query_proj(rel_embeddings), self.num_attention_heads),
|
850 |
+
[shape_list(query_layer)[0] // self.num_attention_heads, 1, 1],
|
851 |
+
) # .split(self.all_head_size, dim=-1)
|
852 |
+
|
853 |
+
score = 0
|
854 |
+
# content->position
|
855 |
+
if "c2p" in self.pos_att_type:
|
856 |
+
scale = tf.math.sqrt(tf.cast(shape_list(pos_key_layer)[-1] * scale_factor, tf.float32))
|
857 |
+
c2p_att = tf.matmul(query_layer, tf.transpose(pos_key_layer, [0, 2, 1]))
|
858 |
+
c2p_pos = tf.clip_by_value(relative_pos + att_span, 0, att_span * 2 - 1)
|
859 |
+
c2p_att = take_along_axis(
|
860 |
+
c2p_att,
|
861 |
+
tf.broadcast_to(
|
862 |
+
tf.squeeze(c2p_pos, 0),
|
863 |
+
[shape_list(query_layer)[0], shape_list(query_layer)[1], shape_list(relative_pos)[-1]],
|
864 |
+
),
|
865 |
+
)
|
866 |
+
score += c2p_att / scale
|
867 |
+
|
868 |
+
# position->content
|
869 |
+
if "p2c" in self.pos_att_type:
|
870 |
+
scale = tf.math.sqrt(tf.cast(shape_list(pos_query_layer)[-1] * scale_factor, tf.float32))
|
871 |
+
if shape_list(key_layer)[-2] != shape_list(query_layer)[-2]:
|
872 |
+
r_pos = build_relative_position(
|
873 |
+
shape_list(key_layer)[-2],
|
874 |
+
shape_list(key_layer)[-2],
|
875 |
+
bucket_size=self.position_buckets,
|
876 |
+
max_position=self.max_relative_positions,
|
877 |
+
)
|
878 |
+
r_pos = tf.expand_dims(r_pos, 0)
|
879 |
+
else:
|
880 |
+
r_pos = relative_pos
|
881 |
+
|
882 |
+
p2c_pos = tf.clip_by_value(-r_pos + att_span, 0, att_span * 2 - 1)
|
883 |
+
|
884 |
+
p2c_att = tf.matmul(key_layer, tf.transpose(pos_query_layer, [0, 2, 1]))
|
885 |
+
p2c_att = tf.transpose(
|
886 |
+
take_along_axis(
|
887 |
+
p2c_att,
|
888 |
+
tf.broadcast_to(
|
889 |
+
tf.squeeze(p2c_pos, 0),
|
890 |
+
[shape_list(query_layer)[0], shape_list(key_layer)[-2], shape_list(key_layer)[-2]],
|
891 |
+
),
|
892 |
+
),
|
893 |
+
[0, 2, 1],
|
894 |
+
)
|
895 |
+
score += p2c_att / scale
|
896 |
+
|
897 |
+
return score
|
898 |
+
|
899 |
+
def build(self, input_shape=None):
|
900 |
+
if self.built:
|
901 |
+
return
|
902 |
+
self.built = True
|
903 |
+
if getattr(self, "query_proj", None) is not None:
|
904 |
+
with tf.name_scope(self.query_proj.name):
|
905 |
+
self.query_proj.build([None, None, self.config.hidden_size])
|
906 |
+
if getattr(self, "key_proj", None) is not None:
|
907 |
+
with tf.name_scope(self.key_proj.name):
|
908 |
+
self.key_proj.build([None, None, self.config.hidden_size])
|
909 |
+
if getattr(self, "value_proj", None) is not None:
|
910 |
+
with tf.name_scope(self.value_proj.name):
|
911 |
+
self.value_proj.build([None, None, self.config.hidden_size])
|
912 |
+
if getattr(self, "dropout", None) is not None:
|
913 |
+
with tf.name_scope(self.dropout.name):
|
914 |
+
self.dropout.build(None)
|
915 |
+
if getattr(self, "pos_dropout", None) is not None:
|
916 |
+
with tf.name_scope(self.pos_dropout.name):
|
917 |
+
self.pos_dropout.build(None)
|
918 |
+
if getattr(self, "pos_key_proj", None) is not None:
|
919 |
+
with tf.name_scope(self.pos_key_proj.name):
|
920 |
+
self.pos_key_proj.build([None, None, self.config.hidden_size])
|
921 |
+
if getattr(self, "pos_query_proj", None) is not None:
|
922 |
+
with tf.name_scope(self.pos_query_proj.name):
|
923 |
+
self.pos_query_proj.build([None, None, self.config.hidden_size])
|
924 |
+
|
925 |
+
|
926 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaEmbeddings Deberta->DebertaV2
|
927 |
+
class TFDebertaV2Embeddings(keras.layers.Layer):
|
928 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
929 |
+
|
930 |
+
def __init__(self, config, **kwargs):
|
931 |
+
super().__init__(**kwargs)
|
932 |
+
|
933 |
+
self.config = config
|
934 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
935 |
+
self.hidden_size = config.hidden_size
|
936 |
+
self.max_position_embeddings = config.max_position_embeddings
|
937 |
+
self.position_biased_input = getattr(config, "position_biased_input", True)
|
938 |
+
self.initializer_range = config.initializer_range
|
939 |
+
if self.embedding_size != config.hidden_size:
|
940 |
+
self.embed_proj = keras.layers.Dense(
|
941 |
+
config.hidden_size,
|
942 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
943 |
+
name="embed_proj",
|
944 |
+
use_bias=False,
|
945 |
+
)
|
946 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
947 |
+
self.dropout = TFDebertaV2StableDropout(config.hidden_dropout_prob, name="dropout")
|
948 |
+
|
949 |
+
def build(self, input_shape=None):
|
950 |
+
with tf.name_scope("word_embeddings"):
|
951 |
+
self.weight = self.add_weight(
|
952 |
+
name="weight",
|
953 |
+
shape=[self.config.vocab_size, self.embedding_size],
|
954 |
+
initializer=get_initializer(self.initializer_range),
|
955 |
+
)
|
956 |
+
|
957 |
+
with tf.name_scope("token_type_embeddings"):
|
958 |
+
if self.config.type_vocab_size > 0:
|
959 |
+
self.token_type_embeddings = self.add_weight(
|
960 |
+
name="embeddings",
|
961 |
+
shape=[self.config.type_vocab_size, self.embedding_size],
|
962 |
+
initializer=get_initializer(self.initializer_range),
|
963 |
+
)
|
964 |
+
else:
|
965 |
+
self.token_type_embeddings = None
|
966 |
+
|
967 |
+
with tf.name_scope("position_embeddings"):
|
968 |
+
if self.position_biased_input:
|
969 |
+
self.position_embeddings = self.add_weight(
|
970 |
+
name="embeddings",
|
971 |
+
shape=[self.max_position_embeddings, self.hidden_size],
|
972 |
+
initializer=get_initializer(self.initializer_range),
|
973 |
+
)
|
974 |
+
else:
|
975 |
+
self.position_embeddings = None
|
976 |
+
|
977 |
+
if self.built:
|
978 |
+
return
|
979 |
+
self.built = True
|
980 |
+
if getattr(self, "LayerNorm", None) is not None:
|
981 |
+
with tf.name_scope(self.LayerNorm.name):
|
982 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
983 |
+
if getattr(self, "dropout", None) is not None:
|
984 |
+
with tf.name_scope(self.dropout.name):
|
985 |
+
self.dropout.build(None)
|
986 |
+
if getattr(self, "embed_proj", None) is not None:
|
987 |
+
with tf.name_scope(self.embed_proj.name):
|
988 |
+
self.embed_proj.build([None, None, self.embedding_size])
|
989 |
+
|
990 |
+
def call(
|
991 |
+
self,
|
992 |
+
input_ids: tf.Tensor = None,
|
993 |
+
position_ids: tf.Tensor = None,
|
994 |
+
token_type_ids: tf.Tensor = None,
|
995 |
+
inputs_embeds: tf.Tensor = None,
|
996 |
+
mask: tf.Tensor = None,
|
997 |
+
training: bool = False,
|
998 |
+
) -> tf.Tensor:
|
999 |
+
"""
|
1000 |
+
Applies embedding based on inputs tensor.
|
1001 |
+
|
1002 |
+
Returns:
|
1003 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
1004 |
+
"""
|
1005 |
+
if input_ids is None and inputs_embeds is None:
|
1006 |
+
raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
|
1007 |
+
|
1008 |
+
if input_ids is not None:
|
1009 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
1010 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
1011 |
+
|
1012 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
1013 |
+
|
1014 |
+
if token_type_ids is None:
|
1015 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
1016 |
+
|
1017 |
+
if position_ids is None:
|
1018 |
+
position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
|
1019 |
+
|
1020 |
+
final_embeddings = inputs_embeds
|
1021 |
+
if self.position_biased_input:
|
1022 |
+
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
|
1023 |
+
final_embeddings += position_embeds
|
1024 |
+
if self.config.type_vocab_size > 0:
|
1025 |
+
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
|
1026 |
+
final_embeddings += token_type_embeds
|
1027 |
+
|
1028 |
+
if self.embedding_size != self.hidden_size:
|
1029 |
+
final_embeddings = self.embed_proj(final_embeddings)
|
1030 |
+
|
1031 |
+
final_embeddings = self.LayerNorm(final_embeddings)
|
1032 |
+
|
1033 |
+
if mask is not None:
|
1034 |
+
if len(shape_list(mask)) != len(shape_list(final_embeddings)):
|
1035 |
+
if len(shape_list(mask)) == 4:
|
1036 |
+
mask = tf.squeeze(tf.squeeze(mask, axis=1), axis=1)
|
1037 |
+
mask = tf.cast(tf.expand_dims(mask, axis=2), tf.float32)
|
1038 |
+
|
1039 |
+
final_embeddings = final_embeddings * mask
|
1040 |
+
|
1041 |
+
final_embeddings = self.dropout(final_embeddings, training=training)
|
1042 |
+
|
1043 |
+
return final_embeddings
|
1044 |
+
|
1045 |
+
|
1046 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaPredictionHeadTransform with Deberta->DebertaV2
|
1047 |
+
class TFDebertaV2PredictionHeadTransform(keras.layers.Layer):
|
1048 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
1049 |
+
super().__init__(**kwargs)
|
1050 |
+
|
1051 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
1052 |
+
|
1053 |
+
self.dense = keras.layers.Dense(
|
1054 |
+
units=self.embedding_size,
|
1055 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
1056 |
+
name="dense",
|
1057 |
+
)
|
1058 |
+
|
1059 |
+
if isinstance(config.hidden_act, str):
|
1060 |
+
self.transform_act_fn = get_tf_activation(config.hidden_act)
|
1061 |
+
else:
|
1062 |
+
self.transform_act_fn = config.hidden_act
|
1063 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
1064 |
+
self.config = config
|
1065 |
+
|
1066 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
1067 |
+
hidden_states = self.dense(inputs=hidden_states)
|
1068 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
1069 |
+
hidden_states = self.LayerNorm(hidden_states)
|
1070 |
+
|
1071 |
+
return hidden_states
|
1072 |
+
|
1073 |
+
def build(self, input_shape=None):
|
1074 |
+
if self.built:
|
1075 |
+
return
|
1076 |
+
self.built = True
|
1077 |
+
if getattr(self, "dense", None) is not None:
|
1078 |
+
with tf.name_scope(self.dense.name):
|
1079 |
+
self.dense.build([None, None, self.config.hidden_size])
|
1080 |
+
if getattr(self, "LayerNorm", None) is not None:
|
1081 |
+
with tf.name_scope(self.LayerNorm.name):
|
1082 |
+
self.LayerNorm.build([None, None, self.embedding_size])
|
1083 |
+
|
1084 |
+
|
1085 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaLMPredictionHead with Deberta->DebertaV2
|
1086 |
+
class TFDebertaV2LMPredictionHead(keras.layers.Layer):
|
1087 |
+
def __init__(self, config: DebertaV2Config, input_embeddings: keras.layers.Layer, **kwargs):
|
1088 |
+
super().__init__(**kwargs)
|
1089 |
+
|
1090 |
+
self.config = config
|
1091 |
+
self.embedding_size = getattr(config, "embedding_size", config.hidden_size)
|
1092 |
+
|
1093 |
+
self.transform = TFDebertaV2PredictionHeadTransform(config, name="transform")
|
1094 |
+
|
1095 |
+
# The output weights are the same as the input embeddings, but there is
|
1096 |
+
# an output-only bias for each token.
|
1097 |
+
self.input_embeddings = input_embeddings
|
1098 |
+
|
1099 |
+
def build(self, input_shape=None):
|
1100 |
+
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
|
1101 |
+
|
1102 |
+
if self.built:
|
1103 |
+
return
|
1104 |
+
self.built = True
|
1105 |
+
if getattr(self, "transform", None) is not None:
|
1106 |
+
with tf.name_scope(self.transform.name):
|
1107 |
+
self.transform.build(None)
|
1108 |
+
|
1109 |
+
def get_output_embeddings(self) -> keras.layers.Layer:
|
1110 |
+
return self.input_embeddings
|
1111 |
+
|
1112 |
+
def set_output_embeddings(self, value: tf.Variable):
|
1113 |
+
self.input_embeddings.weight = value
|
1114 |
+
self.input_embeddings.vocab_size = shape_list(value)[0]
|
1115 |
+
|
1116 |
+
def get_bias(self) -> Dict[str, tf.Variable]:
|
1117 |
+
return {"bias": self.bias}
|
1118 |
+
|
1119 |
+
def set_bias(self, value: tf.Variable):
|
1120 |
+
self.bias = value["bias"]
|
1121 |
+
self.config.vocab_size = shape_list(value["bias"])[0]
|
1122 |
+
|
1123 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
1124 |
+
hidden_states = self.transform(hidden_states=hidden_states)
|
1125 |
+
seq_length = shape_list(hidden_states)[1]
|
1126 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])
|
1127 |
+
hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
|
1128 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
|
1129 |
+
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
|
1130 |
+
|
1131 |
+
return hidden_states
|
1132 |
+
|
1133 |
+
|
1134 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaOnlyMLMHead with Deberta->DebertaV2
|
1135 |
+
class TFDebertaV2OnlyMLMHead(keras.layers.Layer):
|
1136 |
+
def __init__(self, config: DebertaV2Config, input_embeddings: keras.layers.Layer, **kwargs):
|
1137 |
+
super().__init__(**kwargs)
|
1138 |
+
self.predictions = TFDebertaV2LMPredictionHead(config, input_embeddings, name="predictions")
|
1139 |
+
|
1140 |
+
def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
|
1141 |
+
prediction_scores = self.predictions(hidden_states=sequence_output)
|
1142 |
+
|
1143 |
+
return prediction_scores
|
1144 |
+
|
1145 |
+
def build(self, input_shape=None):
|
1146 |
+
if self.built:
|
1147 |
+
return
|
1148 |
+
self.built = True
|
1149 |
+
if getattr(self, "predictions", None) is not None:
|
1150 |
+
with tf.name_scope(self.predictions.name):
|
1151 |
+
self.predictions.build(None)
|
1152 |
+
|
1153 |
+
|
1154 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaMainLayer with Deberta->DebertaV2
|
1155 |
+
class TFDebertaV2MainLayer(keras.layers.Layer):
|
1156 |
+
config_class = DebertaV2Config
|
1157 |
+
|
1158 |
+
def __init__(self, config: DebertaV2Config, **kwargs):
|
1159 |
+
super().__init__(**kwargs)
|
1160 |
+
|
1161 |
+
self.config = config
|
1162 |
+
|
1163 |
+
self.embeddings = TFDebertaV2Embeddings(config, name="embeddings")
|
1164 |
+
self.encoder = TFDebertaV2Encoder(config, name="encoder")
|
1165 |
+
|
1166 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
1167 |
+
return self.embeddings
|
1168 |
+
|
1169 |
+
def set_input_embeddings(self, value: tf.Variable):
|
1170 |
+
self.embeddings.weight = value
|
1171 |
+
self.embeddings.vocab_size = shape_list(value)[0]
|
1172 |
+
|
1173 |
+
def _prune_heads(self, heads_to_prune):
|
1174 |
+
"""
|
1175 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
1176 |
+
class PreTrainedModel
|
1177 |
+
"""
|
1178 |
+
raise NotImplementedError
|
1179 |
+
|
1180 |
+
@unpack_inputs
|
1181 |
+
def call(
|
1182 |
+
self,
|
1183 |
+
input_ids: TFModelInputType | None = None,
|
1184 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1185 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
1186 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1187 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
1188 |
+
output_attentions: Optional[bool] = None,
|
1189 |
+
output_hidden_states: Optional[bool] = None,
|
1190 |
+
return_dict: Optional[bool] = None,
|
1191 |
+
training: bool = False,
|
1192 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
1193 |
+
if input_ids is not None and inputs_embeds is not None:
|
1194 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1195 |
+
elif input_ids is not None:
|
1196 |
+
input_shape = shape_list(input_ids)
|
1197 |
+
elif inputs_embeds is not None:
|
1198 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
1199 |
+
else:
|
1200 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1201 |
+
|
1202 |
+
if attention_mask is None:
|
1203 |
+
attention_mask = tf.fill(dims=input_shape, value=1)
|
1204 |
+
|
1205 |
+
if token_type_ids is None:
|
1206 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
1207 |
+
|
1208 |
+
embedding_output = self.embeddings(
|
1209 |
+
input_ids=input_ids,
|
1210 |
+
position_ids=position_ids,
|
1211 |
+
token_type_ids=token_type_ids,
|
1212 |
+
inputs_embeds=inputs_embeds,
|
1213 |
+
mask=attention_mask,
|
1214 |
+
training=training,
|
1215 |
+
)
|
1216 |
+
|
1217 |
+
encoder_outputs = self.encoder(
|
1218 |
+
hidden_states=embedding_output,
|
1219 |
+
attention_mask=attention_mask,
|
1220 |
+
output_attentions=output_attentions,
|
1221 |
+
output_hidden_states=output_hidden_states,
|
1222 |
+
return_dict=return_dict,
|
1223 |
+
training=training,
|
1224 |
+
)
|
1225 |
+
|
1226 |
+
sequence_output = encoder_outputs[0]
|
1227 |
+
|
1228 |
+
if not return_dict:
|
1229 |
+
return (sequence_output,) + encoder_outputs[1:]
|
1230 |
+
|
1231 |
+
return TFBaseModelOutput(
|
1232 |
+
last_hidden_state=sequence_output,
|
1233 |
+
hidden_states=encoder_outputs.hidden_states,
|
1234 |
+
attentions=encoder_outputs.attentions,
|
1235 |
+
)
|
1236 |
+
|
1237 |
+
def build(self, input_shape=None):
|
1238 |
+
if self.built:
|
1239 |
+
return
|
1240 |
+
self.built = True
|
1241 |
+
if getattr(self, "embeddings", None) is not None:
|
1242 |
+
with tf.name_scope(self.embeddings.name):
|
1243 |
+
self.embeddings.build(None)
|
1244 |
+
if getattr(self, "encoder", None) is not None:
|
1245 |
+
with tf.name_scope(self.encoder.name):
|
1246 |
+
self.encoder.build(None)
|
1247 |
+
|
1248 |
+
|
1249 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaPreTrainedModel with Deberta->DebertaV2
|
1250 |
+
class TFDebertaV2PreTrainedModel(TFPreTrainedModel):
|
1251 |
+
"""
|
1252 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
1253 |
+
models.
|
1254 |
+
"""
|
1255 |
+
|
1256 |
+
config_class = DebertaV2Config
|
1257 |
+
base_model_prefix = "deberta"
|
1258 |
+
|
1259 |
+
|
1260 |
+
DEBERTA_START_DOCSTRING = r"""
|
1261 |
+
The DeBERTa model was proposed in [DeBERTa: Decoding-enhanced BERT with Disentangled
|
1262 |
+
Attention](https://arxiv.org/abs/2006.03654) by Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen. It's build
|
1263 |
+
on top of BERT/RoBERTa with two improvements, i.e. disentangled attention and enhanced mask decoder. With those two
|
1264 |
+
improvements, it out perform BERT/RoBERTa on a majority of tasks with 80GB pretraining data.
|
1265 |
+
|
1266 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
1267 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
1268 |
+
behavior.
|
1269 |
+
|
1270 |
+
<Tip>
|
1271 |
+
|
1272 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
1273 |
+
|
1274 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
1275 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
1276 |
+
|
1277 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
1278 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
1279 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
1280 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
1281 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
1282 |
+
positional argument:
|
1283 |
+
|
1284 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
1285 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
1286 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
1287 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
1288 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
1289 |
+
|
1290 |
+
Note that when creating models and layers with
|
1291 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
1292 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
1293 |
+
|
1294 |
+
</Tip>
|
1295 |
+
|
1296 |
+
Parameters:
|
1297 |
+
config ([`DebertaV2Config`]): Model configuration class with all the parameters of the model.
|
1298 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
1299 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
1300 |
+
"""
|
1301 |
+
|
1302 |
+
DEBERTA_INPUTS_DOCSTRING = r"""
|
1303 |
+
Args:
|
1304 |
+
input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
|
1305 |
+
Indices of input sequence tokens in the vocabulary.
|
1306 |
+
|
1307 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
1308 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
1309 |
+
|
1310 |
+
[What are input IDs?](../glossary#input-ids)
|
1311 |
+
attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
1312 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1313 |
+
|
1314 |
+
- 1 for tokens that are **not masked**,
|
1315 |
+
- 0 for tokens that are **masked**.
|
1316 |
+
|
1317 |
+
[What are attention masks?](../glossary#attention-mask)
|
1318 |
+
token_type_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
1319 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
1320 |
+
1]`:
|
1321 |
+
|
1322 |
+
- 0 corresponds to a *sentence A* token,
|
1323 |
+
- 1 corresponds to a *sentence B* token.
|
1324 |
+
|
1325 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
1326 |
+
position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
1327 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1328 |
+
config.max_position_embeddings - 1]`.
|
1329 |
+
|
1330 |
+
[What are position IDs?](../glossary#position-ids)
|
1331 |
+
inputs_embeds (`np.ndarray` or `tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
|
1332 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
1333 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
1334 |
+
model's internal embedding lookup matrix.
|
1335 |
+
output_attentions (`bool`, *optional*):
|
1336 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1337 |
+
tensors for more detail.
|
1338 |
+
output_hidden_states (`bool`, *optional*):
|
1339 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1340 |
+
more detail.
|
1341 |
+
return_dict (`bool`, *optional*):
|
1342 |
+
Whether or not to return a [`~utils.ModelOutput``] instead of a plain tuple.
|
1343 |
+
"""
|
1344 |
+
|
1345 |
+
|
1346 |
+
@add_start_docstrings(
|
1347 |
+
"The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.",
|
1348 |
+
DEBERTA_START_DOCSTRING,
|
1349 |
+
)
|
1350 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaModel with Deberta->DebertaV2
|
1351 |
+
class TFDebertaV2Model(TFDebertaV2PreTrainedModel):
|
1352 |
+
def __init__(self, config: DebertaV2Config, *inputs, **kwargs):
|
1353 |
+
super().__init__(config, *inputs, **kwargs)
|
1354 |
+
|
1355 |
+
self.deberta = TFDebertaV2MainLayer(config, name="deberta")
|
1356 |
+
|
1357 |
+
@unpack_inputs
|
1358 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1359 |
+
@add_code_sample_docstrings(
|
1360 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1361 |
+
output_type=TFBaseModelOutput,
|
1362 |
+
config_class=_CONFIG_FOR_DOC,
|
1363 |
+
)
|
1364 |
+
def call(
|
1365 |
+
self,
|
1366 |
+
input_ids: TFModelInputType | None = None,
|
1367 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1368 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
1369 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1370 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
1371 |
+
output_attentions: Optional[bool] = None,
|
1372 |
+
output_hidden_states: Optional[bool] = None,
|
1373 |
+
return_dict: Optional[bool] = None,
|
1374 |
+
training: Optional[bool] = False,
|
1375 |
+
) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:
|
1376 |
+
outputs = self.deberta(
|
1377 |
+
input_ids=input_ids,
|
1378 |
+
attention_mask=attention_mask,
|
1379 |
+
token_type_ids=token_type_ids,
|
1380 |
+
position_ids=position_ids,
|
1381 |
+
inputs_embeds=inputs_embeds,
|
1382 |
+
output_attentions=output_attentions,
|
1383 |
+
output_hidden_states=output_hidden_states,
|
1384 |
+
return_dict=return_dict,
|
1385 |
+
training=training,
|
1386 |
+
)
|
1387 |
+
|
1388 |
+
return outputs
|
1389 |
+
|
1390 |
+
def build(self, input_shape=None):
|
1391 |
+
if self.built:
|
1392 |
+
return
|
1393 |
+
self.built = True
|
1394 |
+
if getattr(self, "deberta", None) is not None:
|
1395 |
+
with tf.name_scope(self.deberta.name):
|
1396 |
+
self.deberta.build(None)
|
1397 |
+
|
1398 |
+
|
1399 |
+
@add_start_docstrings("""DeBERTa Model with a `language modeling` head on top.""", DEBERTA_START_DOCSTRING)
|
1400 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaForMaskedLM with Deberta->DebertaV2
|
1401 |
+
class TFDebertaV2ForMaskedLM(TFDebertaV2PreTrainedModel, TFMaskedLanguageModelingLoss):
|
1402 |
+
def __init__(self, config: DebertaV2Config, *inputs, **kwargs):
|
1403 |
+
super().__init__(config, *inputs, **kwargs)
|
1404 |
+
|
1405 |
+
if config.is_decoder:
|
1406 |
+
logger.warning(
|
1407 |
+
"If you want to use `TFDebertaV2ForMaskedLM` make sure `config.is_decoder=False` for "
|
1408 |
+
"bi-directional self-attention."
|
1409 |
+
)
|
1410 |
+
|
1411 |
+
self.deberta = TFDebertaV2MainLayer(config, name="deberta")
|
1412 |
+
self.mlm = TFDebertaV2OnlyMLMHead(config, input_embeddings=self.deberta.embeddings, name="cls")
|
1413 |
+
|
1414 |
+
def get_lm_head(self) -> keras.layers.Layer:
|
1415 |
+
return self.mlm.predictions
|
1416 |
+
|
1417 |
+
@unpack_inputs
|
1418 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1419 |
+
@add_code_sample_docstrings(
|
1420 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1421 |
+
output_type=TFMaskedLMOutput,
|
1422 |
+
config_class=_CONFIG_FOR_DOC,
|
1423 |
+
)
|
1424 |
+
def call(
|
1425 |
+
self,
|
1426 |
+
input_ids: TFModelInputType | None = None,
|
1427 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1428 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
1429 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1430 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
1431 |
+
output_attentions: Optional[bool] = None,
|
1432 |
+
output_hidden_states: Optional[bool] = None,
|
1433 |
+
return_dict: Optional[bool] = None,
|
1434 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
1435 |
+
training: Optional[bool] = False,
|
1436 |
+
) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
|
1437 |
+
r"""
|
1438 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
1439 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
1440 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
1441 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1442 |
+
"""
|
1443 |
+
outputs = self.deberta(
|
1444 |
+
input_ids=input_ids,
|
1445 |
+
attention_mask=attention_mask,
|
1446 |
+
token_type_ids=token_type_ids,
|
1447 |
+
position_ids=position_ids,
|
1448 |
+
inputs_embeds=inputs_embeds,
|
1449 |
+
output_attentions=output_attentions,
|
1450 |
+
output_hidden_states=output_hidden_states,
|
1451 |
+
return_dict=return_dict,
|
1452 |
+
training=training,
|
1453 |
+
)
|
1454 |
+
sequence_output = outputs[0]
|
1455 |
+
prediction_scores = self.mlm(sequence_output=sequence_output, training=training)
|
1456 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores)
|
1457 |
+
|
1458 |
+
if not return_dict:
|
1459 |
+
output = (prediction_scores,) + outputs[2:]
|
1460 |
+
return ((loss,) + output) if loss is not None else output
|
1461 |
+
|
1462 |
+
return TFMaskedLMOutput(
|
1463 |
+
loss=loss,
|
1464 |
+
logits=prediction_scores,
|
1465 |
+
hidden_states=outputs.hidden_states,
|
1466 |
+
attentions=outputs.attentions,
|
1467 |
+
)
|
1468 |
+
|
1469 |
+
def build(self, input_shape=None):
|
1470 |
+
if self.built:
|
1471 |
+
return
|
1472 |
+
self.built = True
|
1473 |
+
if getattr(self, "deberta", None) is not None:
|
1474 |
+
with tf.name_scope(self.deberta.name):
|
1475 |
+
self.deberta.build(None)
|
1476 |
+
if getattr(self, "mlm", None) is not None:
|
1477 |
+
with tf.name_scope(self.mlm.name):
|
1478 |
+
self.mlm.build(None)
|
1479 |
+
|
1480 |
+
|
1481 |
+
@add_start_docstrings(
|
1482 |
+
"""
|
1483 |
+
DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
|
1484 |
+
pooled output) e.g. for GLUE tasks.
|
1485 |
+
""",
|
1486 |
+
DEBERTA_START_DOCSTRING,
|
1487 |
+
)
|
1488 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaForSequenceClassification with Deberta->DebertaV2
|
1489 |
+
class TFDebertaV2ForSequenceClassification(TFDebertaV2PreTrainedModel, TFSequenceClassificationLoss):
|
1490 |
+
def __init__(self, config: DebertaV2Config, *inputs, **kwargs):
|
1491 |
+
super().__init__(config, *inputs, **kwargs)
|
1492 |
+
|
1493 |
+
self.num_labels = config.num_labels
|
1494 |
+
|
1495 |
+
self.deberta = TFDebertaV2MainLayer(config, name="deberta")
|
1496 |
+
self.pooler = TFDebertaV2ContextPooler(config, name="pooler")
|
1497 |
+
|
1498 |
+
drop_out = getattr(config, "cls_dropout", None)
|
1499 |
+
drop_out = self.config.hidden_dropout_prob if drop_out is None else drop_out
|
1500 |
+
self.dropout = TFDebertaV2StableDropout(drop_out, name="cls_dropout")
|
1501 |
+
self.classifier = keras.layers.Dense(
|
1502 |
+
units=config.num_labels,
|
1503 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
1504 |
+
name="classifier",
|
1505 |
+
)
|
1506 |
+
self.output_dim = self.pooler.output_dim
|
1507 |
+
|
1508 |
+
@unpack_inputs
|
1509 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1510 |
+
@add_code_sample_docstrings(
|
1511 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1512 |
+
output_type=TFSequenceClassifierOutput,
|
1513 |
+
config_class=_CONFIG_FOR_DOC,
|
1514 |
+
)
|
1515 |
+
def call(
|
1516 |
+
self,
|
1517 |
+
input_ids: TFModelInputType | None = None,
|
1518 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1519 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
1520 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1521 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
1522 |
+
output_attentions: Optional[bool] = None,
|
1523 |
+
output_hidden_states: Optional[bool] = None,
|
1524 |
+
return_dict: Optional[bool] = None,
|
1525 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
1526 |
+
training: Optional[bool] = False,
|
1527 |
+
) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
|
1528 |
+
r"""
|
1529 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
1530 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1531 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1532 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1533 |
+
"""
|
1534 |
+
outputs = self.deberta(
|
1535 |
+
input_ids=input_ids,
|
1536 |
+
attention_mask=attention_mask,
|
1537 |
+
token_type_ids=token_type_ids,
|
1538 |
+
position_ids=position_ids,
|
1539 |
+
inputs_embeds=inputs_embeds,
|
1540 |
+
output_attentions=output_attentions,
|
1541 |
+
output_hidden_states=output_hidden_states,
|
1542 |
+
return_dict=return_dict,
|
1543 |
+
training=training,
|
1544 |
+
)
|
1545 |
+
sequence_output = outputs[0]
|
1546 |
+
pooled_output = self.pooler(sequence_output, training=training)
|
1547 |
+
pooled_output = self.dropout(pooled_output, training=training)
|
1548 |
+
logits = self.classifier(pooled_output)
|
1549 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
1550 |
+
|
1551 |
+
if not return_dict:
|
1552 |
+
output = (logits,) + outputs[1:]
|
1553 |
+
|
1554 |
+
return ((loss,) + output) if loss is not None else output
|
1555 |
+
|
1556 |
+
return TFSequenceClassifierOutput(
|
1557 |
+
loss=loss,
|
1558 |
+
logits=logits,
|
1559 |
+
hidden_states=outputs.hidden_states,
|
1560 |
+
attentions=outputs.attentions,
|
1561 |
+
)
|
1562 |
+
|
1563 |
+
def build(self, input_shape=None):
|
1564 |
+
if self.built:
|
1565 |
+
return
|
1566 |
+
self.built = True
|
1567 |
+
if getattr(self, "deberta", None) is not None:
|
1568 |
+
with tf.name_scope(self.deberta.name):
|
1569 |
+
self.deberta.build(None)
|
1570 |
+
if getattr(self, "pooler", None) is not None:
|
1571 |
+
with tf.name_scope(self.pooler.name):
|
1572 |
+
self.pooler.build(None)
|
1573 |
+
if getattr(self, "dropout", None) is not None:
|
1574 |
+
with tf.name_scope(self.dropout.name):
|
1575 |
+
self.dropout.build(None)
|
1576 |
+
if getattr(self, "classifier", None) is not None:
|
1577 |
+
with tf.name_scope(self.classifier.name):
|
1578 |
+
self.classifier.build([None, None, self.output_dim])
|
1579 |
+
|
1580 |
+
|
1581 |
+
@add_start_docstrings(
|
1582 |
+
"""
|
1583 |
+
DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
1584 |
+
Named-Entity-Recognition (NER) tasks.
|
1585 |
+
""",
|
1586 |
+
DEBERTA_START_DOCSTRING,
|
1587 |
+
)
|
1588 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaForTokenClassification with Deberta->DebertaV2
|
1589 |
+
class TFDebertaV2ForTokenClassification(TFDebertaV2PreTrainedModel, TFTokenClassificationLoss):
|
1590 |
+
def __init__(self, config: DebertaV2Config, *inputs, **kwargs):
|
1591 |
+
super().__init__(config, *inputs, **kwargs)
|
1592 |
+
|
1593 |
+
self.num_labels = config.num_labels
|
1594 |
+
|
1595 |
+
self.deberta = TFDebertaV2MainLayer(config, name="deberta")
|
1596 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
1597 |
+
self.classifier = keras.layers.Dense(
|
1598 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
1599 |
+
)
|
1600 |
+
self.config = config
|
1601 |
+
|
1602 |
+
@unpack_inputs
|
1603 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1604 |
+
@add_code_sample_docstrings(
|
1605 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1606 |
+
output_type=TFTokenClassifierOutput,
|
1607 |
+
config_class=_CONFIG_FOR_DOC,
|
1608 |
+
)
|
1609 |
+
def call(
|
1610 |
+
self,
|
1611 |
+
input_ids: TFModelInputType | None = None,
|
1612 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1613 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
1614 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1615 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
1616 |
+
output_attentions: Optional[bool] = None,
|
1617 |
+
output_hidden_states: Optional[bool] = None,
|
1618 |
+
return_dict: Optional[bool] = None,
|
1619 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
1620 |
+
training: Optional[bool] = False,
|
1621 |
+
) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
|
1622 |
+
r"""
|
1623 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
1624 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
1625 |
+
"""
|
1626 |
+
outputs = self.deberta(
|
1627 |
+
input_ids=input_ids,
|
1628 |
+
attention_mask=attention_mask,
|
1629 |
+
token_type_ids=token_type_ids,
|
1630 |
+
position_ids=position_ids,
|
1631 |
+
inputs_embeds=inputs_embeds,
|
1632 |
+
output_attentions=output_attentions,
|
1633 |
+
output_hidden_states=output_hidden_states,
|
1634 |
+
return_dict=return_dict,
|
1635 |
+
training=training,
|
1636 |
+
)
|
1637 |
+
sequence_output = outputs[0]
|
1638 |
+
sequence_output = self.dropout(sequence_output, training=training)
|
1639 |
+
logits = self.classifier(inputs=sequence_output)
|
1640 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
1641 |
+
|
1642 |
+
if not return_dict:
|
1643 |
+
output = (logits,) + outputs[1:]
|
1644 |
+
return ((loss,) + output) if loss is not None else output
|
1645 |
+
|
1646 |
+
return TFTokenClassifierOutput(
|
1647 |
+
loss=loss,
|
1648 |
+
logits=logits,
|
1649 |
+
hidden_states=outputs.hidden_states,
|
1650 |
+
attentions=outputs.attentions,
|
1651 |
+
)
|
1652 |
+
|
1653 |
+
def build(self, input_shape=None):
|
1654 |
+
if self.built:
|
1655 |
+
return
|
1656 |
+
self.built = True
|
1657 |
+
if getattr(self, "deberta", None) is not None:
|
1658 |
+
with tf.name_scope(self.deberta.name):
|
1659 |
+
self.deberta.build(None)
|
1660 |
+
if getattr(self, "classifier", None) is not None:
|
1661 |
+
with tf.name_scope(self.classifier.name):
|
1662 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
1663 |
+
|
1664 |
+
|
1665 |
+
@add_start_docstrings(
|
1666 |
+
"""
|
1667 |
+
DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
1668 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1669 |
+
""",
|
1670 |
+
DEBERTA_START_DOCSTRING,
|
1671 |
+
)
|
1672 |
+
# Copied from transformers.models.deberta.modeling_tf_deberta.TFDebertaForQuestionAnswering with Deberta->DebertaV2
|
1673 |
+
class TFDebertaV2ForQuestionAnswering(TFDebertaV2PreTrainedModel, TFQuestionAnsweringLoss):
|
1674 |
+
def __init__(self, config: DebertaV2Config, *inputs, **kwargs):
|
1675 |
+
super().__init__(config, *inputs, **kwargs)
|
1676 |
+
|
1677 |
+
self.num_labels = config.num_labels
|
1678 |
+
|
1679 |
+
self.deberta = TFDebertaV2MainLayer(config, name="deberta")
|
1680 |
+
self.qa_outputs = keras.layers.Dense(
|
1681 |
+
units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
1682 |
+
)
|
1683 |
+
self.config = config
|
1684 |
+
|
1685 |
+
@unpack_inputs
|
1686 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1687 |
+
@add_code_sample_docstrings(
|
1688 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1689 |
+
output_type=TFQuestionAnsweringModelOutput,
|
1690 |
+
config_class=_CONFIG_FOR_DOC,
|
1691 |
+
)
|
1692 |
+
def call(
|
1693 |
+
self,
|
1694 |
+
input_ids: TFModelInputType | None = None,
|
1695 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1696 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
1697 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1698 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
1699 |
+
output_attentions: Optional[bool] = None,
|
1700 |
+
output_hidden_states: Optional[bool] = None,
|
1701 |
+
return_dict: Optional[bool] = None,
|
1702 |
+
start_positions: np.ndarray | tf.Tensor | None = None,
|
1703 |
+
end_positions: np.ndarray | tf.Tensor | None = None,
|
1704 |
+
training: Optional[bool] = False,
|
1705 |
+
) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
|
1706 |
+
r"""
|
1707 |
+
start_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
1708 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1709 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1710 |
+
are not taken into account for computing the loss.
|
1711 |
+
end_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
1712 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1713 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1714 |
+
are not taken into account for computing the loss.
|
1715 |
+
"""
|
1716 |
+
outputs = self.deberta(
|
1717 |
+
input_ids=input_ids,
|
1718 |
+
attention_mask=attention_mask,
|
1719 |
+
token_type_ids=token_type_ids,
|
1720 |
+
position_ids=position_ids,
|
1721 |
+
inputs_embeds=inputs_embeds,
|
1722 |
+
output_attentions=output_attentions,
|
1723 |
+
output_hidden_states=output_hidden_states,
|
1724 |
+
return_dict=return_dict,
|
1725 |
+
training=training,
|
1726 |
+
)
|
1727 |
+
sequence_output = outputs[0]
|
1728 |
+
logits = self.qa_outputs(inputs=sequence_output)
|
1729 |
+
start_logits, end_logits = tf.split(value=logits, num_or_size_splits=2, axis=-1)
|
1730 |
+
start_logits = tf.squeeze(input=start_logits, axis=-1)
|
1731 |
+
end_logits = tf.squeeze(input=end_logits, axis=-1)
|
1732 |
+
loss = None
|
1733 |
+
|
1734 |
+
if start_positions is not None and end_positions is not None:
|
1735 |
+
labels = {"start_position": start_positions}
|
1736 |
+
labels["end_position"] = end_positions
|
1737 |
+
loss = self.hf_compute_loss(labels=labels, logits=(start_logits, end_logits))
|
1738 |
+
|
1739 |
+
if not return_dict:
|
1740 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1741 |
+
return ((loss,) + output) if loss is not None else output
|
1742 |
+
|
1743 |
+
return TFQuestionAnsweringModelOutput(
|
1744 |
+
loss=loss,
|
1745 |
+
start_logits=start_logits,
|
1746 |
+
end_logits=end_logits,
|
1747 |
+
hidden_states=outputs.hidden_states,
|
1748 |
+
attentions=outputs.attentions,
|
1749 |
+
)
|
1750 |
+
|
1751 |
+
def build(self, input_shape=None):
|
1752 |
+
if self.built:
|
1753 |
+
return
|
1754 |
+
self.built = True
|
1755 |
+
if getattr(self, "deberta", None) is not None:
|
1756 |
+
with tf.name_scope(self.deberta.name):
|
1757 |
+
self.deberta.build(None)
|
1758 |
+
if getattr(self, "qa_outputs", None) is not None:
|
1759 |
+
with tf.name_scope(self.qa_outputs.name):
|
1760 |
+
self.qa_outputs.build([None, None, self.config.hidden_size])
|
1761 |
+
|
1762 |
+
|
1763 |
+
@add_start_docstrings(
|
1764 |
+
"""
|
1765 |
+
DeBERTa Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
1766 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
1767 |
+
""",
|
1768 |
+
DEBERTA_START_DOCSTRING,
|
1769 |
+
)
|
1770 |
+
class TFDebertaV2ForMultipleChoice(TFDebertaV2PreTrainedModel, TFMultipleChoiceLoss):
|
1771 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
1772 |
+
# _keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"nsp___cls", r"cls.predictions", r"cls.seq_relationship"]
|
1773 |
+
# _keys_to_ignore_on_load_missing = [r"dropout"]
|
1774 |
+
|
1775 |
+
def __init__(self, config: DebertaV2Config, *inputs, **kwargs):
|
1776 |
+
super().__init__(config, *inputs, **kwargs)
|
1777 |
+
|
1778 |
+
self.deberta = TFDebertaV2MainLayer(config, name="deberta")
|
1779 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
1780 |
+
self.pooler = TFDebertaV2ContextPooler(config, name="pooler")
|
1781 |
+
self.classifier = keras.layers.Dense(
|
1782 |
+
units=1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
1783 |
+
)
|
1784 |
+
self.output_dim = self.pooler.output_dim
|
1785 |
+
|
1786 |
+
@unpack_inputs
|
1787 |
+
@add_start_docstrings_to_model_forward(DEBERTA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
1788 |
+
@add_code_sample_docstrings(
|
1789 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1790 |
+
output_type=TFMultipleChoiceModelOutput,
|
1791 |
+
config_class=_CONFIG_FOR_DOC,
|
1792 |
+
)
|
1793 |
+
def call(
|
1794 |
+
self,
|
1795 |
+
input_ids: TFModelInputType | None = None,
|
1796 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
1797 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
1798 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
1799 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
1800 |
+
output_attentions: Optional[bool] = None,
|
1801 |
+
output_hidden_states: Optional[bool] = None,
|
1802 |
+
return_dict: Optional[bool] = None,
|
1803 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
1804 |
+
training: Optional[bool] = False,
|
1805 |
+
) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
|
1806 |
+
r"""
|
1807 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
1808 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
|
1809 |
+
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
|
1810 |
+
"""
|
1811 |
+
if input_ids is not None:
|
1812 |
+
num_choices = shape_list(input_ids)[1]
|
1813 |
+
seq_length = shape_list(input_ids)[2]
|
1814 |
+
else:
|
1815 |
+
num_choices = shape_list(inputs_embeds)[1]
|
1816 |
+
seq_length = shape_list(inputs_embeds)[2]
|
1817 |
+
|
1818 |
+
flat_input_ids = tf.reshape(tensor=input_ids, shape=(-1, seq_length)) if input_ids is not None else None
|
1819 |
+
flat_attention_mask = (
|
1820 |
+
tf.reshape(tensor=attention_mask, shape=(-1, seq_length)) if attention_mask is not None else None
|
1821 |
+
)
|
1822 |
+
flat_token_type_ids = (
|
1823 |
+
tf.reshape(tensor=token_type_ids, shape=(-1, seq_length)) if token_type_ids is not None else None
|
1824 |
+
)
|
1825 |
+
flat_position_ids = (
|
1826 |
+
tf.reshape(tensor=position_ids, shape=(-1, seq_length)) if position_ids is not None else None
|
1827 |
+
)
|
1828 |
+
flat_inputs_embeds = (
|
1829 |
+
tf.reshape(tensor=inputs_embeds, shape=(-1, seq_length, shape_list(inputs_embeds)[3]))
|
1830 |
+
if inputs_embeds is not None
|
1831 |
+
else None
|
1832 |
+
)
|
1833 |
+
outputs = self.deberta(
|
1834 |
+
input_ids=flat_input_ids,
|
1835 |
+
attention_mask=flat_attention_mask,
|
1836 |
+
token_type_ids=flat_token_type_ids,
|
1837 |
+
position_ids=flat_position_ids,
|
1838 |
+
inputs_embeds=flat_inputs_embeds,
|
1839 |
+
output_attentions=output_attentions,
|
1840 |
+
output_hidden_states=output_hidden_states,
|
1841 |
+
return_dict=return_dict,
|
1842 |
+
training=training,
|
1843 |
+
)
|
1844 |
+
sequence_output = outputs[0]
|
1845 |
+
pooled_output = self.pooler(sequence_output, training=training)
|
1846 |
+
pooled_output = self.dropout(pooled_output, training=training)
|
1847 |
+
logits = self.classifier(pooled_output)
|
1848 |
+
reshaped_logits = tf.reshape(tensor=logits, shape=(-1, num_choices))
|
1849 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=reshaped_logits)
|
1850 |
+
|
1851 |
+
if not return_dict:
|
1852 |
+
output = (reshaped_logits,) + outputs[2:]
|
1853 |
+
return ((loss,) + output) if loss is not None else output
|
1854 |
+
|
1855 |
+
return TFMultipleChoiceModelOutput(
|
1856 |
+
loss=loss,
|
1857 |
+
logits=reshaped_logits,
|
1858 |
+
hidden_states=outputs.hidden_states,
|
1859 |
+
attentions=outputs.attentions,
|
1860 |
+
)
|
1861 |
+
|
1862 |
+
def build(self, input_shape=None):
|
1863 |
+
if self.built:
|
1864 |
+
return
|
1865 |
+
self.built = True
|
1866 |
+
if getattr(self, "deberta", None) is not None:
|
1867 |
+
with tf.name_scope(self.deberta.name):
|
1868 |
+
self.deberta.build(None)
|
1869 |
+
if getattr(self, "pooler", None) is not None:
|
1870 |
+
with tf.name_scope(self.pooler.name):
|
1871 |
+
self.pooler.build(None)
|
1872 |
+
if getattr(self, "classifier", None) is not None:
|
1873 |
+
with tf.name_scope(self.classifier.name):
|
1874 |
+
self.classifier.build([None, None, self.output_dim])
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/tokenization_deberta_v2.py
ADDED
@@ -0,0 +1,521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2020 Microsoft 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 class for model DeBERTa."""
|
16 |
+
|
17 |
+
import os
|
18 |
+
import unicodedata
|
19 |
+
from typing import Any, Dict, List, Optional, Tuple
|
20 |
+
|
21 |
+
import sentencepiece as sp
|
22 |
+
|
23 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
24 |
+
from ...utils import logging
|
25 |
+
|
26 |
+
|
27 |
+
logger = logging.get_logger(__name__)
|
28 |
+
|
29 |
+
|
30 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spm.model"}
|
31 |
+
|
32 |
+
|
33 |
+
class DebertaV2Tokenizer(PreTrainedTokenizer):
|
34 |
+
r"""
|
35 |
+
Constructs a DeBERTa-v2 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
36 |
+
|
37 |
+
Args:
|
38 |
+
vocab_file (`str`):
|
39 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
40 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
41 |
+
do_lower_case (`bool`, *optional*, defaults to `False`):
|
42 |
+
Whether or not to lowercase the input when tokenizing.
|
43 |
+
bos_token (`string`, *optional*, defaults to `"[CLS]"`):
|
44 |
+
The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
|
45 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
46 |
+
sequence. The token used is the `cls_token`.
|
47 |
+
eos_token (`string`, *optional*, defaults to `"[SEP]"`):
|
48 |
+
The end of sequence token. When building a sequence using special tokens, this is not the token that is
|
49 |
+
used for the end of sequence. The token used is the `sep_token`.
|
50 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
51 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
52 |
+
token instead.
|
53 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
54 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
55 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
56 |
+
token of a sequence built with special tokens.
|
57 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
58 |
+
The token used for padding, for example when batching sequences of different lengths.
|
59 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
60 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
61 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
62 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
63 |
+
The token used for masking values. This is the token used when training this model with masked language
|
64 |
+
modeling. This is the token which the model will try to predict.
|
65 |
+
sp_model_kwargs (`dict`, *optional*):
|
66 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
67 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
68 |
+
to set:
|
69 |
+
|
70 |
+
- `enable_sampling`: Enable subword regularization.
|
71 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
72 |
+
|
73 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
74 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
75 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
76 |
+
using forward-filtering-and-backward-sampling algorithm.
|
77 |
+
|
78 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
79 |
+
BPE-dropout.
|
80 |
+
"""
|
81 |
+
|
82 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
83 |
+
|
84 |
+
def __init__(
|
85 |
+
self,
|
86 |
+
vocab_file,
|
87 |
+
do_lower_case=False,
|
88 |
+
split_by_punct=False,
|
89 |
+
bos_token="[CLS]",
|
90 |
+
eos_token="[SEP]",
|
91 |
+
unk_token="[UNK]",
|
92 |
+
sep_token="[SEP]",
|
93 |
+
pad_token="[PAD]",
|
94 |
+
cls_token="[CLS]",
|
95 |
+
mask_token="[MASK]",
|
96 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
97 |
+
**kwargs,
|
98 |
+
) -> None:
|
99 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
100 |
+
|
101 |
+
if not os.path.isfile(vocab_file):
|
102 |
+
raise ValueError(
|
103 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
|
104 |
+
" model use `tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
105 |
+
)
|
106 |
+
self.do_lower_case = do_lower_case
|
107 |
+
self.split_by_punct = split_by_punct
|
108 |
+
self.vocab_file = vocab_file
|
109 |
+
self._tokenizer = SPMTokenizer(
|
110 |
+
vocab_file, None, split_by_punct=split_by_punct, sp_model_kwargs=self.sp_model_kwargs
|
111 |
+
)
|
112 |
+
unk_token = AddedToken(unk_token, normalized=True, special=True) if isinstance(unk_token, str) else unk_token
|
113 |
+
super().__init__(
|
114 |
+
do_lower_case=do_lower_case,
|
115 |
+
bos_token=bos_token,
|
116 |
+
eos_token=eos_token,
|
117 |
+
unk_token=unk_token,
|
118 |
+
sep_token=sep_token,
|
119 |
+
pad_token=pad_token,
|
120 |
+
cls_token=cls_token,
|
121 |
+
mask_token=mask_token,
|
122 |
+
split_by_punct=split_by_punct,
|
123 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
124 |
+
**kwargs,
|
125 |
+
)
|
126 |
+
self._tokenizer.special_tokens = self.all_special_tokens
|
127 |
+
|
128 |
+
@property
|
129 |
+
def vocab_size(self):
|
130 |
+
return len(self.vocab)
|
131 |
+
|
132 |
+
@property
|
133 |
+
def vocab(self):
|
134 |
+
return self._tokenizer.vocab
|
135 |
+
|
136 |
+
def get_vocab(self):
|
137 |
+
vocab = self.vocab.copy()
|
138 |
+
vocab.update(self.get_added_vocab())
|
139 |
+
return vocab
|
140 |
+
|
141 |
+
def _tokenize(self, text: str) -> List[str]:
|
142 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
143 |
+
if self.do_lower_case:
|
144 |
+
text = text.lower()
|
145 |
+
return self._tokenizer.tokenize(text)
|
146 |
+
|
147 |
+
def _convert_token_to_id(self, token):
|
148 |
+
"""Converts a token (str) in an id using the vocab."""
|
149 |
+
return self._tokenizer.spm.PieceToId(token)
|
150 |
+
|
151 |
+
def _convert_id_to_token(self, index):
|
152 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
153 |
+
return self._tokenizer.spm.IdToPiece(index) if index < self.vocab_size else self.unk_token
|
154 |
+
|
155 |
+
def convert_tokens_to_string(self, tokens):
|
156 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
157 |
+
return self._tokenizer.decode(tokens)
|
158 |
+
|
159 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
160 |
+
"""
|
161 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
162 |
+
adding special tokens. A DeBERTa sequence has the following format:
|
163 |
+
|
164 |
+
- single sequence: [CLS] X [SEP]
|
165 |
+
- pair of sequences: [CLS] A [SEP] B [SEP]
|
166 |
+
|
167 |
+
Args:
|
168 |
+
token_ids_0 (`List[int]`):
|
169 |
+
List of IDs to which the special tokens will be added.
|
170 |
+
token_ids_1 (`List[int]`, *optional*):
|
171 |
+
Optional second list of IDs for sequence pairs.
|
172 |
+
|
173 |
+
Returns:
|
174 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
175 |
+
"""
|
176 |
+
|
177 |
+
if token_ids_1 is None:
|
178 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
179 |
+
cls = [self.cls_token_id]
|
180 |
+
sep = [self.sep_token_id]
|
181 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
182 |
+
|
183 |
+
def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
|
184 |
+
"""
|
185 |
+
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
|
186 |
+
special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
|
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 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
194 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
195 |
+
|
196 |
+
Returns:
|
197 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
198 |
+
"""
|
199 |
+
|
200 |
+
if already_has_special_tokens:
|
201 |
+
return super().get_special_tokens_mask(
|
202 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
203 |
+
)
|
204 |
+
|
205 |
+
if token_ids_1 is not None:
|
206 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
207 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
208 |
+
|
209 |
+
def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
|
210 |
+
"""
|
211 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
|
212 |
+
sequence pair mask has the following format:
|
213 |
+
|
214 |
+
```
|
215 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
216 |
+
| first sequence | second sequence |
|
217 |
+
```
|
218 |
+
|
219 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
220 |
+
|
221 |
+
Args:
|
222 |
+
token_ids_0 (`List[int]`):
|
223 |
+
List of IDs.
|
224 |
+
token_ids_1 (`List[int]`, *optional*):
|
225 |
+
Optional second list of IDs for sequence pairs.
|
226 |
+
|
227 |
+
Returns:
|
228 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
229 |
+
"""
|
230 |
+
sep = [self.sep_token_id]
|
231 |
+
cls = [self.cls_token_id]
|
232 |
+
if token_ids_1 is None:
|
233 |
+
return len(cls + token_ids_0 + sep) * [0]
|
234 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
235 |
+
|
236 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
237 |
+
add_prefix_space = kwargs.pop("add_prefix_space", False)
|
238 |
+
if is_split_into_words or add_prefix_space:
|
239 |
+
text = " " + text
|
240 |
+
return (text, kwargs)
|
241 |
+
|
242 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
243 |
+
return self._tokenizer.save_pretrained(save_directory, filename_prefix=filename_prefix)
|
244 |
+
|
245 |
+
|
246 |
+
class SPMTokenizer:
|
247 |
+
r"""
|
248 |
+
Constructs a tokenizer based on [SentencePiece](https://github.com/google/sentencepiece).
|
249 |
+
|
250 |
+
Args:
|
251 |
+
vocab_file (`str`):
|
252 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
253 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
254 |
+
sp_model_kwargs (`dict`, *optional*):
|
255 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
256 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
257 |
+
to set:
|
258 |
+
|
259 |
+
- `enable_sampling`: Enable subword regularization.
|
260 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
261 |
+
|
262 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
263 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
264 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
265 |
+
using forward-filtering-and-backward-sampling algorithm.
|
266 |
+
|
267 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
268 |
+
BPE-dropout.
|
269 |
+
"""
|
270 |
+
|
271 |
+
def __init__(
|
272 |
+
self, vocab_file, special_tokens, split_by_punct=False, sp_model_kwargs: Optional[Dict[str, Any]] = None
|
273 |
+
):
|
274 |
+
self.split_by_punct = split_by_punct
|
275 |
+
self.vocab_file = vocab_file
|
276 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
277 |
+
spm = sp.SentencePieceProcessor(**self.sp_model_kwargs)
|
278 |
+
if not os.path.exists(vocab_file):
|
279 |
+
raise FileNotFoundError(f"{vocab_file} does not exist!")
|
280 |
+
spm.load(vocab_file)
|
281 |
+
bpe_vocab_size = spm.GetPieceSize()
|
282 |
+
# Token map
|
283 |
+
# <unk> 0+1
|
284 |
+
# <s> 1+1
|
285 |
+
# </s> 2+1
|
286 |
+
self.vocab = {spm.IdToPiece(i): i for i in range(bpe_vocab_size)}
|
287 |
+
self.ids_to_tokens = [spm.IdToPiece(i) for i in range(bpe_vocab_size)]
|
288 |
+
# self.vocab['[PAD]'] = 0
|
289 |
+
# self.vocab['[CLS]'] = 1
|
290 |
+
# self.vocab['[SEP]'] = 2
|
291 |
+
# self.vocab['[UNK]'] = 3
|
292 |
+
|
293 |
+
self.spm = spm
|
294 |
+
self.special_tokens = special_tokens
|
295 |
+
|
296 |
+
def __getstate__(self):
|
297 |
+
state = self.__dict__.copy()
|
298 |
+
state["spm"] = None
|
299 |
+
return state
|
300 |
+
|
301 |
+
def __setstate__(self, d):
|
302 |
+
self.__dict__ = d
|
303 |
+
|
304 |
+
# for backward compatibility
|
305 |
+
if not hasattr(self, "sp_model_kwargs"):
|
306 |
+
self.sp_model_kwargs = {}
|
307 |
+
|
308 |
+
self.spm = sp.SentencePieceProcessor(**self.sp_model_kwargs)
|
309 |
+
self.spm.Load(self.vocab_file)
|
310 |
+
|
311 |
+
def tokenize(self, text):
|
312 |
+
return self._encode_as_pieces(text)
|
313 |
+
|
314 |
+
def convert_ids_to_tokens(self, ids):
|
315 |
+
tokens = []
|
316 |
+
for i in ids:
|
317 |
+
tokens.append(self.ids_to_tokens[i])
|
318 |
+
return tokens
|
319 |
+
|
320 |
+
def decode(self, tokens, start=-1, end=-1, raw_text=None):
|
321 |
+
if raw_text is None:
|
322 |
+
current_sub_tokens = []
|
323 |
+
out_string = ""
|
324 |
+
prev_is_special = False
|
325 |
+
for token in tokens:
|
326 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
327 |
+
if token in self.special_tokens:
|
328 |
+
if not prev_is_special:
|
329 |
+
out_string += " "
|
330 |
+
out_string += self.spm.decode_pieces(current_sub_tokens) + token
|
331 |
+
prev_is_special = True
|
332 |
+
current_sub_tokens = []
|
333 |
+
else:
|
334 |
+
current_sub_tokens.append(token)
|
335 |
+
prev_is_special = False
|
336 |
+
out_string += self.spm.decode_pieces(current_sub_tokens)
|
337 |
+
return out_string.strip()
|
338 |
+
else:
|
339 |
+
words = self.split_to_words(raw_text)
|
340 |
+
word_tokens = [self.tokenize(w) for w in words]
|
341 |
+
token2words = [0] * len(tokens)
|
342 |
+
tid = 0
|
343 |
+
for i, w in enumerate(word_tokens):
|
344 |
+
for k, t in enumerate(w):
|
345 |
+
token2words[tid] = i
|
346 |
+
tid += 1
|
347 |
+
word_start = token2words[start]
|
348 |
+
word_end = token2words[end] if end < len(tokens) else len(words)
|
349 |
+
text = "".join(words[word_start:word_end])
|
350 |
+
return text
|
351 |
+
|
352 |
+
# TODO add a deprecation cycle as this can have different behaviour from our API
|
353 |
+
def add_special_token(self, token):
|
354 |
+
if token not in self.special_tokens:
|
355 |
+
self.special_tokens.append(token)
|
356 |
+
if token not in self.vocab:
|
357 |
+
self.vocab[token] = len(self.vocab) - 1
|
358 |
+
self.ids_to_tokens.append(token)
|
359 |
+
return self.id(token)
|
360 |
+
|
361 |
+
def part_of_whole_word(self, token, is_bos=False):
|
362 |
+
logger.warning_once(
|
363 |
+
"The `DebertaTokenizer.part_of_whole_word` method is deprecated and will be removed in `transformers==4.35`"
|
364 |
+
)
|
365 |
+
if is_bos:
|
366 |
+
return True
|
367 |
+
if (
|
368 |
+
len(token) == 1
|
369 |
+
and (_is_whitespace(list(token)[0]) or _is_control(list(token)[0]) or _is_punctuation(list(token)[0]))
|
370 |
+
) or token in self.special_tokens:
|
371 |
+
return False
|
372 |
+
|
373 |
+
word_start = b"\xe2\x96\x81".decode("utf-8")
|
374 |
+
return not token.startswith(word_start)
|
375 |
+
|
376 |
+
def pad(self):
|
377 |
+
return "[PAD]"
|
378 |
+
|
379 |
+
def bos(self):
|
380 |
+
return "[CLS]"
|
381 |
+
|
382 |
+
def eos(self):
|
383 |
+
return "[SEP]"
|
384 |
+
|
385 |
+
def unk(self):
|
386 |
+
return "[UNK]"
|
387 |
+
|
388 |
+
def mask(self):
|
389 |
+
return "[MASK]"
|
390 |
+
|
391 |
+
def sym(self, id):
|
392 |
+
return self.ids_to_tokens[id]
|
393 |
+
|
394 |
+
def id(self, sym):
|
395 |
+
logger.warning_once(
|
396 |
+
"The `DebertaTokenizer.id` method is deprecated and will be removed in `transformers==4.35`"
|
397 |
+
)
|
398 |
+
return self.vocab[sym] if sym in self.vocab else 1
|
399 |
+
|
400 |
+
def _encode_as_pieces(self, text):
|
401 |
+
text = convert_to_unicode(text)
|
402 |
+
if self.split_by_punct:
|
403 |
+
words = self._run_split_on_punc(text)
|
404 |
+
pieces = [self.spm.encode(w, out_type=str) for w in words]
|
405 |
+
return [p for w in pieces for p in w]
|
406 |
+
else:
|
407 |
+
return self.spm.encode(text, out_type=str)
|
408 |
+
|
409 |
+
def split_to_words(self, text):
|
410 |
+
pieces = self._encode_as_pieces(text)
|
411 |
+
word_start = b"\xe2\x96\x81".decode("utf-8")
|
412 |
+
words = []
|
413 |
+
offset = 0
|
414 |
+
prev_end = 0
|
415 |
+
for i, p in enumerate(pieces):
|
416 |
+
if p.startswith(word_start):
|
417 |
+
if offset > prev_end:
|
418 |
+
words.append(text[prev_end:offset])
|
419 |
+
prev_end = offset
|
420 |
+
w = p.replace(word_start, "")
|
421 |
+
else:
|
422 |
+
w = p
|
423 |
+
try:
|
424 |
+
s = text.index(w, offset)
|
425 |
+
pn = ""
|
426 |
+
k = i + 1
|
427 |
+
while k < len(pieces):
|
428 |
+
pn = pieces[k].replace(word_start, "")
|
429 |
+
if len(pn) > 0:
|
430 |
+
break
|
431 |
+
k += 1
|
432 |
+
|
433 |
+
if len(pn) > 0 and pn in text[offset:s]:
|
434 |
+
offset = offset + 1
|
435 |
+
else:
|
436 |
+
offset = s + len(w)
|
437 |
+
except Exception:
|
438 |
+
offset = offset + 1
|
439 |
+
|
440 |
+
if prev_end < offset:
|
441 |
+
words.append(text[prev_end:offset])
|
442 |
+
|
443 |
+
return words
|
444 |
+
|
445 |
+
def _run_split_on_punc(self, text):
|
446 |
+
"""Splits punctuation on a piece of text."""
|
447 |
+
chars = list(text)
|
448 |
+
i = 0
|
449 |
+
start_new_word = True
|
450 |
+
output = []
|
451 |
+
while i < len(chars):
|
452 |
+
char = chars[i]
|
453 |
+
if _is_punctuation(char):
|
454 |
+
output.append([char])
|
455 |
+
start_new_word = True
|
456 |
+
else:
|
457 |
+
if start_new_word:
|
458 |
+
output.append([])
|
459 |
+
start_new_word = False
|
460 |
+
output[-1].append(char)
|
461 |
+
i += 1
|
462 |
+
|
463 |
+
return ["".join(x) for x in output]
|
464 |
+
|
465 |
+
def save_pretrained(self, path: str, filename_prefix: str = None):
|
466 |
+
filename = VOCAB_FILES_NAMES[list(VOCAB_FILES_NAMES.keys())[0]]
|
467 |
+
if filename_prefix is not None:
|
468 |
+
filename = filename_prefix + "-" + filename
|
469 |
+
full_path = os.path.join(path, filename)
|
470 |
+
with open(full_path, "wb") as fs:
|
471 |
+
fs.write(self.spm.serialized_model_proto())
|
472 |
+
return (full_path,)
|
473 |
+
|
474 |
+
|
475 |
+
def _is_whitespace(char):
|
476 |
+
"""Checks whether `chars` is a whitespace character."""
|
477 |
+
# \t, \n, and \r are technically control characters but we treat them
|
478 |
+
# as whitespace since they are generally considered as such.
|
479 |
+
if char == " " or char == "\t" or char == "\n" or char == "\r":
|
480 |
+
return True
|
481 |
+
cat = unicodedata.category(char)
|
482 |
+
if cat == "Zs":
|
483 |
+
return True
|
484 |
+
return False
|
485 |
+
|
486 |
+
|
487 |
+
def _is_control(char):
|
488 |
+
"""Checks whether `chars` is a control character."""
|
489 |
+
# These are technically control characters but we count them as whitespace
|
490 |
+
# characters.
|
491 |
+
if char == "\t" or char == "\n" or char == "\r":
|
492 |
+
return False
|
493 |
+
cat = unicodedata.category(char)
|
494 |
+
if cat.startswith("C"):
|
495 |
+
return True
|
496 |
+
return False
|
497 |
+
|
498 |
+
|
499 |
+
def _is_punctuation(char):
|
500 |
+
"""Checks whether `chars` is a punctuation character."""
|
501 |
+
cp = ord(char)
|
502 |
+
# We treat all non-letter/number ASCII as punctuation.
|
503 |
+
# Characters such as "^", "$", and "`" are not in the Unicode
|
504 |
+
# Punctuation class but we treat them as punctuation anyways, for
|
505 |
+
# consistency.
|
506 |
+
if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
|
507 |
+
return True
|
508 |
+
cat = unicodedata.category(char)
|
509 |
+
if cat.startswith("P"):
|
510 |
+
return True
|
511 |
+
return False
|
512 |
+
|
513 |
+
|
514 |
+
def convert_to_unicode(text):
|
515 |
+
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
|
516 |
+
if isinstance(text, str):
|
517 |
+
return text
|
518 |
+
elif isinstance(text, bytes):
|
519 |
+
return text.decode("utf-8", "ignore")
|
520 |
+
else:
|
521 |
+
raise ValueError(f"Unsupported string type: {type(text)}")
|
llmeval-env/lib/python3.10/site-packages/transformers/models/deberta_v2/tokenization_deberta_v2_fast.py
ADDED
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2020 Microsoft 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 class for model DeBERTa."""
|
16 |
+
|
17 |
+
import os
|
18 |
+
from shutil import copyfile
|
19 |
+
from typing import Optional, Tuple
|
20 |
+
|
21 |
+
from ...file_utils import is_sentencepiece_available
|
22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
23 |
+
from ...utils import logging
|
24 |
+
|
25 |
+
|
26 |
+
if is_sentencepiece_available():
|
27 |
+
from .tokenization_deberta_v2 import DebertaV2Tokenizer
|
28 |
+
else:
|
29 |
+
DebertaV2Tokenizer = None
|
30 |
+
|
31 |
+
logger = logging.get_logger(__name__)
|
32 |
+
|
33 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spm.model", "tokenizer_file": "tokenizer.json"}
|
34 |
+
|
35 |
+
|
36 |
+
class DebertaV2TokenizerFast(PreTrainedTokenizerFast):
|
37 |
+
r"""
|
38 |
+
Constructs a DeBERTa-v2 fast tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
39 |
+
|
40 |
+
Args:
|
41 |
+
vocab_file (`str`):
|
42 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
43 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
44 |
+
do_lower_case (`bool`, *optional*, defaults to `False`):
|
45 |
+
Whether or not to lowercase the input when tokenizing.
|
46 |
+
bos_token (`string`, *optional*, defaults to `"[CLS]"`):
|
47 |
+
The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
|
48 |
+
When building a sequence using special tokens, this is not the token that is used for the beginning of
|
49 |
+
sequence. The token used is the `cls_token`.
|
50 |
+
eos_token (`string`, *optional*, defaults to `"[SEP]"`):
|
51 |
+
The end of sequence token. When building a sequence using special tokens, this is not the token that is
|
52 |
+
used for the end of sequence. The token used is the `sep_token`.
|
53 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
54 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
55 |
+
token instead.
|
56 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
57 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
58 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
59 |
+
token of a sequence built with special tokens.
|
60 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
61 |
+
The token used for padding, for example when batching sequences of different lengths.
|
62 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
63 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
64 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
65 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
66 |
+
The token used for masking values. This is the token used when training this model with masked language
|
67 |
+
modeling. This is the token which the model will try to predict.
|
68 |
+
sp_model_kwargs (`dict`, *optional*):
|
69 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
70 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
71 |
+
to set:
|
72 |
+
|
73 |
+
- `enable_sampling`: Enable subword regularization.
|
74 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
75 |
+
|
76 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
77 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
78 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
79 |
+
using forward-filtering-and-backward-sampling algorithm.
|
80 |
+
|
81 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
82 |
+
BPE-dropout.
|
83 |
+
"""
|
84 |
+
|
85 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
86 |
+
slow_tokenizer_class = DebertaV2Tokenizer
|
87 |
+
|
88 |
+
def __init__(
|
89 |
+
self,
|
90 |
+
vocab_file=None,
|
91 |
+
tokenizer_file=None,
|
92 |
+
do_lower_case=False,
|
93 |
+
split_by_punct=False,
|
94 |
+
bos_token="[CLS]",
|
95 |
+
eos_token="[SEP]",
|
96 |
+
unk_token="[UNK]",
|
97 |
+
sep_token="[SEP]",
|
98 |
+
pad_token="[PAD]",
|
99 |
+
cls_token="[CLS]",
|
100 |
+
mask_token="[MASK]",
|
101 |
+
**kwargs,
|
102 |
+
) -> None:
|
103 |
+
super().__init__(
|
104 |
+
vocab_file,
|
105 |
+
tokenizer_file=tokenizer_file,
|
106 |
+
do_lower_case=do_lower_case,
|
107 |
+
bos_token=bos_token,
|
108 |
+
eos_token=eos_token,
|
109 |
+
unk_token=unk_token,
|
110 |
+
sep_token=sep_token,
|
111 |
+
pad_token=pad_token,
|
112 |
+
cls_token=cls_token,
|
113 |
+
mask_token=mask_token,
|
114 |
+
split_by_punct=split_by_punct,
|
115 |
+
**kwargs,
|
116 |
+
)
|
117 |
+
|
118 |
+
self.do_lower_case = do_lower_case
|
119 |
+
self.split_by_punct = split_by_punct
|
120 |
+
self.vocab_file = vocab_file
|
121 |
+
|
122 |
+
@property
|
123 |
+
def can_save_slow_tokenizer(self) -> bool:
|
124 |
+
return os.path.isfile(self.vocab_file) if self.vocab_file else False
|
125 |
+
|
126 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
127 |
+
"""
|
128 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
129 |
+
adding special tokens. A DeBERTa sequence has the following format:
|
130 |
+
|
131 |
+
- single sequence: [CLS] X [SEP]
|
132 |
+
- pair of sequences: [CLS] A [SEP] B [SEP]
|
133 |
+
|
134 |
+
Args:
|
135 |
+
token_ids_0 (`List[int]`):
|
136 |
+
List of IDs to which the special tokens will be added.
|
137 |
+
token_ids_1 (`List[int]`, *optional*):
|
138 |
+
Optional second list of IDs for sequence pairs.
|
139 |
+
|
140 |
+
Returns:
|
141 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
142 |
+
"""
|
143 |
+
|
144 |
+
if token_ids_1 is None:
|
145 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
146 |
+
cls = [self.cls_token_id]
|
147 |
+
sep = [self.sep_token_id]
|
148 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
149 |
+
|
150 |
+
def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
|
151 |
+
"""
|
152 |
+
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
|
153 |
+
special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
|
154 |
+
|
155 |
+
Args:
|
156 |
+
token_ids_0 (`List[int]`):
|
157 |
+
List of IDs.
|
158 |
+
token_ids_1 (`List[int]`, *optional*):
|
159 |
+
Optional second list of IDs for sequence pairs.
|
160 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
161 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
162 |
+
|
163 |
+
Returns:
|
164 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
165 |
+
"""
|
166 |
+
|
167 |
+
if already_has_special_tokens:
|
168 |
+
return super().get_special_tokens_mask(
|
169 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
170 |
+
)
|
171 |
+
|
172 |
+
if token_ids_1 is not None:
|
173 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
174 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
175 |
+
|
176 |
+
def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
|
177 |
+
"""
|
178 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A DeBERTa
|
179 |
+
sequence 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 |
+
if not self.can_save_slow_tokenizer:
|
205 |
+
raise ValueError(
|
206 |
+
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
|
207 |
+
"tokenizer."
|
208 |
+
)
|
209 |
+
|
210 |
+
if not os.path.isdir(save_directory):
|
211 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
212 |
+
return
|
213 |
+
out_vocab_file = os.path.join(
|
214 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
215 |
+
)
|
216 |
+
|
217 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
|
218 |
+
copyfile(self.vocab_file, out_vocab_file)
|
219 |
+
|
220 |
+
return (out_vocab_file,)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/persimmon/__pycache__/configuration_persimmon.cpython-310.pyc
ADDED
Binary file (6.51 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/persimmon/__pycache__/convert_persimmon_weights_to_hf.cpython-310.pyc
ADDED
Binary file (2.76 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/persimmon/__pycache__/modeling_persimmon.cpython-310.pyc
ADDED
Binary file (32.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__init__.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
from typing import TYPE_CHECKING
|
15 |
+
|
16 |
+
from ...utils import (
|
17 |
+
OptionalDependencyNotAvailable,
|
18 |
+
_LazyModule,
|
19 |
+
is_essentia_available,
|
20 |
+
is_librosa_available,
|
21 |
+
is_pretty_midi_available,
|
22 |
+
is_scipy_available,
|
23 |
+
is_torch_available,
|
24 |
+
)
|
25 |
+
|
26 |
+
|
27 |
+
_import_structure = {
|
28 |
+
"configuration_pop2piano": ["POP2PIANO_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pop2PianoConfig"],
|
29 |
+
}
|
30 |
+
|
31 |
+
try:
|
32 |
+
if not is_torch_available():
|
33 |
+
raise OptionalDependencyNotAvailable()
|
34 |
+
except OptionalDependencyNotAvailable:
|
35 |
+
pass
|
36 |
+
else:
|
37 |
+
_import_structure["modeling_pop2piano"] = [
|
38 |
+
"POP2PIANO_PRETRAINED_MODEL_ARCHIVE_LIST",
|
39 |
+
"Pop2PianoForConditionalGeneration",
|
40 |
+
"Pop2PianoPreTrainedModel",
|
41 |
+
]
|
42 |
+
|
43 |
+
try:
|
44 |
+
if not (is_librosa_available() and is_essentia_available() and is_scipy_available() and is_torch_available()):
|
45 |
+
raise OptionalDependencyNotAvailable()
|
46 |
+
except OptionalDependencyNotAvailable:
|
47 |
+
pass
|
48 |
+
else:
|
49 |
+
_import_structure["feature_extraction_pop2piano"] = ["Pop2PianoFeatureExtractor"]
|
50 |
+
|
51 |
+
try:
|
52 |
+
if not (is_pretty_midi_available() and is_torch_available()):
|
53 |
+
raise OptionalDependencyNotAvailable()
|
54 |
+
except OptionalDependencyNotAvailable:
|
55 |
+
pass
|
56 |
+
else:
|
57 |
+
_import_structure["tokenization_pop2piano"] = ["Pop2PianoTokenizer"]
|
58 |
+
|
59 |
+
try:
|
60 |
+
if not (
|
61 |
+
is_pretty_midi_available()
|
62 |
+
and is_torch_available()
|
63 |
+
and is_librosa_available()
|
64 |
+
and is_essentia_available()
|
65 |
+
and is_scipy_available()
|
66 |
+
):
|
67 |
+
raise OptionalDependencyNotAvailable()
|
68 |
+
except OptionalDependencyNotAvailable:
|
69 |
+
pass
|
70 |
+
else:
|
71 |
+
_import_structure["processing_pop2piano"] = ["Pop2PianoProcessor"]
|
72 |
+
|
73 |
+
|
74 |
+
if TYPE_CHECKING:
|
75 |
+
from .configuration_pop2piano import POP2PIANO_PRETRAINED_CONFIG_ARCHIVE_MAP, Pop2PianoConfig
|
76 |
+
|
77 |
+
try:
|
78 |
+
if not is_torch_available():
|
79 |
+
raise OptionalDependencyNotAvailable()
|
80 |
+
except OptionalDependencyNotAvailable:
|
81 |
+
pass
|
82 |
+
else:
|
83 |
+
from .modeling_pop2piano import (
|
84 |
+
POP2PIANO_PRETRAINED_MODEL_ARCHIVE_LIST,
|
85 |
+
Pop2PianoForConditionalGeneration,
|
86 |
+
Pop2PianoPreTrainedModel,
|
87 |
+
)
|
88 |
+
|
89 |
+
try:
|
90 |
+
if not (is_librosa_available() and is_essentia_available() and is_scipy_available() and is_torch_available()):
|
91 |
+
raise OptionalDependencyNotAvailable()
|
92 |
+
except OptionalDependencyNotAvailable:
|
93 |
+
pass
|
94 |
+
else:
|
95 |
+
from .feature_extraction_pop2piano import Pop2PianoFeatureExtractor
|
96 |
+
|
97 |
+
try:
|
98 |
+
if not (is_pretty_midi_available() and is_torch_available()):
|
99 |
+
raise OptionalDependencyNotAvailable()
|
100 |
+
except OptionalDependencyNotAvailable:
|
101 |
+
pass
|
102 |
+
else:
|
103 |
+
from .tokenization_pop2piano import Pop2PianoTokenizer
|
104 |
+
|
105 |
+
try:
|
106 |
+
if not (
|
107 |
+
is_pretty_midi_available()
|
108 |
+
and is_torch_available()
|
109 |
+
and is_librosa_available()
|
110 |
+
and is_essentia_available()
|
111 |
+
and is_scipy_available()
|
112 |
+
):
|
113 |
+
raise OptionalDependencyNotAvailable()
|
114 |
+
except OptionalDependencyNotAvailable:
|
115 |
+
pass
|
116 |
+
else:
|
117 |
+
from .processing_pop2piano import Pop2PianoProcessor
|
118 |
+
|
119 |
+
else:
|
120 |
+
import sys
|
121 |
+
|
122 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.78 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/configuration_pop2piano.cpython-310.pyc
ADDED
Binary file (5.14 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/convert_pop2piano_weights_to_hf.cpython-310.pyc
ADDED
Binary file (4.23 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/feature_extraction_pop2piano.cpython-310.pyc
ADDED
Binary file (14.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/modeling_pop2piano.cpython-310.pyc
ADDED
Binary file (40.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/transformers/models/pop2piano/__pycache__/processing_pop2piano.cpython-310.pyc
ADDED
Binary file (4.59 kB). View file
|
|