Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- lib/python3.12/site-packages/transformers/models/altclip/__init__.py +28 -0
- lib/python3.12/site-packages/transformers/models/altclip/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/altclip/__pycache__/configuration_altclip.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/altclip/__pycache__/modeling_altclip.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/altclip/__pycache__/processing_altclip.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/altclip/configuration_altclip.py +384 -0
- lib/python3.12/site-packages/transformers/models/altclip/modeling_altclip.py +1758 -0
- lib/python3.12/site-packages/transformers/models/altclip/processing_altclip.py +148 -0
- lib/python3.12/site-packages/transformers/models/beit/__init__.py +30 -0
- lib/python3.12/site-packages/transformers/models/beit/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/beit/__pycache__/feature_extraction_beit.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_flax_beit.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/beit/configuration_beit.py +229 -0
- lib/python3.12/site-packages/transformers/models/beit/feature_extraction_beit.py +36 -0
- lib/python3.12/site-packages/transformers/models/beit/image_processing_beit.py +515 -0
- lib/python3.12/site-packages/transformers/models/beit/modeling_beit.py +1652 -0
- lib/python3.12/site-packages/transformers/models/beit/modeling_flax_beit.py +956 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/__init__.py +28 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/configuration_bert_generation.py +127 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/modeling_bert_generation.py +1011 -0
- lib/python3.12/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py +175 -0
- lib/python3.12/site-packages/transformers/models/blip_2/__init__.py +28 -0
- lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/blip_2/configuration_blip_2.py +345 -0
- lib/python3.12/site-packages/transformers/models/blip_2/modeling_blip_2.py +0 -0
- lib/python3.12/site-packages/transformers/models/blip_2/processing_blip_2.py +193 -0
- lib/python3.12/site-packages/transformers/models/cvt/__init__.py +28 -0
- lib/python3.12/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/cvt/configuration_cvt.py +146 -0
- lib/python3.12/site-packages/transformers/models/cvt/modeling_cvt.py +725 -0
- lib/python3.12/site-packages/transformers/models/cvt/modeling_tf_cvt.py +1096 -0
- lib/python3.12/site-packages/transformers/models/donut/__init__.py +30 -0
- lib/python3.12/site-packages/transformers/models/donut/__pycache__/__init__.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/donut/__pycache__/configuration_donut_swin.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/donut/__pycache__/feature_extraction_donut.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/donut/__pycache__/modeling_donut_swin.cpython-312.pyc +0 -0
- lib/python3.12/site-packages/transformers/models/donut/__pycache__/processing_donut.cpython-312.pyc +0 -0
lib/python3.12/site-packages/transformers/models/altclip/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_altclip import *
|
| 22 |
+
from .modeling_altclip import *
|
| 23 |
+
from .processing_altclip import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/altclip/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (703 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/altclip/__pycache__/configuration_altclip.cpython-312.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/altclip/__pycache__/modeling_altclip.cpython-312.pyc
ADDED
|
Binary file (85.9 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/altclip/__pycache__/processing_altclip.cpython-312.pyc
ADDED
|
Binary file (7.3 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/altclip/configuration_altclip.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""AltCLIP model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class AltCLIPTextConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`AltCLIPTextModel`]. It is used to instantiate a
|
| 27 |
+
AltCLIP text model according to the specified arguments, defining the model architecture. Instantiating a
|
| 28 |
+
configuration with the defaults will yield a similar configuration to that of the AltCLIP
|
| 29 |
+
[BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 250002):
|
| 37 |
+
Vocabulary size of the AltCLIP model. Defines the number of different tokens that can be represented by the
|
| 38 |
+
`inputs_ids` passed when calling [`AltCLIPTextModel`].
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
| 42 |
+
Number of hidden layers in the Transformer encoder.
|
| 43 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 44 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
| 46 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 47 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 49 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 50 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 51 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 52 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
max_position_embeddings (`int`, *optional*, defaults to 514):
|
| 55 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 56 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 57 |
+
type_vocab_size (`int`, *optional*, defaults to 1):
|
| 58 |
+
The vocabulary size of the `token_type_ids` passed when calling [`AltCLIPTextModel`]
|
| 59 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 60 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 61 |
+
initializer_factor (`float`, *optional*, defaults to 0.02):
|
| 62 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 63 |
+
testing).
|
| 64 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 65 |
+
The epsilon used by the layer normalization layers.
|
| 66 |
+
pad_token_id (`int`, *optional*, defaults to 1): The id of the *padding* token.
|
| 67 |
+
bos_token_id (`int`, *optional*, defaults to 0): The id of the *beginning-of-sequence* token.
|
| 68 |
+
eos_token_id (`Union[int, List[int]]`, *optional*, defaults to 2):
|
| 69 |
+
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
|
| 70 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 71 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 72 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 73 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 74 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 75 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 76 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 78 |
+
relevant if `config.is_decoder=True`.
|
| 79 |
+
project_dim (`int`, *optional*, defaults to 768):
|
| 80 |
+
The dimensions of the teacher model before the mapping layer.
|
| 81 |
+
|
| 82 |
+
Examples:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import AltCLIPTextModel, AltCLIPTextConfig
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a AltCLIPTextConfig with BAAI/AltCLIP style configuration
|
| 88 |
+
>>> configuration = AltCLIPTextConfig()
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a AltCLIPTextModel (with random weights) from the BAAI/AltCLIP style configuration
|
| 91 |
+
>>> model = AltCLIPTextModel(configuration)
|
| 92 |
+
|
| 93 |
+
>>> # Accessing the model configuration
|
| 94 |
+
>>> configuration = model.config
|
| 95 |
+
```"""
|
| 96 |
+
|
| 97 |
+
model_type = "altclip_text_model"
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_size=250002,
|
| 102 |
+
hidden_size=1024,
|
| 103 |
+
num_hidden_layers=24,
|
| 104 |
+
num_attention_heads=16,
|
| 105 |
+
intermediate_size=4096,
|
| 106 |
+
hidden_act="gelu",
|
| 107 |
+
hidden_dropout_prob=0.1,
|
| 108 |
+
attention_probs_dropout_prob=0.1,
|
| 109 |
+
max_position_embeddings=514,
|
| 110 |
+
type_vocab_size=1,
|
| 111 |
+
initializer_range=0.02,
|
| 112 |
+
initializer_factor=0.02,
|
| 113 |
+
layer_norm_eps=1e-05,
|
| 114 |
+
pad_token_id=1,
|
| 115 |
+
bos_token_id=0,
|
| 116 |
+
eos_token_id=2,
|
| 117 |
+
position_embedding_type="absolute",
|
| 118 |
+
use_cache=True,
|
| 119 |
+
project_dim=768,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 123 |
+
|
| 124 |
+
self.vocab_size = vocab_size
|
| 125 |
+
self.hidden_size = hidden_size
|
| 126 |
+
self.num_hidden_layers = num_hidden_layers
|
| 127 |
+
self.num_attention_heads = num_attention_heads
|
| 128 |
+
self.hidden_act = hidden_act
|
| 129 |
+
self.intermediate_size = intermediate_size
|
| 130 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 131 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 132 |
+
self.max_position_embeddings = max_position_embeddings
|
| 133 |
+
self.type_vocab_size = type_vocab_size
|
| 134 |
+
self.initializer_range = initializer_range
|
| 135 |
+
self.initializer_factor = initializer_factor
|
| 136 |
+
self.layer_norm_eps = layer_norm_eps
|
| 137 |
+
self.position_embedding_type = position_embedding_type
|
| 138 |
+
self.use_cache = use_cache
|
| 139 |
+
self.project_dim = project_dim
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class AltCLIPVisionConfig(PretrainedConfig):
|
| 143 |
+
r"""
|
| 144 |
+
This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
|
| 145 |
+
AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 146 |
+
with the defaults will yield a similar configuration to that of the AltCLIP
|
| 147 |
+
[BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
|
| 148 |
+
|
| 149 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 150 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 155 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 156 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 157 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 158 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 159 |
+
Dimensionality of text and vision projection layers.
|
| 160 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 161 |
+
Number of hidden layers in the Transformer encoder.
|
| 162 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 163 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 164 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 165 |
+
The number of input channels.
|
| 166 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 167 |
+
The size (resolution) of each image.
|
| 168 |
+
patch_size (`int`, *optional*, defaults to 32):
|
| 169 |
+
The size (resolution) of each patch.
|
| 170 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
|
| 171 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 172 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
|
| 173 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
|
| 174 |
+
The epsilon used by the layer normalization layers.
|
| 175 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 176 |
+
The dropout ratio for the attention probabilities.
|
| 177 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 178 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 179 |
+
initializer_factor (`float`, *optional*, defaults to 1.0):
|
| 180 |
+
A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
|
| 181 |
+
testing).
|
| 182 |
+
|
| 183 |
+
Example:
|
| 184 |
+
|
| 185 |
+
```python
|
| 186 |
+
>>> from transformers import AltCLIPVisionConfig, AltCLIPVisionModel
|
| 187 |
+
|
| 188 |
+
>>> # Initializing a AltCLIPVisionConfig with BAAI/AltCLIP style configuration
|
| 189 |
+
>>> configuration = AltCLIPVisionConfig()
|
| 190 |
+
|
| 191 |
+
>>> # Initializing a AltCLIPVisionModel (with random weights) from the BAAI/AltCLIP style configuration
|
| 192 |
+
>>> model = AltCLIPVisionModel(configuration)
|
| 193 |
+
|
| 194 |
+
>>> # Accessing the model configuration
|
| 195 |
+
>>> configuration = model.config
|
| 196 |
+
```"""
|
| 197 |
+
|
| 198 |
+
model_type = "altclip_vision_model"
|
| 199 |
+
base_config_key = "vision_config"
|
| 200 |
+
|
| 201 |
+
def __init__(
|
| 202 |
+
self,
|
| 203 |
+
hidden_size=768,
|
| 204 |
+
intermediate_size=3072,
|
| 205 |
+
projection_dim=512,
|
| 206 |
+
num_hidden_layers=12,
|
| 207 |
+
num_attention_heads=12,
|
| 208 |
+
num_channels=3,
|
| 209 |
+
image_size=224,
|
| 210 |
+
patch_size=32,
|
| 211 |
+
hidden_act="quick_gelu",
|
| 212 |
+
layer_norm_eps=1e-5,
|
| 213 |
+
attention_dropout=0.0,
|
| 214 |
+
initializer_range=0.02,
|
| 215 |
+
initializer_factor=1.0,
|
| 216 |
+
**kwargs,
|
| 217 |
+
):
|
| 218 |
+
super().__init__(**kwargs)
|
| 219 |
+
|
| 220 |
+
self.hidden_size = hidden_size
|
| 221 |
+
self.intermediate_size = intermediate_size
|
| 222 |
+
self.projection_dim = projection_dim
|
| 223 |
+
self.num_hidden_layers = num_hidden_layers
|
| 224 |
+
self.num_attention_heads = num_attention_heads
|
| 225 |
+
self.num_channels = num_channels
|
| 226 |
+
self.patch_size = patch_size
|
| 227 |
+
self.image_size = image_size
|
| 228 |
+
self.initializer_range = initializer_range
|
| 229 |
+
self.initializer_factor = initializer_factor
|
| 230 |
+
self.attention_dropout = attention_dropout
|
| 231 |
+
self.layer_norm_eps = layer_norm_eps
|
| 232 |
+
self.hidden_act = hidden_act
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class AltCLIPConfig(PretrainedConfig):
|
| 236 |
+
r"""
|
| 237 |
+
This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
|
| 238 |
+
AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 239 |
+
with the defaults will yield a similar configuration to that of the AltCLIP
|
| 240 |
+
[BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
|
| 241 |
+
|
| 242 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 243 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 244 |
+
|
| 245 |
+
Args:
|
| 246 |
+
text_config (`dict`, *optional*):
|
| 247 |
+
Dictionary of configuration options used to initialize [`AltCLIPTextConfig`].
|
| 248 |
+
vision_config (`dict`, *optional*):
|
| 249 |
+
Dictionary of configuration options used to initialize [`AltCLIPVisionConfig`].
|
| 250 |
+
projection_dim (`int`, *optional*, defaults to 768):
|
| 251 |
+
Dimensionality of text and vision projection layers.
|
| 252 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
| 253 |
+
The initial value of the *logit_scale* parameter. Default is used as per the original CLIP implementation.
|
| 254 |
+
kwargs (*optional*):
|
| 255 |
+
Dictionary of keyword arguments.
|
| 256 |
+
|
| 257 |
+
Example:
|
| 258 |
+
|
| 259 |
+
```python
|
| 260 |
+
>>> from transformers import AltCLIPConfig, AltCLIPModel
|
| 261 |
+
|
| 262 |
+
>>> # Initializing a AltCLIPConfig with BAAI/AltCLIP style configuration
|
| 263 |
+
>>> configuration = AltCLIPConfig()
|
| 264 |
+
|
| 265 |
+
>>> # Initializing a AltCLIPModel (with random weights) from the BAAI/AltCLIP style configuration
|
| 266 |
+
>>> model = AltCLIPModel(configuration)
|
| 267 |
+
|
| 268 |
+
>>> # Accessing the model configuration
|
| 269 |
+
>>> configuration = model.config
|
| 270 |
+
|
| 271 |
+
>>> # We can also initialize a AltCLIPConfig from a AltCLIPTextConfig and a AltCLIPVisionConfig
|
| 272 |
+
|
| 273 |
+
>>> # Initializing a AltCLIPText and AltCLIPVision configuration
|
| 274 |
+
>>> config_text = AltCLIPTextConfig()
|
| 275 |
+
>>> config_vision = AltCLIPVisionConfig()
|
| 276 |
+
|
| 277 |
+
>>> config = AltCLIPConfig.from_text_vision_configs(config_text, config_vision)
|
| 278 |
+
```"""
|
| 279 |
+
|
| 280 |
+
model_type = "altclip"
|
| 281 |
+
sub_configs = {"text_config": AltCLIPTextConfig, "vision_config": AltCLIPVisionConfig}
|
| 282 |
+
|
| 283 |
+
def __init__(
|
| 284 |
+
self, text_config=None, vision_config=None, projection_dim=768, logit_scale_init_value=2.6592, **kwargs
|
| 285 |
+
):
|
| 286 |
+
# If `_config_dict` exist, we use them for the backward compatibility.
|
| 287 |
+
# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
|
| 288 |
+
# of confusion!).
|
| 289 |
+
text_config_dict = kwargs.pop("text_config_dict", None)
|
| 290 |
+
vision_config_dict = kwargs.pop("vision_config_dict", None)
|
| 291 |
+
|
| 292 |
+
super().__init__(**kwargs)
|
| 293 |
+
|
| 294 |
+
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
|
| 295 |
+
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
|
| 296 |
+
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
|
| 297 |
+
if text_config_dict is not None:
|
| 298 |
+
if text_config is None:
|
| 299 |
+
text_config = {}
|
| 300 |
+
|
| 301 |
+
# This is the complete result when using `text_config_dict`.
|
| 302 |
+
_text_config_dict = AltCLIPTextConfig(**text_config_dict).to_dict()
|
| 303 |
+
|
| 304 |
+
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
|
| 305 |
+
for key, value in _text_config_dict.items():
|
| 306 |
+
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
|
| 307 |
+
# If specified in `text_config_dict`
|
| 308 |
+
if key in text_config_dict:
|
| 309 |
+
message = (
|
| 310 |
+
f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
|
| 311 |
+
f'The value `text_config_dict["{key}"]` will be used instead.'
|
| 312 |
+
)
|
| 313 |
+
# If inferred from default argument values (just to be super careful)
|
| 314 |
+
else:
|
| 315 |
+
message = (
|
| 316 |
+
f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
|
| 317 |
+
f'value `text_config["{key}"]` will be overridden.'
|
| 318 |
+
)
|
| 319 |
+
logger.info(message)
|
| 320 |
+
|
| 321 |
+
# Update all values in `text_config` with the ones in `_text_config_dict`.
|
| 322 |
+
text_config.update(_text_config_dict)
|
| 323 |
+
|
| 324 |
+
if vision_config_dict is not None:
|
| 325 |
+
if vision_config is None:
|
| 326 |
+
vision_config = {}
|
| 327 |
+
|
| 328 |
+
# This is the complete result when using `vision_config_dict`.
|
| 329 |
+
_vision_config_dict = AltCLIPVisionConfig(**vision_config_dict).to_dict()
|
| 330 |
+
# convert keys to string instead of integer
|
| 331 |
+
if "id2label" in _vision_config_dict:
|
| 332 |
+
_vision_config_dict["id2label"] = {
|
| 333 |
+
str(key): value for key, value in _vision_config_dict["id2label"].items()
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
|
| 337 |
+
for key, value in _vision_config_dict.items():
|
| 338 |
+
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
|
| 339 |
+
# If specified in `vision_config_dict`
|
| 340 |
+
if key in vision_config_dict:
|
| 341 |
+
message = (
|
| 342 |
+
f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
|
| 343 |
+
f'values. The value `vision_config_dict["{key}"]` will be used instead.'
|
| 344 |
+
)
|
| 345 |
+
# If inferred from default argument values (just to be super careful)
|
| 346 |
+
else:
|
| 347 |
+
message = (
|
| 348 |
+
f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
|
| 349 |
+
f'The value `vision_config["{key}"]` will be overridden.'
|
| 350 |
+
)
|
| 351 |
+
logger.info(message)
|
| 352 |
+
|
| 353 |
+
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
|
| 354 |
+
vision_config.update(_vision_config_dict)
|
| 355 |
+
|
| 356 |
+
if text_config is None:
|
| 357 |
+
text_config = {}
|
| 358 |
+
logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.")
|
| 359 |
+
|
| 360 |
+
if vision_config is None:
|
| 361 |
+
vision_config = {}
|
| 362 |
+
logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.")
|
| 363 |
+
|
| 364 |
+
self.text_config = AltCLIPTextConfig(**text_config)
|
| 365 |
+
self.vision_config = AltCLIPVisionConfig(**vision_config)
|
| 366 |
+
|
| 367 |
+
self.projection_dim = projection_dim
|
| 368 |
+
self.logit_scale_init_value = logit_scale_init_value
|
| 369 |
+
self.initializer_factor = 1.0
|
| 370 |
+
|
| 371 |
+
@classmethod
|
| 372 |
+
def from_text_vision_configs(cls, text_config: AltCLIPTextConfig, vision_config: AltCLIPVisionConfig, **kwargs):
|
| 373 |
+
r"""
|
| 374 |
+
Instantiate a [`AltCLIPConfig`] (or a derived class) from altclip text model configuration and altclip vision
|
| 375 |
+
model configuration.
|
| 376 |
+
|
| 377 |
+
Returns:
|
| 378 |
+
[`AltCLIPConfig`]: An instance of a configuration object
|
| 379 |
+
"""
|
| 380 |
+
|
| 381 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
__all__ = ["AltCLIPTextConfig", "AltCLIPVisionConfig", "AltCLIPConfig"]
|
lib/python3.12/site-packages/transformers/models/altclip/modeling_altclip.py
ADDED
|
@@ -0,0 +1,1758 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The BAAI Teams Authors and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch AltCLIP model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...modeling_outputs import (
|
| 27 |
+
BaseModelOutput,
|
| 28 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 29 |
+
BaseModelOutputWithPooling,
|
| 30 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 31 |
+
BaseModelOutputWithPoolingAndProjection,
|
| 32 |
+
)
|
| 33 |
+
from ...modeling_utils import PreTrainedModel
|
| 34 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 35 |
+
from ...utils import ModelOutput, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, torch_int
|
| 36 |
+
from .configuration_altclip import AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
_CHECKPOINT_FOR_DOC = "BAAI/AltCLIP"
|
| 42 |
+
_CONFIG_FOR_DOC = "AltCLIPConfig"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
ALTCLIP_START_DOCSTRING = r"""
|
| 46 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 47 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 48 |
+
etc.)
|
| 49 |
+
|
| 50 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 51 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 52 |
+
and behavior.
|
| 53 |
+
|
| 54 |
+
Parameters:
|
| 55 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
| 56 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 57 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
ALTCLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 61 |
+
Args:
|
| 62 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 63 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 64 |
+
it.
|
| 65 |
+
|
| 66 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 67 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 68 |
+
|
| 69 |
+
[What are input IDs?](../glossary#input-ids)
|
| 70 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 71 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 72 |
+
|
| 73 |
+
- 1 for tokens that are **not masked**,
|
| 74 |
+
- 0 for tokens that are **masked**.
|
| 75 |
+
|
| 76 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 77 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 78 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 79 |
+
config.max_position_embeddings - 1]`.
|
| 80 |
+
|
| 81 |
+
[What are position IDs?](../glossary#position-ids)
|
| 82 |
+
output_attentions (`bool`, *optional*):
|
| 83 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 84 |
+
tensors for more detail.
|
| 85 |
+
output_hidden_states (`bool`, *optional*):
|
| 86 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 87 |
+
more detail.
|
| 88 |
+
return_dict (`bool`, *optional*):
|
| 89 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
ALTCLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 93 |
+
Args:
|
| 94 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 95 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 96 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 97 |
+
output_attentions (`bool`, *optional*):
|
| 98 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 99 |
+
tensors for more detail.
|
| 100 |
+
output_hidden_states (`bool`, *optional*):
|
| 101 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 102 |
+
more detail.
|
| 103 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults `False`):
|
| 104 |
+
Whether to interpolate the pre-trained position encodings.
|
| 105 |
+
return_dict (`bool`, *optional*):
|
| 106 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
ALTCLIP_INPUTS_DOCSTRING = r"""
|
| 110 |
+
Args:
|
| 111 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 112 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 113 |
+
it.
|
| 114 |
+
|
| 115 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 116 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 117 |
+
|
| 118 |
+
[What are input IDs?](../glossary#input-ids)
|
| 119 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 120 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 121 |
+
|
| 122 |
+
- 1 for tokens that are **not masked**,
|
| 123 |
+
- 0 for tokens that are **masked**.
|
| 124 |
+
|
| 125 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 126 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 127 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 128 |
+
config.max_position_embeddings - 1]`.
|
| 129 |
+
|
| 130 |
+
[What are position IDs?](../glossary#position-ids)
|
| 131 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 132 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 133 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 134 |
+
return_loss (`bool`, *optional*):
|
| 135 |
+
Whether or not to return the contrastive loss.
|
| 136 |
+
output_attentions (`bool`, *optional*):
|
| 137 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 138 |
+
tensors for more detail.
|
| 139 |
+
output_hidden_states (`bool`, *optional*):
|
| 140 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 141 |
+
more detail.
|
| 142 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults `False`):
|
| 143 |
+
Whether to interpolate the pre-trained position encodings.
|
| 144 |
+
return_dict (`bool`, *optional*):
|
| 145 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# contrastive loss function, adapted from
|
| 150 |
+
# https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
|
| 151 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 152 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 156 |
+
caption_loss = contrastive_loss(similarity)
|
| 157 |
+
image_loss = contrastive_loss(similarity.t())
|
| 158 |
+
return (caption_loss + image_loss) / 2.0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@dataclass
|
| 162 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP
|
| 163 |
+
class AltCLIPOutput(ModelOutput):
|
| 164 |
+
"""
|
| 165 |
+
Args:
|
| 166 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 167 |
+
Contrastive loss for image-text similarity.
|
| 168 |
+
logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 169 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 170 |
+
similarity scores.
|
| 171 |
+
logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 172 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 173 |
+
similarity scores.
|
| 174 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 175 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPTextModel`].
|
| 176 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 177 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`AltCLIPVisionModel`].
|
| 178 |
+
text_model_output (`BaseModelOutputWithPooling`):
|
| 179 |
+
The output of the [`AltCLIPTextModel`].
|
| 180 |
+
vision_model_output (`BaseModelOutputWithPooling`):
|
| 181 |
+
The output of the [`AltCLIPVisionModel`].
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
loss: Optional[torch.FloatTensor] = None
|
| 185 |
+
logits_per_image: Optional[torch.FloatTensor] = None
|
| 186 |
+
logits_per_text: Optional[torch.FloatTensor] = None
|
| 187 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 188 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 189 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 190 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 191 |
+
|
| 192 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 193 |
+
return tuple(
|
| 194 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 195 |
+
for k in self.keys()
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->AltRoberta
|
| 200 |
+
class AltRobertaEmbeddings(nn.Module):
|
| 201 |
+
"""
|
| 202 |
+
Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
# Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
|
| 206 |
+
def __init__(self, config):
|
| 207 |
+
super().__init__()
|
| 208 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 209 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 210 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 211 |
+
|
| 212 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 213 |
+
# any TensorFlow checkpoint file
|
| 214 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 215 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 216 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 217 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 218 |
+
self.register_buffer(
|
| 219 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 220 |
+
)
|
| 221 |
+
self.register_buffer(
|
| 222 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
# End copy
|
| 226 |
+
self.padding_idx = config.pad_token_id
|
| 227 |
+
self.position_embeddings = nn.Embedding(
|
| 228 |
+
config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
def forward(
|
| 232 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
| 233 |
+
):
|
| 234 |
+
if position_ids is None:
|
| 235 |
+
if input_ids is not None:
|
| 236 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
| 237 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
| 238 |
+
else:
|
| 239 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
| 240 |
+
|
| 241 |
+
if input_ids is not None:
|
| 242 |
+
input_shape = input_ids.size()
|
| 243 |
+
else:
|
| 244 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 245 |
+
|
| 246 |
+
seq_length = input_shape[1]
|
| 247 |
+
|
| 248 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 249 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 250 |
+
# issue #5664
|
| 251 |
+
if token_type_ids is None:
|
| 252 |
+
if hasattr(self, "token_type_ids"):
|
| 253 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 254 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 255 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 256 |
+
else:
|
| 257 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 258 |
+
|
| 259 |
+
if inputs_embeds is None:
|
| 260 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 261 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 262 |
+
|
| 263 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 264 |
+
if self.position_embedding_type == "absolute":
|
| 265 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 266 |
+
embeddings += position_embeddings
|
| 267 |
+
embeddings = self.LayerNorm(embeddings)
|
| 268 |
+
embeddings = self.dropout(embeddings)
|
| 269 |
+
return embeddings
|
| 270 |
+
|
| 271 |
+
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
|
| 272 |
+
"""
|
| 273 |
+
We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
|
| 274 |
+
|
| 275 |
+
Args:
|
| 276 |
+
inputs_embeds: torch.Tensor
|
| 277 |
+
|
| 278 |
+
Returns: torch.Tensor
|
| 279 |
+
"""
|
| 280 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 281 |
+
sequence_length = input_shape[1]
|
| 282 |
+
|
| 283 |
+
position_ids = torch.arange(
|
| 284 |
+
self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
|
| 285 |
+
)
|
| 286 |
+
return position_ids.unsqueeze(0).expand(input_shape)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->AltRoberta
|
| 290 |
+
class AltRobertaSelfAttention(nn.Module):
|
| 291 |
+
def __init__(self, config, position_embedding_type=None):
|
| 292 |
+
super().__init__()
|
| 293 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 294 |
+
raise ValueError(
|
| 295 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 296 |
+
f"heads ({config.num_attention_heads})"
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
self.num_attention_heads = config.num_attention_heads
|
| 300 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 301 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 302 |
+
|
| 303 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 304 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 305 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 306 |
+
|
| 307 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 308 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 309 |
+
config, "position_embedding_type", "absolute"
|
| 310 |
+
)
|
| 311 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 312 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 313 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 314 |
+
|
| 315 |
+
self.is_decoder = config.is_decoder
|
| 316 |
+
|
| 317 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 318 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 319 |
+
x = x.view(new_x_shape)
|
| 320 |
+
return x.permute(0, 2, 1, 3)
|
| 321 |
+
|
| 322 |
+
def forward(
|
| 323 |
+
self,
|
| 324 |
+
hidden_states: torch.Tensor,
|
| 325 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 326 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 327 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 328 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 329 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 330 |
+
output_attentions: Optional[bool] = False,
|
| 331 |
+
) -> Tuple[torch.Tensor]:
|
| 332 |
+
mixed_query_layer = self.query(hidden_states)
|
| 333 |
+
|
| 334 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 335 |
+
# and values come from an encoder; the attention mask needs to be
|
| 336 |
+
# such that the encoder's padding tokens are not attended to.
|
| 337 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 338 |
+
|
| 339 |
+
if is_cross_attention and past_key_value is not None:
|
| 340 |
+
# reuse k,v, cross_attentions
|
| 341 |
+
key_layer = past_key_value[0]
|
| 342 |
+
value_layer = past_key_value[1]
|
| 343 |
+
attention_mask = encoder_attention_mask
|
| 344 |
+
elif is_cross_attention:
|
| 345 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 346 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 347 |
+
attention_mask = encoder_attention_mask
|
| 348 |
+
elif past_key_value is not None:
|
| 349 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 350 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 351 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 352 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 353 |
+
else:
|
| 354 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 355 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 356 |
+
|
| 357 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 358 |
+
|
| 359 |
+
use_cache = past_key_value is not None
|
| 360 |
+
if self.is_decoder:
|
| 361 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 362 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 363 |
+
# key/value_states (first "if" case)
|
| 364 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 365 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 366 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 367 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 368 |
+
past_key_value = (key_layer, value_layer)
|
| 369 |
+
|
| 370 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 371 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 372 |
+
|
| 373 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 374 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 375 |
+
if use_cache:
|
| 376 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 377 |
+
-1, 1
|
| 378 |
+
)
|
| 379 |
+
else:
|
| 380 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 381 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 382 |
+
distance = position_ids_l - position_ids_r
|
| 383 |
+
|
| 384 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 385 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 386 |
+
|
| 387 |
+
if self.position_embedding_type == "relative_key":
|
| 388 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 389 |
+
attention_scores = attention_scores + relative_position_scores
|
| 390 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 391 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 392 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 393 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 394 |
+
|
| 395 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 396 |
+
if attention_mask is not None:
|
| 397 |
+
# Apply the attention mask is (precomputed for all layers in AltRobertaModel forward() function)
|
| 398 |
+
attention_scores = attention_scores + attention_mask
|
| 399 |
+
|
| 400 |
+
# Normalize the attention scores to probabilities.
|
| 401 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 402 |
+
|
| 403 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 404 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 405 |
+
attention_probs = self.dropout(attention_probs)
|
| 406 |
+
|
| 407 |
+
# Mask heads if we want to
|
| 408 |
+
if head_mask is not None:
|
| 409 |
+
attention_probs = attention_probs * head_mask
|
| 410 |
+
|
| 411 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 412 |
+
|
| 413 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 414 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 415 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 416 |
+
|
| 417 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 418 |
+
|
| 419 |
+
if self.is_decoder:
|
| 420 |
+
outputs = outputs + (past_key_value,)
|
| 421 |
+
return outputs
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput
|
| 425 |
+
class AltRobertaSelfOutput(nn.Module):
|
| 426 |
+
def __init__(self, config):
|
| 427 |
+
super().__init__()
|
| 428 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 429 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 430 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 431 |
+
|
| 432 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 433 |
+
hidden_states = self.dense(hidden_states)
|
| 434 |
+
hidden_states = self.dropout(hidden_states)
|
| 435 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 436 |
+
return hidden_states
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
ALT_ROBERTA_SELF_ATTENTION_CLASSES = {
|
| 440 |
+
"eager": AltRobertaSelfAttention,
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaAttention with Roberta->AltRoberta,ROBERTA->ALT_ROBERTA
|
| 445 |
+
class AltRobertaAttention(nn.Module):
|
| 446 |
+
def __init__(self, config, position_embedding_type=None):
|
| 447 |
+
super().__init__()
|
| 448 |
+
self.self = ALT_ROBERTA_SELF_ATTENTION_CLASSES[config._attn_implementation](
|
| 449 |
+
config, position_embedding_type=position_embedding_type
|
| 450 |
+
)
|
| 451 |
+
self.output = AltRobertaSelfOutput(config)
|
| 452 |
+
self.pruned_heads = set()
|
| 453 |
+
|
| 454 |
+
def prune_heads(self, heads):
|
| 455 |
+
if len(heads) == 0:
|
| 456 |
+
return
|
| 457 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 458 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
# Prune linear layers
|
| 462 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 463 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 464 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 465 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 466 |
+
|
| 467 |
+
# Update hyper params and store pruned heads
|
| 468 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 469 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 470 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 471 |
+
|
| 472 |
+
def forward(
|
| 473 |
+
self,
|
| 474 |
+
hidden_states: torch.Tensor,
|
| 475 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 476 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 477 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 478 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 479 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 480 |
+
output_attentions: Optional[bool] = False,
|
| 481 |
+
) -> Tuple[torch.Tensor]:
|
| 482 |
+
self_outputs = self.self(
|
| 483 |
+
hidden_states,
|
| 484 |
+
attention_mask,
|
| 485 |
+
head_mask,
|
| 486 |
+
encoder_hidden_states,
|
| 487 |
+
encoder_attention_mask,
|
| 488 |
+
past_key_value,
|
| 489 |
+
output_attentions,
|
| 490 |
+
)
|
| 491 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 492 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 493 |
+
return outputs
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate with Roberta->AltRoberta
|
| 497 |
+
class AltRobertaIntermediate(nn.Module):
|
| 498 |
+
def __init__(self, config):
|
| 499 |
+
super().__init__()
|
| 500 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 501 |
+
if isinstance(config.hidden_act, str):
|
| 502 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 503 |
+
else:
|
| 504 |
+
self.intermediate_act_fn = config.hidden_act
|
| 505 |
+
|
| 506 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 507 |
+
hidden_states = self.dense(hidden_states)
|
| 508 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 509 |
+
return hidden_states
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaOutput
|
| 513 |
+
class AltRobertaOutput(nn.Module):
|
| 514 |
+
def __init__(self, config):
|
| 515 |
+
super().__init__()
|
| 516 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 517 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 518 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 519 |
+
|
| 520 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 521 |
+
hidden_states = self.dense(hidden_states)
|
| 522 |
+
hidden_states = self.dropout(hidden_states)
|
| 523 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 524 |
+
return hidden_states
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaLayer with Roberta->AltRoberta
|
| 528 |
+
class AltRobertaLayer(nn.Module):
|
| 529 |
+
def __init__(self, config):
|
| 530 |
+
super().__init__()
|
| 531 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 532 |
+
self.seq_len_dim = 1
|
| 533 |
+
self.attention = AltRobertaAttention(config)
|
| 534 |
+
self.is_decoder = config.is_decoder
|
| 535 |
+
self.add_cross_attention = config.add_cross_attention
|
| 536 |
+
if self.add_cross_attention:
|
| 537 |
+
if not self.is_decoder:
|
| 538 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 539 |
+
self.crossattention = AltRobertaAttention(config, position_embedding_type="absolute")
|
| 540 |
+
self.intermediate = AltRobertaIntermediate(config)
|
| 541 |
+
self.output = AltRobertaOutput(config)
|
| 542 |
+
|
| 543 |
+
def forward(
|
| 544 |
+
self,
|
| 545 |
+
hidden_states: torch.Tensor,
|
| 546 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 547 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 548 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 549 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 550 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 551 |
+
output_attentions: Optional[bool] = False,
|
| 552 |
+
) -> Tuple[torch.Tensor]:
|
| 553 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 554 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 555 |
+
self_attention_outputs = self.attention(
|
| 556 |
+
hidden_states,
|
| 557 |
+
attention_mask,
|
| 558 |
+
head_mask,
|
| 559 |
+
output_attentions=output_attentions,
|
| 560 |
+
past_key_value=self_attn_past_key_value,
|
| 561 |
+
)
|
| 562 |
+
attention_output = self_attention_outputs[0]
|
| 563 |
+
|
| 564 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 565 |
+
if self.is_decoder:
|
| 566 |
+
outputs = self_attention_outputs[1:-1]
|
| 567 |
+
present_key_value = self_attention_outputs[-1]
|
| 568 |
+
else:
|
| 569 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 570 |
+
|
| 571 |
+
cross_attn_present_key_value = None
|
| 572 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 573 |
+
if not hasattr(self, "crossattention"):
|
| 574 |
+
raise ValueError(
|
| 575 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 576 |
+
" by setting `config.add_cross_attention=True`"
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 580 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 581 |
+
cross_attention_outputs = self.crossattention(
|
| 582 |
+
attention_output,
|
| 583 |
+
attention_mask,
|
| 584 |
+
head_mask,
|
| 585 |
+
encoder_hidden_states,
|
| 586 |
+
encoder_attention_mask,
|
| 587 |
+
cross_attn_past_key_value,
|
| 588 |
+
output_attentions,
|
| 589 |
+
)
|
| 590 |
+
attention_output = cross_attention_outputs[0]
|
| 591 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 592 |
+
|
| 593 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 594 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 595 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 596 |
+
|
| 597 |
+
layer_output = apply_chunking_to_forward(
|
| 598 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 599 |
+
)
|
| 600 |
+
outputs = (layer_output,) + outputs
|
| 601 |
+
|
| 602 |
+
# if decoder, return the attn key/values as the last output
|
| 603 |
+
if self.is_decoder:
|
| 604 |
+
outputs = outputs + (present_key_value,)
|
| 605 |
+
|
| 606 |
+
return outputs
|
| 607 |
+
|
| 608 |
+
def feed_forward_chunk(self, attention_output):
|
| 609 |
+
intermediate_output = self.intermediate(attention_output)
|
| 610 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 611 |
+
return layer_output
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->AltRoberta
|
| 615 |
+
class AltRobertaEncoder(nn.Module):
|
| 616 |
+
def __init__(self, config):
|
| 617 |
+
super().__init__()
|
| 618 |
+
self.config = config
|
| 619 |
+
self.layer = nn.ModuleList([AltRobertaLayer(config) for _ in range(config.num_hidden_layers)])
|
| 620 |
+
self.gradient_checkpointing = False
|
| 621 |
+
|
| 622 |
+
def forward(
|
| 623 |
+
self,
|
| 624 |
+
hidden_states: torch.Tensor,
|
| 625 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 626 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 627 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 628 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 629 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 630 |
+
use_cache: Optional[bool] = None,
|
| 631 |
+
output_attentions: Optional[bool] = False,
|
| 632 |
+
output_hidden_states: Optional[bool] = False,
|
| 633 |
+
return_dict: Optional[bool] = True,
|
| 634 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 635 |
+
all_hidden_states = () if output_hidden_states else None
|
| 636 |
+
all_self_attentions = () if output_attentions else None
|
| 637 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 638 |
+
|
| 639 |
+
if self.gradient_checkpointing and self.training:
|
| 640 |
+
if use_cache:
|
| 641 |
+
logger.warning_once(
|
| 642 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 643 |
+
)
|
| 644 |
+
use_cache = False
|
| 645 |
+
|
| 646 |
+
next_decoder_cache = () if use_cache else None
|
| 647 |
+
for i, layer_module in enumerate(self.layer):
|
| 648 |
+
if output_hidden_states:
|
| 649 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 650 |
+
|
| 651 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 652 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 653 |
+
|
| 654 |
+
if self.gradient_checkpointing and self.training:
|
| 655 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 656 |
+
layer_module.__call__,
|
| 657 |
+
hidden_states,
|
| 658 |
+
attention_mask,
|
| 659 |
+
layer_head_mask,
|
| 660 |
+
encoder_hidden_states,
|
| 661 |
+
encoder_attention_mask,
|
| 662 |
+
past_key_value,
|
| 663 |
+
output_attentions,
|
| 664 |
+
)
|
| 665 |
+
else:
|
| 666 |
+
layer_outputs = layer_module(
|
| 667 |
+
hidden_states,
|
| 668 |
+
attention_mask,
|
| 669 |
+
layer_head_mask,
|
| 670 |
+
encoder_hidden_states,
|
| 671 |
+
encoder_attention_mask,
|
| 672 |
+
past_key_value,
|
| 673 |
+
output_attentions,
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
hidden_states = layer_outputs[0]
|
| 677 |
+
if use_cache:
|
| 678 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 679 |
+
if output_attentions:
|
| 680 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 681 |
+
if self.config.add_cross_attention:
|
| 682 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 683 |
+
|
| 684 |
+
if output_hidden_states:
|
| 685 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 686 |
+
|
| 687 |
+
if not return_dict:
|
| 688 |
+
return tuple(
|
| 689 |
+
v
|
| 690 |
+
for v in [
|
| 691 |
+
hidden_states,
|
| 692 |
+
next_decoder_cache,
|
| 693 |
+
all_hidden_states,
|
| 694 |
+
all_self_attentions,
|
| 695 |
+
all_cross_attentions,
|
| 696 |
+
]
|
| 697 |
+
if v is not None
|
| 698 |
+
)
|
| 699 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 700 |
+
last_hidden_state=hidden_states,
|
| 701 |
+
past_key_values=next_decoder_cache,
|
| 702 |
+
hidden_states=all_hidden_states,
|
| 703 |
+
attentions=all_self_attentions,
|
| 704 |
+
cross_attentions=all_cross_attentions,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
|
| 709 |
+
class AltRobertaPooler(nn.Module):
|
| 710 |
+
def __init__(self, config):
|
| 711 |
+
super().__init__()
|
| 712 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 713 |
+
self.activation = nn.Tanh()
|
| 714 |
+
|
| 715 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 716 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 717 |
+
# to the first token.
|
| 718 |
+
first_token_tensor = hidden_states[:, 0]
|
| 719 |
+
pooled_output = self.dense(first_token_tensor)
|
| 720 |
+
pooled_output = self.activation(pooled_output)
|
| 721 |
+
return pooled_output
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPAttention with CLIP->AltCLIP
|
| 725 |
+
class AltCLIPAttention(nn.Module):
|
| 726 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 727 |
+
|
| 728 |
+
def __init__(self, config):
|
| 729 |
+
super().__init__()
|
| 730 |
+
self.config = config
|
| 731 |
+
self.embed_dim = config.hidden_size
|
| 732 |
+
self.num_heads = config.num_attention_heads
|
| 733 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 734 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 735 |
+
raise ValueError(
|
| 736 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 737 |
+
f" {self.num_heads})."
|
| 738 |
+
)
|
| 739 |
+
self.scale = self.head_dim**-0.5
|
| 740 |
+
self.dropout = config.attention_dropout
|
| 741 |
+
|
| 742 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 743 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 744 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 745 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 746 |
+
|
| 747 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 748 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 749 |
+
|
| 750 |
+
def forward(
|
| 751 |
+
self,
|
| 752 |
+
hidden_states: torch.Tensor,
|
| 753 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 754 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 755 |
+
output_attentions: Optional[bool] = False,
|
| 756 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 757 |
+
"""Input shape: Batch x Time x Channel"""
|
| 758 |
+
|
| 759 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 760 |
+
|
| 761 |
+
# get query proj
|
| 762 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 763 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 764 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 765 |
+
|
| 766 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 767 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 768 |
+
key_states = key_states.view(*proj_shape)
|
| 769 |
+
value_states = value_states.view(*proj_shape)
|
| 770 |
+
|
| 771 |
+
src_len = key_states.size(1)
|
| 772 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 773 |
+
|
| 774 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 775 |
+
raise ValueError(
|
| 776 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 777 |
+
f" {attn_weights.size()}"
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
# apply the causal_attention_mask first
|
| 781 |
+
if causal_attention_mask is not None:
|
| 782 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 783 |
+
raise ValueError(
|
| 784 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 785 |
+
f" {causal_attention_mask.size()}"
|
| 786 |
+
)
|
| 787 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
| 788 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 789 |
+
|
| 790 |
+
if attention_mask is not None:
|
| 791 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 792 |
+
raise ValueError(
|
| 793 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 794 |
+
)
|
| 795 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 796 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 797 |
+
|
| 798 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 799 |
+
|
| 800 |
+
if output_attentions:
|
| 801 |
+
# this operation is a bit awkward, but it's required to
|
| 802 |
+
# make sure that attn_weights keeps its gradient.
|
| 803 |
+
# In order to do so, attn_weights have to reshaped
|
| 804 |
+
# twice and have to be reused in the following
|
| 805 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 806 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 807 |
+
else:
|
| 808 |
+
attn_weights_reshaped = None
|
| 809 |
+
|
| 810 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 811 |
+
|
| 812 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 813 |
+
|
| 814 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 815 |
+
raise ValueError(
|
| 816 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 817 |
+
f" {attn_output.size()}"
|
| 818 |
+
)
|
| 819 |
+
|
| 820 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 821 |
+
attn_output = attn_output.transpose(1, 2)
|
| 822 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 823 |
+
|
| 824 |
+
attn_output = self.out_proj(attn_output)
|
| 825 |
+
|
| 826 |
+
return attn_output, attn_weights_reshaped
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->AltCLIP
|
| 830 |
+
class AltCLIPMLP(nn.Module):
|
| 831 |
+
def __init__(self, config):
|
| 832 |
+
super().__init__()
|
| 833 |
+
self.config = config
|
| 834 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 835 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 836 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 837 |
+
|
| 838 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 839 |
+
hidden_states = self.fc1(hidden_states)
|
| 840 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 841 |
+
hidden_states = self.fc2(hidden_states)
|
| 842 |
+
return hidden_states
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
class AltCLIPEncoderLayer(nn.Module):
|
| 846 |
+
def __init__(self, config: AltCLIPConfig):
|
| 847 |
+
super().__init__()
|
| 848 |
+
self.embed_dim = config.hidden_size
|
| 849 |
+
self.self_attn = AltCLIPAttention(config)
|
| 850 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 851 |
+
self.mlp = AltCLIPMLP(config)
|
| 852 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 853 |
+
|
| 854 |
+
def forward(
|
| 855 |
+
self,
|
| 856 |
+
hidden_states: torch.Tensor,
|
| 857 |
+
attention_mask: torch.Tensor,
|
| 858 |
+
causal_attention_mask: torch.Tensor,
|
| 859 |
+
output_attentions: Optional[bool] = False,
|
| 860 |
+
) -> Tuple[torch.FloatTensor]:
|
| 861 |
+
"""
|
| 862 |
+
Args:
|
| 863 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 864 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 865 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 866 |
+
`(config.encoder_attention_heads,)`.
|
| 867 |
+
output_attentions (`bool`, *optional*):
|
| 868 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 869 |
+
returned tensors for more detail.
|
| 870 |
+
"""
|
| 871 |
+
residual = hidden_states
|
| 872 |
+
|
| 873 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 874 |
+
hidden_states, attn_weights = self.self_attn(
|
| 875 |
+
hidden_states=hidden_states,
|
| 876 |
+
attention_mask=attention_mask,
|
| 877 |
+
causal_attention_mask=causal_attention_mask,
|
| 878 |
+
output_attentions=output_attentions,
|
| 879 |
+
)
|
| 880 |
+
hidden_states = residual + hidden_states
|
| 881 |
+
|
| 882 |
+
residual = hidden_states
|
| 883 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 884 |
+
hidden_states = self.mlp(hidden_states)
|
| 885 |
+
hidden_states = residual + hidden_states
|
| 886 |
+
|
| 887 |
+
outputs = (hidden_states,)
|
| 888 |
+
|
| 889 |
+
if output_attentions:
|
| 890 |
+
outputs += (attn_weights,)
|
| 891 |
+
|
| 892 |
+
return outputs
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
class AltCLIPEncoder(nn.Module):
|
| 896 |
+
"""
|
| 897 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 898 |
+
[`AltCLIPEncoderLayer`].
|
| 899 |
+
|
| 900 |
+
Args:
|
| 901 |
+
config: AltCLIPConfig
|
| 902 |
+
"""
|
| 903 |
+
|
| 904 |
+
def __init__(self, config: AltCLIPConfig):
|
| 905 |
+
super().__init__()
|
| 906 |
+
self.config = config
|
| 907 |
+
self.layers = nn.ModuleList([AltCLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 908 |
+
self.gradient_checkpointing = False
|
| 909 |
+
|
| 910 |
+
def forward(
|
| 911 |
+
self,
|
| 912 |
+
inputs_embeds,
|
| 913 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 914 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 915 |
+
output_attentions: Optional[bool] = None,
|
| 916 |
+
output_hidden_states: Optional[bool] = None,
|
| 917 |
+
return_dict: Optional[bool] = None,
|
| 918 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 919 |
+
r"""
|
| 920 |
+
Args:
|
| 921 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 922 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 923 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 924 |
+
than the model's internal embedding lookup matrix.
|
| 925 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 926 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 927 |
+
|
| 928 |
+
- 1 for tokens that are **not masked**,
|
| 929 |
+
- 0 for tokens that are **masked**.
|
| 930 |
+
|
| 931 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 932 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 933 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
| 934 |
+
|
| 935 |
+
- 1 for tokens that are **not masked**,
|
| 936 |
+
- 0 for tokens that are **masked**.
|
| 937 |
+
|
| 938 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 939 |
+
output_attentions (`bool`, *optional*):
|
| 940 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 941 |
+
returned tensors for more detail.
|
| 942 |
+
output_hidden_states (`bool`, *optional*):
|
| 943 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 944 |
+
for more detail.
|
| 945 |
+
return_dict (`bool`, *optional*):
|
| 946 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 947 |
+
"""
|
| 948 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 949 |
+
output_hidden_states = (
|
| 950 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 951 |
+
)
|
| 952 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 953 |
+
|
| 954 |
+
encoder_states = () if output_hidden_states else None
|
| 955 |
+
all_attentions = () if output_attentions else None
|
| 956 |
+
|
| 957 |
+
hidden_states = inputs_embeds
|
| 958 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 959 |
+
if output_hidden_states:
|
| 960 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 961 |
+
if self.gradient_checkpointing and self.training:
|
| 962 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 963 |
+
encoder_layer.__call__,
|
| 964 |
+
hidden_states,
|
| 965 |
+
attention_mask,
|
| 966 |
+
causal_attention_mask,
|
| 967 |
+
output_attentions,
|
| 968 |
+
)
|
| 969 |
+
else:
|
| 970 |
+
layer_outputs = encoder_layer(
|
| 971 |
+
hidden_states,
|
| 972 |
+
attention_mask,
|
| 973 |
+
causal_attention_mask,
|
| 974 |
+
output_attentions=output_attentions,
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
hidden_states = layer_outputs[0]
|
| 978 |
+
|
| 979 |
+
if output_attentions:
|
| 980 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 981 |
+
|
| 982 |
+
if output_hidden_states:
|
| 983 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 984 |
+
|
| 985 |
+
if not return_dict:
|
| 986 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 987 |
+
return BaseModelOutput(
|
| 988 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 989 |
+
)
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->AltCLIP
|
| 993 |
+
class AltCLIPVisionEmbeddings(nn.Module):
|
| 994 |
+
def __init__(self, config: AltCLIPVisionConfig):
|
| 995 |
+
super().__init__()
|
| 996 |
+
self.config = config
|
| 997 |
+
self.embed_dim = config.hidden_size
|
| 998 |
+
self.image_size = config.image_size
|
| 999 |
+
self.patch_size = config.patch_size
|
| 1000 |
+
|
| 1001 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 1002 |
+
|
| 1003 |
+
self.patch_embedding = nn.Conv2d(
|
| 1004 |
+
in_channels=config.num_channels,
|
| 1005 |
+
out_channels=self.embed_dim,
|
| 1006 |
+
kernel_size=self.patch_size,
|
| 1007 |
+
stride=self.patch_size,
|
| 1008 |
+
bias=False,
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 1012 |
+
self.num_positions = self.num_patches + 1
|
| 1013 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 1014 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 1015 |
+
|
| 1016 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 1017 |
+
"""
|
| 1018 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 1019 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 1020 |
+
|
| 1021 |
+
Adapted from:
|
| 1022 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 1023 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 1024 |
+
"""
|
| 1025 |
+
|
| 1026 |
+
num_patches = embeddings.shape[1] - 1
|
| 1027 |
+
position_embedding = self.position_embedding.weight.unsqueeze(0)
|
| 1028 |
+
num_positions = position_embedding.shape[1] - 1
|
| 1029 |
+
|
| 1030 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 1031 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 1032 |
+
return self.position_embedding(self.position_ids)
|
| 1033 |
+
|
| 1034 |
+
class_pos_embed = position_embedding[:, :1]
|
| 1035 |
+
patch_pos_embed = position_embedding[:, 1:]
|
| 1036 |
+
|
| 1037 |
+
dim = embeddings.shape[-1]
|
| 1038 |
+
|
| 1039 |
+
new_height = height // self.patch_size
|
| 1040 |
+
new_width = width // self.patch_size
|
| 1041 |
+
|
| 1042 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 1043 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 1044 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 1045 |
+
|
| 1046 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 1047 |
+
patch_pos_embed,
|
| 1048 |
+
size=(new_height, new_width),
|
| 1049 |
+
mode="bicubic",
|
| 1050 |
+
align_corners=False,
|
| 1051 |
+
)
|
| 1052 |
+
|
| 1053 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 1054 |
+
|
| 1055 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 1056 |
+
|
| 1057 |
+
def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
|
| 1058 |
+
batch_size, _, height, width = pixel_values.shape
|
| 1059 |
+
if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
|
| 1060 |
+
raise ValueError(
|
| 1061 |
+
f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
|
| 1062 |
+
)
|
| 1063 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 1064 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 1065 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 1066 |
+
|
| 1067 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 1068 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 1069 |
+
if interpolate_pos_encoding:
|
| 1070 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 1071 |
+
else:
|
| 1072 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 1073 |
+
return embeddings
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
class AltCLIPPreTrainedModel(PreTrainedModel):
|
| 1077 |
+
"""
|
| 1078 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 1079 |
+
models.
|
| 1080 |
+
"""
|
| 1081 |
+
|
| 1082 |
+
config_class = AltCLIPConfig
|
| 1083 |
+
base_model_prefix = "altclip"
|
| 1084 |
+
supports_gradient_checkpointing = True
|
| 1085 |
+
_no_split_module = []
|
| 1086 |
+
|
| 1087 |
+
def _init_weights(self, module):
|
| 1088 |
+
"""Initialize the weights"""
|
| 1089 |
+
factor = self.config.initializer_factor
|
| 1090 |
+
if isinstance(module, AltCLIPVisionEmbeddings):
|
| 1091 |
+
factor = self.config.initializer_factor
|
| 1092 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 1093 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 1094 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
| 1095 |
+
elif isinstance(module, AltCLIPAttention):
|
| 1096 |
+
factor = self.config.initializer_factor
|
| 1097 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 1098 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 1099 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 1100 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 1101 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 1102 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 1103 |
+
elif isinstance(module, AltCLIPMLP):
|
| 1104 |
+
factor = self.config.initializer_factor
|
| 1105 |
+
in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 1106 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 1107 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 1108 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 1109 |
+
elif isinstance(module, AltCLIPModel):
|
| 1110 |
+
nn.init.normal_(
|
| 1111 |
+
module.text_projection.weight,
|
| 1112 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
| 1113 |
+
)
|
| 1114 |
+
module.text_projection._is_hf_initialized = True
|
| 1115 |
+
nn.init.normal_(
|
| 1116 |
+
module.visual_projection.weight,
|
| 1117 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
| 1118 |
+
)
|
| 1119 |
+
module.visual_projection._is_hf_initialized = True
|
| 1120 |
+
elif isinstance(module, nn.LayerNorm):
|
| 1121 |
+
module.bias.data.zero_()
|
| 1122 |
+
module.weight.data.fill_(1.0)
|
| 1123 |
+
elif isinstance(module, nn.Linear):
|
| 1124 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
|
| 1125 |
+
if module.bias is not None:
|
| 1126 |
+
module.bias.data.zero_()
|
| 1127 |
+
elif isinstance(module, nn.Embedding):
|
| 1128 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_factor)
|
| 1129 |
+
if module.padding_idx is not None:
|
| 1130 |
+
module.weight.data[module.padding_idx].zero_()
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
class AltCLIPVisionTransformer(nn.Module):
|
| 1134 |
+
def __init__(self, config: AltCLIPVisionConfig):
|
| 1135 |
+
super().__init__()
|
| 1136 |
+
self.config = config
|
| 1137 |
+
embed_dim = config.hidden_size
|
| 1138 |
+
|
| 1139 |
+
self.embeddings = AltCLIPVisionEmbeddings(config)
|
| 1140 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1141 |
+
self.encoder = AltCLIPEncoder(config)
|
| 1142 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 1143 |
+
|
| 1144 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
|
| 1145 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=AltCLIPVisionConfig)
|
| 1146 |
+
def forward(
|
| 1147 |
+
self,
|
| 1148 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1149 |
+
output_attentions: Optional[bool] = None,
|
| 1150 |
+
output_hidden_states: Optional[bool] = None,
|
| 1151 |
+
return_dict: Optional[bool] = None,
|
| 1152 |
+
interpolate_pos_encoding: Optional[bool] = False,
|
| 1153 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1154 |
+
r"""
|
| 1155 |
+
Returns:
|
| 1156 |
+
|
| 1157 |
+
"""
|
| 1158 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1159 |
+
output_hidden_states = (
|
| 1160 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1161 |
+
)
|
| 1162 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1163 |
+
|
| 1164 |
+
if pixel_values is None:
|
| 1165 |
+
raise ValueError("You have to specify pixel_values")
|
| 1166 |
+
|
| 1167 |
+
hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 1168 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
| 1169 |
+
|
| 1170 |
+
encoder_outputs = self.encoder(
|
| 1171 |
+
inputs_embeds=hidden_states,
|
| 1172 |
+
output_attentions=output_attentions,
|
| 1173 |
+
output_hidden_states=output_hidden_states,
|
| 1174 |
+
return_dict=return_dict,
|
| 1175 |
+
)
|
| 1176 |
+
|
| 1177 |
+
last_hidden_state = encoder_outputs[0]
|
| 1178 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 1179 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 1180 |
+
|
| 1181 |
+
if not return_dict:
|
| 1182 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 1183 |
+
|
| 1184 |
+
return BaseModelOutputWithPooling(
|
| 1185 |
+
last_hidden_state=last_hidden_state,
|
| 1186 |
+
pooler_output=pooled_output,
|
| 1187 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1188 |
+
attentions=encoder_outputs.attentions,
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
|
| 1192 |
+
class AltCLIPVisionModel(AltCLIPPreTrainedModel):
|
| 1193 |
+
config_class = AltCLIPVisionConfig
|
| 1194 |
+
main_input_name = "pixel_values"
|
| 1195 |
+
|
| 1196 |
+
def __init__(self, config: AltCLIPVisionConfig):
|
| 1197 |
+
super().__init__(config)
|
| 1198 |
+
self.vision_model = AltCLIPVisionTransformer(config)
|
| 1199 |
+
# Initialize weights and apply final processing
|
| 1200 |
+
self.post_init()
|
| 1201 |
+
|
| 1202 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1203 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1204 |
+
|
| 1205 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
|
| 1206 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=AltCLIPVisionConfig)
|
| 1207 |
+
def forward(
|
| 1208 |
+
self,
|
| 1209 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1210 |
+
output_attentions: Optional[bool] = None,
|
| 1211 |
+
output_hidden_states: Optional[bool] = None,
|
| 1212 |
+
interpolate_pos_encoding: bool = False,
|
| 1213 |
+
return_dict: Optional[bool] = None,
|
| 1214 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 1215 |
+
r"""
|
| 1216 |
+
Returns:
|
| 1217 |
+
|
| 1218 |
+
Examples:
|
| 1219 |
+
|
| 1220 |
+
```python
|
| 1221 |
+
>>> from PIL import Image
|
| 1222 |
+
>>> import requests
|
| 1223 |
+
>>> from transformers import AutoProcessor, AltCLIPVisionModel
|
| 1224 |
+
|
| 1225 |
+
>>> model = AltCLIPVisionModel.from_pretrained("BAAI/AltCLIP")
|
| 1226 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1227 |
+
|
| 1228 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1229 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1230 |
+
|
| 1231 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1232 |
+
|
| 1233 |
+
>>> outputs = model(**inputs)
|
| 1234 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1235 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1236 |
+
```"""
|
| 1237 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1238 |
+
|
| 1239 |
+
return self.vision_model(
|
| 1240 |
+
pixel_values=pixel_values,
|
| 1241 |
+
output_attentions=output_attentions,
|
| 1242 |
+
output_hidden_states=output_hidden_states,
|
| 1243 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1244 |
+
return_dict=return_dict,
|
| 1245 |
+
)
|
| 1246 |
+
|
| 1247 |
+
|
| 1248 |
+
class AltRobertaModel(AltCLIPPreTrainedModel):
|
| 1249 |
+
"""
|
| 1250 |
+
|
| 1251 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 1252 |
+
cross-attention is added between the self-attention layers, following the architecture described in *Attention is
|
| 1253 |
+
all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
|
| 1254 |
+
Kaiser and Illia Polosukhin.
|
| 1255 |
+
|
| 1256 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 1257 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 1258 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 1259 |
+
|
| 1260 |
+
.. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
|
| 1261 |
+
|
| 1262 |
+
"""
|
| 1263 |
+
|
| 1264 |
+
config_class = AltCLIPTextConfig
|
| 1265 |
+
|
| 1266 |
+
# Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->AltRoberta
|
| 1267 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 1268 |
+
super().__init__(config)
|
| 1269 |
+
self.config = config
|
| 1270 |
+
|
| 1271 |
+
self.embeddings = AltRobertaEmbeddings(config)
|
| 1272 |
+
self.encoder = AltRobertaEncoder(config)
|
| 1273 |
+
|
| 1274 |
+
self.pooler = AltRobertaPooler(config) if add_pooling_layer else None
|
| 1275 |
+
|
| 1276 |
+
# Initialize weights and apply final processing
|
| 1277 |
+
self.post_init()
|
| 1278 |
+
|
| 1279 |
+
def get_input_embeddings(self):
|
| 1280 |
+
return self.embeddings.word_embeddings
|
| 1281 |
+
|
| 1282 |
+
def set_input_embeddings(self, value):
|
| 1283 |
+
self.embeddings.word_embeddings = value
|
| 1284 |
+
|
| 1285 |
+
def _prune_heads(self, heads_to_prune):
|
| 1286 |
+
"""
|
| 1287 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 1288 |
+
class PreTrainedModel
|
| 1289 |
+
"""
|
| 1290 |
+
for layer, heads in heads_to_prune.items():
|
| 1291 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 1292 |
+
|
| 1293 |
+
# Copied from transformers.models.clap.modeling_clap.ClapTextModel.forward
|
| 1294 |
+
def forward(
|
| 1295 |
+
self,
|
| 1296 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1297 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1298 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1299 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1300 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1301 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1302 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1303 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1304 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1305 |
+
use_cache: Optional[bool] = None,
|
| 1306 |
+
output_attentions: Optional[bool] = None,
|
| 1307 |
+
output_hidden_states: Optional[bool] = None,
|
| 1308 |
+
return_dict: Optional[bool] = None,
|
| 1309 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 1310 |
+
r"""
|
| 1311 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1312 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1313 |
+
the model is configured as a decoder.
|
| 1314 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1315 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1316 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1317 |
+
|
| 1318 |
+
- 1 for tokens that are **not masked**,
|
| 1319 |
+
- 0 for tokens that are **masked**.
|
| 1320 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
| 1321 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1322 |
+
|
| 1323 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1324 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1325 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1326 |
+
use_cache (`bool`, *optional*):
|
| 1327 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1328 |
+
`past_key_values`).
|
| 1329 |
+
"""
|
| 1330 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1331 |
+
output_hidden_states = (
|
| 1332 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1333 |
+
)
|
| 1334 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1335 |
+
|
| 1336 |
+
if self.config.is_decoder:
|
| 1337 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1338 |
+
else:
|
| 1339 |
+
use_cache = False
|
| 1340 |
+
|
| 1341 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1342 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1343 |
+
elif input_ids is not None:
|
| 1344 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 1345 |
+
input_shape = input_ids.size()
|
| 1346 |
+
elif inputs_embeds is not None:
|
| 1347 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1348 |
+
else:
|
| 1349 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1350 |
+
|
| 1351 |
+
batch_size, seq_length = input_shape
|
| 1352 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1353 |
+
|
| 1354 |
+
# past_key_values_length
|
| 1355 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1356 |
+
|
| 1357 |
+
if attention_mask is None:
|
| 1358 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
| 1359 |
+
|
| 1360 |
+
if token_type_ids is None:
|
| 1361 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1362 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1363 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1364 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1365 |
+
else:
|
| 1366 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1367 |
+
|
| 1368 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1369 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1370 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1371 |
+
|
| 1372 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 1373 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 1374 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 1375 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 1376 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 1377 |
+
if encoder_attention_mask is None:
|
| 1378 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 1379 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 1380 |
+
else:
|
| 1381 |
+
encoder_extended_attention_mask = None
|
| 1382 |
+
|
| 1383 |
+
# Prepare head mask if needed
|
| 1384 |
+
# 1.0 in head_mask indicate we keep the head
|
| 1385 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 1386 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 1387 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1388 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1389 |
+
|
| 1390 |
+
embedding_output = self.embeddings(
|
| 1391 |
+
input_ids=input_ids,
|
| 1392 |
+
position_ids=position_ids,
|
| 1393 |
+
token_type_ids=token_type_ids,
|
| 1394 |
+
inputs_embeds=inputs_embeds,
|
| 1395 |
+
past_key_values_length=past_key_values_length,
|
| 1396 |
+
)
|
| 1397 |
+
encoder_outputs = self.encoder(
|
| 1398 |
+
embedding_output,
|
| 1399 |
+
attention_mask=extended_attention_mask,
|
| 1400 |
+
head_mask=head_mask,
|
| 1401 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1402 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 1403 |
+
past_key_values=past_key_values,
|
| 1404 |
+
use_cache=use_cache,
|
| 1405 |
+
output_attentions=output_attentions,
|
| 1406 |
+
output_hidden_states=output_hidden_states,
|
| 1407 |
+
return_dict=return_dict,
|
| 1408 |
+
)
|
| 1409 |
+
sequence_output = encoder_outputs[0]
|
| 1410 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1411 |
+
|
| 1412 |
+
if not return_dict:
|
| 1413 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 1414 |
+
|
| 1415 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 1416 |
+
last_hidden_state=sequence_output,
|
| 1417 |
+
pooler_output=pooled_output,
|
| 1418 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 1419 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1420 |
+
attentions=encoder_outputs.attentions,
|
| 1421 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 1422 |
+
)
|
| 1423 |
+
|
| 1424 |
+
|
| 1425 |
+
class AltCLIPTextModel(AltCLIPPreTrainedModel):
|
| 1426 |
+
config_class = AltCLIPTextConfig
|
| 1427 |
+
|
| 1428 |
+
def __init__(self, config):
|
| 1429 |
+
super().__init__(config)
|
| 1430 |
+
self.roberta = AltRobertaModel(config, add_pooling_layer=False)
|
| 1431 |
+
self.transformation = nn.Linear(config.hidden_size, config.project_dim)
|
| 1432 |
+
self.pre_LN = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 1433 |
+
self.post_init()
|
| 1434 |
+
|
| 1435 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1436 |
+
return self.roberta.embeddings.word_embeddings
|
| 1437 |
+
|
| 1438 |
+
def set_input_embeddings(self, value: nn.Embedding) -> None:
|
| 1439 |
+
self.roberta.embeddings.word_embeddings = value
|
| 1440 |
+
|
| 1441 |
+
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
|
| 1442 |
+
return super().resize_token_embeddings(new_num_tokens)
|
| 1443 |
+
|
| 1444 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_TEXT_INPUTS_DOCSTRING)
|
| 1445 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPoolingAndProjection, config_class=AltCLIPTextConfig)
|
| 1446 |
+
def forward(
|
| 1447 |
+
self,
|
| 1448 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1449 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1450 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1451 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1452 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1453 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1454 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1455 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1456 |
+
output_attentions: Optional[bool] = None,
|
| 1457 |
+
return_dict: Optional[bool] = None,
|
| 1458 |
+
output_hidden_states: Optional[bool] = None,
|
| 1459 |
+
) -> Union[Tuple, BaseModelOutputWithPoolingAndProjection]:
|
| 1460 |
+
r"""
|
| 1461 |
+
Returns:
|
| 1462 |
+
|
| 1463 |
+
Examples:
|
| 1464 |
+
|
| 1465 |
+
```python
|
| 1466 |
+
>>> from transformers import AutoProcessor, AltCLIPTextModel
|
| 1467 |
+
|
| 1468 |
+
>>> model = AltCLIPTextModel.from_pretrained("BAAI/AltCLIP")
|
| 1469 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1470 |
+
|
| 1471 |
+
>>> texts = ["it's a cat", "it's a dog"]
|
| 1472 |
+
|
| 1473 |
+
>>> inputs = processor(text=texts, padding=True, return_tensors="pt")
|
| 1474 |
+
|
| 1475 |
+
>>> outputs = model(**inputs)
|
| 1476 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 1477 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 1478 |
+
```"""
|
| 1479 |
+
|
| 1480 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1481 |
+
|
| 1482 |
+
outputs = self.roberta(
|
| 1483 |
+
input_ids=input_ids,
|
| 1484 |
+
attention_mask=attention_mask,
|
| 1485 |
+
token_type_ids=token_type_ids,
|
| 1486 |
+
position_ids=position_ids,
|
| 1487 |
+
head_mask=head_mask,
|
| 1488 |
+
inputs_embeds=inputs_embeds,
|
| 1489 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1490 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1491 |
+
output_attentions=output_attentions,
|
| 1492 |
+
output_hidden_states=output_hidden_states,
|
| 1493 |
+
return_dict=return_dict,
|
| 1494 |
+
)
|
| 1495 |
+
|
| 1496 |
+
# last module outputs
|
| 1497 |
+
sequence_output = outputs[0]
|
| 1498 |
+
|
| 1499 |
+
# project every module
|
| 1500 |
+
sequence_output = self.pre_LN(sequence_output)
|
| 1501 |
+
|
| 1502 |
+
# pooler
|
| 1503 |
+
projection_state = self.transformation(sequence_output)
|
| 1504 |
+
pooler_output = projection_state[:, 0]
|
| 1505 |
+
|
| 1506 |
+
if not return_dict:
|
| 1507 |
+
return (projection_state, pooler_output) + outputs[2:4]
|
| 1508 |
+
|
| 1509 |
+
return BaseModelOutputWithPoolingAndProjection(
|
| 1510 |
+
last_hidden_state=projection_state,
|
| 1511 |
+
pooler_output=pooler_output,
|
| 1512 |
+
hidden_states=outputs.hidden_states,
|
| 1513 |
+
attentions=outputs.attentions,
|
| 1514 |
+
)
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
class AltCLIPModel(AltCLIPPreTrainedModel):
|
| 1518 |
+
config_class = AltCLIPConfig
|
| 1519 |
+
|
| 1520 |
+
def __init__(self, config: AltCLIPConfig):
|
| 1521 |
+
super().__init__(config)
|
| 1522 |
+
|
| 1523 |
+
if not isinstance(config.vision_config, AltCLIPVisionConfig):
|
| 1524 |
+
raise TypeError(
|
| 1525 |
+
"config.vision_config is expected to be of type AltCLIPVisionConfig but is of type"
|
| 1526 |
+
f" {type(config.vision_config)}."
|
| 1527 |
+
)
|
| 1528 |
+
if not isinstance(config.text_config, AltCLIPTextConfig):
|
| 1529 |
+
raise TypeError(
|
| 1530 |
+
"config.text_config is expected to be of type AltCLIPTextConfig but is of type"
|
| 1531 |
+
f" {type(config.text_config)}."
|
| 1532 |
+
)
|
| 1533 |
+
|
| 1534 |
+
text_config = config.text_config
|
| 1535 |
+
vision_config = config.vision_config
|
| 1536 |
+
|
| 1537 |
+
self.projection_dim = config.projection_dim
|
| 1538 |
+
self.text_embed_dim = text_config.project_dim
|
| 1539 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 1540 |
+
|
| 1541 |
+
self.text_model = AltCLIPTextModel(text_config)
|
| 1542 |
+
self.vision_model = AltCLIPVisionTransformer(vision_config)
|
| 1543 |
+
|
| 1544 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
| 1545 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
| 1546 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
| 1547 |
+
|
| 1548 |
+
# Initialize weights and apply final processing
|
| 1549 |
+
self.post_init()
|
| 1550 |
+
|
| 1551 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_TEXT_INPUTS_DOCSTRING)
|
| 1552 |
+
def get_text_features(
|
| 1553 |
+
self,
|
| 1554 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1555 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1556 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1557 |
+
token_type_ids=None,
|
| 1558 |
+
output_attentions: Optional[bool] = None,
|
| 1559 |
+
output_hidden_states: Optional[bool] = None,
|
| 1560 |
+
return_dict: Optional[bool] = None,
|
| 1561 |
+
) -> torch.FloatTensor:
|
| 1562 |
+
r"""
|
| 1563 |
+
Returns:
|
| 1564 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1565 |
+
applying the projection layer to the pooled output of [`AltCLIPTextModel`].
|
| 1566 |
+
|
| 1567 |
+
Examples:
|
| 1568 |
+
|
| 1569 |
+
```python
|
| 1570 |
+
>>> from transformers import AutoProcessor, AltCLIPModel
|
| 1571 |
+
|
| 1572 |
+
>>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
|
| 1573 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1574 |
+
>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1575 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1576 |
+
```"""
|
| 1577 |
+
# Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1578 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1579 |
+
output_hidden_states = (
|
| 1580 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1581 |
+
)
|
| 1582 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1583 |
+
|
| 1584 |
+
text_outputs = self.text_model(
|
| 1585 |
+
input_ids=input_ids,
|
| 1586 |
+
attention_mask=attention_mask,
|
| 1587 |
+
position_ids=position_ids,
|
| 1588 |
+
token_type_ids=token_type_ids,
|
| 1589 |
+
output_attentions=output_attentions,
|
| 1590 |
+
output_hidden_states=output_hidden_states,
|
| 1591 |
+
return_dict=return_dict,
|
| 1592 |
+
)
|
| 1593 |
+
pooled_output = text_outputs[1]
|
| 1594 |
+
text_features = self.text_projection(pooled_output)
|
| 1595 |
+
|
| 1596 |
+
return text_features
|
| 1597 |
+
|
| 1598 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_VISION_INPUTS_DOCSTRING)
|
| 1599 |
+
def get_image_features(
|
| 1600 |
+
self,
|
| 1601 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1602 |
+
output_attentions: Optional[bool] = None,
|
| 1603 |
+
output_hidden_states: Optional[bool] = None,
|
| 1604 |
+
interpolate_pos_encoding: bool = False,
|
| 1605 |
+
return_dict: Optional[bool] = None,
|
| 1606 |
+
) -> torch.FloatTensor:
|
| 1607 |
+
r"""
|
| 1608 |
+
Returns:
|
| 1609 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1610 |
+
applying the projection layer to the pooled output of [`AltCLIPVisionModel`].
|
| 1611 |
+
|
| 1612 |
+
Examples:
|
| 1613 |
+
|
| 1614 |
+
```python
|
| 1615 |
+
>>> from PIL import Image
|
| 1616 |
+
>>> import requests
|
| 1617 |
+
>>> from transformers import AutoProcessor, AltCLIPModel
|
| 1618 |
+
|
| 1619 |
+
>>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
|
| 1620 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1621 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1622 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1623 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1624 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1625 |
+
```"""
|
| 1626 |
+
# Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1627 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1628 |
+
output_hidden_states = (
|
| 1629 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1630 |
+
)
|
| 1631 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1632 |
+
|
| 1633 |
+
vision_outputs = self.vision_model(
|
| 1634 |
+
pixel_values=pixel_values,
|
| 1635 |
+
output_attentions=output_attentions,
|
| 1636 |
+
output_hidden_states=output_hidden_states,
|
| 1637 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1638 |
+
return_dict=return_dict,
|
| 1639 |
+
)
|
| 1640 |
+
|
| 1641 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1642 |
+
image_features = self.visual_projection(pooled_output)
|
| 1643 |
+
|
| 1644 |
+
return image_features
|
| 1645 |
+
|
| 1646 |
+
@add_start_docstrings_to_model_forward(ALTCLIP_INPUTS_DOCSTRING)
|
| 1647 |
+
@replace_return_docstrings(output_type=AltCLIPOutput, config_class=AltCLIPConfig)
|
| 1648 |
+
def forward(
|
| 1649 |
+
self,
|
| 1650 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1651 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1652 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1653 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1654 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1655 |
+
return_loss: Optional[bool] = None,
|
| 1656 |
+
output_attentions: Optional[bool] = None,
|
| 1657 |
+
output_hidden_states: Optional[bool] = None,
|
| 1658 |
+
interpolate_pos_encoding: bool = False,
|
| 1659 |
+
return_dict: Optional[bool] = None,
|
| 1660 |
+
) -> Union[Tuple, AltCLIPOutput]:
|
| 1661 |
+
r"""
|
| 1662 |
+
Returns:
|
| 1663 |
+
|
| 1664 |
+
Examples:
|
| 1665 |
+
|
| 1666 |
+
```python
|
| 1667 |
+
>>> from PIL import Image
|
| 1668 |
+
>>> import requests
|
| 1669 |
+
>>> from transformers import AutoProcessor, AltCLIPModel
|
| 1670 |
+
|
| 1671 |
+
>>> model = AltCLIPModel.from_pretrained("BAAI/AltCLIP")
|
| 1672 |
+
>>> processor = AutoProcessor.from_pretrained("BAAI/AltCLIP")
|
| 1673 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1674 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1675 |
+
>>> inputs = processor(
|
| 1676 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
| 1677 |
+
... )
|
| 1678 |
+
>>> outputs = model(**inputs)
|
| 1679 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 1680 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1681 |
+
```"""
|
| 1682 |
+
# Use AltCLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1683 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1684 |
+
output_hidden_states = (
|
| 1685 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1686 |
+
)
|
| 1687 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1688 |
+
|
| 1689 |
+
text_outputs = self.text_model(
|
| 1690 |
+
input_ids=input_ids,
|
| 1691 |
+
attention_mask=attention_mask,
|
| 1692 |
+
token_type_ids=token_type_ids,
|
| 1693 |
+
position_ids=position_ids,
|
| 1694 |
+
output_attentions=output_attentions,
|
| 1695 |
+
output_hidden_states=output_hidden_states,
|
| 1696 |
+
return_dict=return_dict,
|
| 1697 |
+
)
|
| 1698 |
+
|
| 1699 |
+
vision_outputs = self.vision_model(
|
| 1700 |
+
pixel_values=pixel_values,
|
| 1701 |
+
output_attentions=output_attentions,
|
| 1702 |
+
output_hidden_states=output_hidden_states,
|
| 1703 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1704 |
+
return_dict=return_dict,
|
| 1705 |
+
)
|
| 1706 |
+
|
| 1707 |
+
image_embeds = vision_outputs[1]
|
| 1708 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 1709 |
+
|
| 1710 |
+
text_embeds = text_outputs[1]
|
| 1711 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1712 |
+
|
| 1713 |
+
# normalized features
|
| 1714 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1715 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1716 |
+
|
| 1717 |
+
# cosine similarity as logits
|
| 1718 |
+
logit_scale = self.logit_scale.exp()
|
| 1719 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
| 1720 |
+
logits_per_image = logits_per_text.T
|
| 1721 |
+
|
| 1722 |
+
loss = None
|
| 1723 |
+
if return_loss:
|
| 1724 |
+
loss = clip_loss(logits_per_text)
|
| 1725 |
+
|
| 1726 |
+
if not return_dict:
|
| 1727 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1728 |
+
return ((loss,) + output) if loss is not None else output
|
| 1729 |
+
|
| 1730 |
+
return AltCLIPOutput(
|
| 1731 |
+
loss=loss,
|
| 1732 |
+
logits_per_image=logits_per_image,
|
| 1733 |
+
logits_per_text=logits_per_text,
|
| 1734 |
+
text_embeds=text_embeds,
|
| 1735 |
+
image_embeds=image_embeds,
|
| 1736 |
+
text_model_output=text_outputs,
|
| 1737 |
+
vision_model_output=vision_outputs,
|
| 1738 |
+
)
|
| 1739 |
+
|
| 1740 |
+
|
| 1741 |
+
# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
|
| 1742 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
| 1743 |
+
"""
|
| 1744 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
| 1745 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
| 1746 |
+
|
| 1747 |
+
Args:
|
| 1748 |
+
x: torch.Tensor x:
|
| 1749 |
+
|
| 1750 |
+
Returns: torch.Tensor
|
| 1751 |
+
"""
|
| 1752 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
| 1753 |
+
mask = input_ids.ne(padding_idx).int()
|
| 1754 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
| 1755 |
+
return incremental_indices.long() + padding_idx
|
| 1756 |
+
|
| 1757 |
+
|
| 1758 |
+
__all__ = ["AltCLIPPreTrainedModel", "AltCLIPVisionModel", "AltCLIPTextModel", "AltCLIPModel"]
|
lib/python3.12/site-packages/transformers/models/altclip/processing_altclip.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Image/Text processor class for AltCLIP
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import List, Union
|
| 20 |
+
|
| 21 |
+
from ...image_utils import ImageInput
|
| 22 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 23 |
+
from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
|
| 24 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class AltClipProcessorKwargs(ProcessingKwargs, total=False):
|
| 28 |
+
_defaults = {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class AltCLIPProcessor(ProcessorMixin):
|
| 32 |
+
r"""
|
| 33 |
+
Constructs a AltCLIP processor which wraps a CLIP image processor and a XLM-Roberta tokenizer into a single
|
| 34 |
+
processor.
|
| 35 |
+
|
| 36 |
+
[`AltCLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`XLMRobertaTokenizerFast`]. See
|
| 37 |
+
the [`~AltCLIPProcessor.__call__`] and [`~AltCLIPProcessor.decode`] for more information.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
image_processor ([`CLIPImageProcessor`], *optional*):
|
| 41 |
+
The image processor is a required input.
|
| 42 |
+
tokenizer ([`XLMRobertaTokenizerFast`], *optional*):
|
| 43 |
+
The tokenizer is a required input.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
attributes = ["image_processor", "tokenizer"]
|
| 47 |
+
image_processor_class = ("CLIPImageProcessor", "CLIPImageProcessorFast")
|
| 48 |
+
tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
|
| 49 |
+
|
| 50 |
+
@deprecate_kwarg(old_name="feature_extractor", version="5.0.0", new_name="image_processor")
|
| 51 |
+
def __init__(self, image_processor=None, tokenizer=None):
|
| 52 |
+
if image_processor is None:
|
| 53 |
+
raise ValueError("You need to specify an `image_processor`.")
|
| 54 |
+
if tokenizer is None:
|
| 55 |
+
raise ValueError("You need to specify a `tokenizer`.")
|
| 56 |
+
|
| 57 |
+
super().__init__(image_processor, tokenizer)
|
| 58 |
+
|
| 59 |
+
def __call__(
|
| 60 |
+
self,
|
| 61 |
+
images: ImageInput = None,
|
| 62 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
| 63 |
+
audio=None,
|
| 64 |
+
videos=None,
|
| 65 |
+
**kwargs: Unpack[AltClipProcessorKwargs],
|
| 66 |
+
) -> BatchEncoding:
|
| 67 |
+
"""
|
| 68 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 69 |
+
and `kwargs` arguments to XLMRobertaTokenizerFast's [`~XLMRobertaTokenizerFast.__call__`] if `text` is not
|
| 70 |
+
`None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
|
| 71 |
+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
|
| 72 |
+
of the above two methods for more information.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
|
| 76 |
+
images (`ImageInput`):
|
| 77 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 78 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 79 |
+
text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
|
| 80 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 81 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 82 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 83 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 84 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 85 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 86 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 87 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 88 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 89 |
+
Returns:
|
| 90 |
+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
|
| 91 |
+
|
| 92 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 93 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 94 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 95 |
+
`None`).
|
| 96 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
if text is None and images is None:
|
| 100 |
+
raise ValueError("You must specify either text or images.")
|
| 101 |
+
|
| 102 |
+
if text is None and images is None:
|
| 103 |
+
raise ValueError("You must specify either text or images.")
|
| 104 |
+
output_kwargs = self._merge_kwargs(
|
| 105 |
+
AltClipProcessorKwargs,
|
| 106 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 107 |
+
**kwargs,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if text is not None:
|
| 111 |
+
encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 112 |
+
if images is not None:
|
| 113 |
+
image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 114 |
+
|
| 115 |
+
# BC for explicit return_tensors
|
| 116 |
+
if "return_tensors" in output_kwargs["common_kwargs"]:
|
| 117 |
+
return_tensors = output_kwargs["common_kwargs"].pop("return_tensors", None)
|
| 118 |
+
|
| 119 |
+
if text is not None and images is not None:
|
| 120 |
+
encoding["pixel_values"] = image_features.pixel_values
|
| 121 |
+
return encoding
|
| 122 |
+
elif text is not None:
|
| 123 |
+
return encoding
|
| 124 |
+
else:
|
| 125 |
+
return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
|
| 126 |
+
|
| 127 |
+
def batch_decode(self, *args, **kwargs):
|
| 128 |
+
"""
|
| 129 |
+
This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`].
|
| 130 |
+
Please refer to the docstring of this method for more information.
|
| 131 |
+
"""
|
| 132 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 133 |
+
|
| 134 |
+
def decode(self, *args, **kwargs):
|
| 135 |
+
"""
|
| 136 |
+
This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please
|
| 137 |
+
refer to the docstring of this method for more information.
|
| 138 |
+
"""
|
| 139 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def model_input_names(self):
|
| 143 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 144 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 145 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
__all__ = ["AltCLIPProcessor"]
|
lib/python3.12/site-packages/transformers/models/beit/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_beit import *
|
| 22 |
+
from .feature_extraction_beit import *
|
| 23 |
+
from .image_processing_beit import *
|
| 24 |
+
from .modeling_beit import *
|
| 25 |
+
from .modeling_flax_beit import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/beit/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (768 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-312.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/beit/__pycache__/feature_extraction_beit.cpython-312.pyc
ADDED
|
Binary file (1.2 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-312.pyc
ADDED
|
Binary file (22.5 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-312.pyc
ADDED
|
Binary file (82.9 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_flax_beit.cpython-312.pyc
ADDED
|
Binary file (46.2 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/beit/configuration_beit.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""BEiT model configuration"""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import Mapping
|
| 20 |
+
|
| 21 |
+
from packaging import version
|
| 22 |
+
|
| 23 |
+
from ...configuration_utils import PretrainedConfig
|
| 24 |
+
from ...onnx import OnnxConfig
|
| 25 |
+
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class BeitConfig(BackboneConfigMixin, PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`BeitModel`]. It is used to instantiate an BEiT
|
| 31 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 32 |
+
defaults will yield a similar configuration to that of the BEiT
|
| 33 |
+
[microsoft/beit-base-patch16-224-pt22k](https://huggingface.co/microsoft/beit-base-patch16-224-pt22k) architecture.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
vocab_size (`int`, *optional*, defaults to 8192):
|
| 37 |
+
Vocabulary size of the BEiT model. Defines the number of different image tokens that can be used during
|
| 38 |
+
pre-training.
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 42 |
+
Number of hidden layers in the Transformer encoder.
|
| 43 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 44 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 45 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 46 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 47 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 48 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 49 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
| 50 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 51 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 52 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 55 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 56 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 57 |
+
The epsilon used by the layer normalization layers.
|
| 58 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 59 |
+
The size (resolution) of each image.
|
| 60 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 61 |
+
The size (resolution) of each patch.
|
| 62 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 63 |
+
The number of input channels.
|
| 64 |
+
use_mask_token (`bool`, *optional*, defaults to `False`):
|
| 65 |
+
Whether to use a mask token for masked image modeling.
|
| 66 |
+
use_absolute_position_embeddings (`bool`, *optional*, defaults to `False`):
|
| 67 |
+
Whether to use BERT-style absolute position embeddings.
|
| 68 |
+
use_relative_position_bias (`bool`, *optional*, defaults to `False`):
|
| 69 |
+
Whether to use T5-style relative position embeddings in the self-attention layers.
|
| 70 |
+
use_shared_relative_position_bias (`bool`, *optional*, defaults to `False`):
|
| 71 |
+
Whether to use the same relative position embeddings across all self-attention layers of the Transformer.
|
| 72 |
+
layer_scale_init_value (`float`, *optional*, defaults to 0.1):
|
| 73 |
+
Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale.
|
| 74 |
+
drop_path_rate (`float`, *optional*, defaults to 0.1):
|
| 75 |
+
Stochastic depth rate per sample (when applied in the main path of residual layers).
|
| 76 |
+
use_mean_pooling (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
|
| 78 |
+
CLS token, before applying the classification head.
|
| 79 |
+
pool_scales (`Tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
|
| 80 |
+
Pooling scales used in Pooling Pyramid Module applied on the last feature map.
|
| 81 |
+
use_auxiliary_head (`bool`, *optional*, defaults to `True`):
|
| 82 |
+
Whether to use an auxiliary head during training.
|
| 83 |
+
auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
|
| 84 |
+
Weight of the cross-entropy loss of the auxiliary head.
|
| 85 |
+
auxiliary_channels (`int`, *optional*, defaults to 256):
|
| 86 |
+
Number of channels to use in the auxiliary head.
|
| 87 |
+
auxiliary_num_convs (`int`, *optional*, defaults to 1):
|
| 88 |
+
Number of convolutional layers to use in the auxiliary head.
|
| 89 |
+
auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
|
| 90 |
+
Whether to concatenate the output of the auxiliary head with the input before the classification layer.
|
| 91 |
+
semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
|
| 92 |
+
The index that is ignored by the loss function of the semantic segmentation model.
|
| 93 |
+
out_features (`List[str]`, *optional*):
|
| 94 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 95 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 96 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 97 |
+
same order as defined in the `stage_names` attribute.
|
| 98 |
+
out_indices (`List[int]`, *optional*):
|
| 99 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 100 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 101 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 102 |
+
same order as defined in the `stage_names` attribute.
|
| 103 |
+
add_fpn (`bool`, *optional*, defaults to `False`):
|
| 104 |
+
Whether to add a FPN as part of the backbone. Only relevant for [`BeitBackbone`].
|
| 105 |
+
reshape_hidden_states (`bool`, *optional*, defaults to `True`):
|
| 106 |
+
Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
|
| 107 |
+
case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
|
| 108 |
+
seq_len, hidden_size)`. Only relevant for [`BeitBackbone`].
|
| 109 |
+
|
| 110 |
+
Example:
|
| 111 |
+
|
| 112 |
+
```python
|
| 113 |
+
>>> from transformers import BeitConfig, BeitModel
|
| 114 |
+
|
| 115 |
+
>>> # Initializing a BEiT beit-base-patch16-224-pt22k style configuration
|
| 116 |
+
>>> configuration = BeitConfig()
|
| 117 |
+
|
| 118 |
+
>>> # Initializing a model (with random weights) from the beit-base-patch16-224-pt22k style configuration
|
| 119 |
+
>>> model = BeitModel(configuration)
|
| 120 |
+
|
| 121 |
+
>>> # Accessing the model configuration
|
| 122 |
+
>>> configuration = model.config
|
| 123 |
+
```"""
|
| 124 |
+
|
| 125 |
+
model_type = "beit"
|
| 126 |
+
|
| 127 |
+
def __init__(
|
| 128 |
+
self,
|
| 129 |
+
vocab_size=8192,
|
| 130 |
+
hidden_size=768,
|
| 131 |
+
num_hidden_layers=12,
|
| 132 |
+
num_attention_heads=12,
|
| 133 |
+
intermediate_size=3072,
|
| 134 |
+
hidden_act="gelu",
|
| 135 |
+
hidden_dropout_prob=0.0,
|
| 136 |
+
attention_probs_dropout_prob=0.0,
|
| 137 |
+
initializer_range=0.02,
|
| 138 |
+
layer_norm_eps=1e-12,
|
| 139 |
+
image_size=224,
|
| 140 |
+
patch_size=16,
|
| 141 |
+
num_channels=3,
|
| 142 |
+
use_mask_token=False,
|
| 143 |
+
use_absolute_position_embeddings=False,
|
| 144 |
+
use_relative_position_bias=False,
|
| 145 |
+
use_shared_relative_position_bias=False,
|
| 146 |
+
layer_scale_init_value=0.1,
|
| 147 |
+
drop_path_rate=0.1,
|
| 148 |
+
use_mean_pooling=True,
|
| 149 |
+
pool_scales=[1, 2, 3, 6],
|
| 150 |
+
use_auxiliary_head=True,
|
| 151 |
+
auxiliary_loss_weight=0.4,
|
| 152 |
+
auxiliary_channels=256,
|
| 153 |
+
auxiliary_num_convs=1,
|
| 154 |
+
auxiliary_concat_input=False,
|
| 155 |
+
semantic_loss_ignore_index=255,
|
| 156 |
+
out_features=None,
|
| 157 |
+
out_indices=None,
|
| 158 |
+
add_fpn=False,
|
| 159 |
+
reshape_hidden_states=True,
|
| 160 |
+
**kwargs,
|
| 161 |
+
):
|
| 162 |
+
super().__init__(**kwargs)
|
| 163 |
+
|
| 164 |
+
self.vocab_size = vocab_size
|
| 165 |
+
self.hidden_size = hidden_size
|
| 166 |
+
self.num_hidden_layers = num_hidden_layers
|
| 167 |
+
self.num_attention_heads = num_attention_heads
|
| 168 |
+
self.intermediate_size = intermediate_size
|
| 169 |
+
self.hidden_act = hidden_act
|
| 170 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 171 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 172 |
+
self.initializer_range = initializer_range
|
| 173 |
+
self.layer_norm_eps = layer_norm_eps
|
| 174 |
+
|
| 175 |
+
self.image_size = image_size
|
| 176 |
+
self.patch_size = patch_size
|
| 177 |
+
self.num_channels = num_channels
|
| 178 |
+
self.use_mask_token = use_mask_token
|
| 179 |
+
self.use_absolute_position_embeddings = use_absolute_position_embeddings
|
| 180 |
+
self.use_relative_position_bias = use_relative_position_bias
|
| 181 |
+
self.use_shared_relative_position_bias = use_shared_relative_position_bias
|
| 182 |
+
self.layer_scale_init_value = layer_scale_init_value
|
| 183 |
+
self.drop_path_rate = drop_path_rate
|
| 184 |
+
self.use_mean_pooling = use_mean_pooling
|
| 185 |
+
# decode head attributes (semantic segmentation)
|
| 186 |
+
self.pool_scales = pool_scales
|
| 187 |
+
# auxiliary head attributes (semantic segmentation)
|
| 188 |
+
self.use_auxiliary_head = use_auxiliary_head
|
| 189 |
+
self.auxiliary_loss_weight = auxiliary_loss_weight
|
| 190 |
+
self.auxiliary_channels = auxiliary_channels
|
| 191 |
+
self.auxiliary_num_convs = auxiliary_num_convs
|
| 192 |
+
self.auxiliary_concat_input = auxiliary_concat_input
|
| 193 |
+
self.semantic_loss_ignore_index = semantic_loss_ignore_index
|
| 194 |
+
|
| 195 |
+
# handle backwards compatibility
|
| 196 |
+
if "segmentation_indices" in kwargs:
|
| 197 |
+
warnings.warn(
|
| 198 |
+
"The `segmentation_indices` argument is deprecated and will be removed in a future version, use `out_indices` instead.",
|
| 199 |
+
FutureWarning,
|
| 200 |
+
)
|
| 201 |
+
out_indices = kwargs.pop("segmentation_indices")
|
| 202 |
+
|
| 203 |
+
# backbone attributes
|
| 204 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, self.num_hidden_layers + 1)]
|
| 205 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 206 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 207 |
+
)
|
| 208 |
+
self.add_fpn = add_fpn
|
| 209 |
+
self.reshape_hidden_states = reshape_hidden_states
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
# Copied from transformers.models.vit.configuration_vit.ViTOnnxConfig
|
| 213 |
+
class BeitOnnxConfig(OnnxConfig):
|
| 214 |
+
torch_onnx_minimum_version = version.parse("1.11")
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 218 |
+
return OrderedDict(
|
| 219 |
+
[
|
| 220 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
| 221 |
+
]
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
@property
|
| 225 |
+
def atol_for_validation(self) -> float:
|
| 226 |
+
return 1e-4
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
__all__ = ["BeitConfig", "BeitOnnxConfig"]
|
lib/python3.12/site-packages/transformers/models/beit/feature_extraction_beit.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 BEiT."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from ...utils import logging
|
| 20 |
+
from .image_processing_beit import BeitImageProcessor
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class BeitFeatureExtractor(BeitImageProcessor):
|
| 27 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
|
| 30 |
+
" use BeitImageProcessor instead.",
|
| 31 |
+
FutureWarning,
|
| 32 |
+
)
|
| 33 |
+
super().__init__(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
__all__ = ["BeitFeatureExtractor"]
|
lib/python3.12/site-packages/transformers/models/beit/image_processing_beit.py
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 Beit."""
|
| 16 |
+
|
| 17 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import INIT_SERVICE_KWARGS, BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ...image_transforms import resize, to_channel_dimension_format
|
| 23 |
+
from ...image_utils import (
|
| 24 |
+
IMAGENET_STANDARD_MEAN,
|
| 25 |
+
IMAGENET_STANDARD_STD,
|
| 26 |
+
ChannelDimension,
|
| 27 |
+
ImageInput,
|
| 28 |
+
PILImageResampling,
|
| 29 |
+
infer_channel_dimension_format,
|
| 30 |
+
is_scaled_image,
|
| 31 |
+
make_list_of_images,
|
| 32 |
+
to_numpy_array,
|
| 33 |
+
valid_images,
|
| 34 |
+
validate_preprocess_arguments,
|
| 35 |
+
)
|
| 36 |
+
from ...utils import (
|
| 37 |
+
TensorType,
|
| 38 |
+
filter_out_non_signature_kwargs,
|
| 39 |
+
is_torch_available,
|
| 40 |
+
is_torch_tensor,
|
| 41 |
+
is_vision_available,
|
| 42 |
+
logging,
|
| 43 |
+
)
|
| 44 |
+
from ...utils.deprecation import deprecate_kwarg
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if is_vision_available():
|
| 48 |
+
import PIL
|
| 49 |
+
|
| 50 |
+
if is_torch_available():
|
| 51 |
+
import torch
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
logger = logging.get_logger(__name__)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class BeitImageProcessor(BaseImageProcessor):
|
| 58 |
+
r"""
|
| 59 |
+
Constructs a BEiT image processor.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
|
| 64 |
+
`do_resize` parameter in the `preprocess` method.
|
| 65 |
+
size (`Dict[str, int]` *optional*, defaults to `{"height": 256, "width": 256}`):
|
| 66 |
+
Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
|
| 67 |
+
method.
|
| 68 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 69 |
+
Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
|
| 70 |
+
`preprocess` method.
|
| 71 |
+
do_center_crop (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the image
|
| 73 |
+
is padded with 0's and then center cropped. Can be overridden by the `do_center_crop` parameter in the
|
| 74 |
+
`preprocess` method.
|
| 75 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
|
| 76 |
+
Desired output size when applying center-cropping. Only has an effect if `do_center_crop` is set to `True`.
|
| 77 |
+
Can be overridden by the `crop_size` parameter in the `preprocess` method.
|
| 78 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 79 |
+
Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
|
| 80 |
+
`preprocess` method.
|
| 81 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 82 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
| 83 |
+
parameter in the `preprocess` method.
|
| 84 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 85 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
| 86 |
+
method.
|
| 87 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 88 |
+
The mean to use if normalizing the image. This is a float or list of floats of length of the number of
|
| 89 |
+
channels of the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
| 90 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 91 |
+
The standard deviation to use if normalizing the image. This is a float or list of floats of length of the
|
| 92 |
+
number of channels of the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 93 |
+
do_reduce_labels (`bool`, *optional*, defaults to `False`):
|
| 94 |
+
Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is
|
| 95 |
+
used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The
|
| 96 |
+
background label will be replaced by 255. Can be overridden by the `do_reduce_labels` parameter in the
|
| 97 |
+
`preprocess` method.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
model_input_names = ["pixel_values"]
|
| 101 |
+
|
| 102 |
+
@deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="4.41.0")
|
| 103 |
+
@filter_out_non_signature_kwargs(extra=INIT_SERVICE_KWARGS)
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
do_resize: bool = True,
|
| 107 |
+
size: Dict[str, int] = None,
|
| 108 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 109 |
+
do_center_crop: bool = True,
|
| 110 |
+
crop_size: Dict[str, int] = None,
|
| 111 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 112 |
+
do_rescale: bool = True,
|
| 113 |
+
do_normalize: bool = True,
|
| 114 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 115 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 116 |
+
do_reduce_labels: bool = False,
|
| 117 |
+
**kwargs,
|
| 118 |
+
) -> None:
|
| 119 |
+
super().__init__(**kwargs)
|
| 120 |
+
size = size if size is not None else {"height": 256, "width": 256}
|
| 121 |
+
size = get_size_dict(size)
|
| 122 |
+
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
|
| 123 |
+
crop_size = get_size_dict(crop_size, param_name="crop_size")
|
| 124 |
+
self.do_resize = do_resize
|
| 125 |
+
self.size = size
|
| 126 |
+
self.resample = resample
|
| 127 |
+
self.do_center_crop = do_center_crop
|
| 128 |
+
self.crop_size = crop_size
|
| 129 |
+
self.do_rescale = do_rescale
|
| 130 |
+
self.rescale_factor = rescale_factor
|
| 131 |
+
self.do_normalize = do_normalize
|
| 132 |
+
self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
| 133 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
| 134 |
+
self.do_reduce_labels = do_reduce_labels
|
| 135 |
+
|
| 136 |
+
@classmethod
|
| 137 |
+
def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
|
| 138 |
+
"""
|
| 139 |
+
Overrides the `from_dict` method from the base class to save support of deprecated `reduce_labels` in old configs
|
| 140 |
+
"""
|
| 141 |
+
image_processor_dict = image_processor_dict.copy()
|
| 142 |
+
if "reduce_labels" in image_processor_dict:
|
| 143 |
+
image_processor_dict["do_reduce_labels"] = image_processor_dict.pop("reduce_labels")
|
| 144 |
+
return super().from_dict(image_processor_dict, **kwargs)
|
| 145 |
+
|
| 146 |
+
def resize(
|
| 147 |
+
self,
|
| 148 |
+
image: np.ndarray,
|
| 149 |
+
size: Dict[str, int],
|
| 150 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 151 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 152 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 153 |
+
**kwargs,
|
| 154 |
+
) -> np.ndarray:
|
| 155 |
+
"""
|
| 156 |
+
Resize an image to (size["height"], size["width"]).
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
image (`np.ndarray`):
|
| 160 |
+
Image to resize.
|
| 161 |
+
size (`Dict[str, int]`):
|
| 162 |
+
Size of the output image.
|
| 163 |
+
resample (`PILImageResampling`, *optional*, defaults to `PIL.Image.BICUBIC`):
|
| 164 |
+
Resampling filter to use when resiizing the image.
|
| 165 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
| 166 |
+
The channel dimension format of the image. If not provided, it will be the same as the input image.
|
| 167 |
+
input_data_format (`str` or `ChannelDimension`, *optional*):
|
| 168 |
+
The channel dimension format of the input image. If not provided, it will be inferred.
|
| 169 |
+
"""
|
| 170 |
+
size = get_size_dict(size, default_to_square=True, param_name="size")
|
| 171 |
+
if "height" not in size or "width" not in size:
|
| 172 |
+
raise ValueError(f"The `size` argument must contain `height` and `width` keys. Got {size.keys()}")
|
| 173 |
+
return resize(
|
| 174 |
+
image,
|
| 175 |
+
size=(size["height"], size["width"]),
|
| 176 |
+
resample=resample,
|
| 177 |
+
data_format=data_format,
|
| 178 |
+
input_data_format=input_data_format,
|
| 179 |
+
**kwargs,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def reduce_label(self, label: ImageInput) -> np.ndarray:
|
| 183 |
+
label = to_numpy_array(label)
|
| 184 |
+
# Avoid using underflow conversion
|
| 185 |
+
label[label == 0] = 255
|
| 186 |
+
label = label - 1
|
| 187 |
+
label[label == 254] = 255
|
| 188 |
+
return label
|
| 189 |
+
|
| 190 |
+
def _preprocess(
|
| 191 |
+
self,
|
| 192 |
+
image: ImageInput,
|
| 193 |
+
do_reduce_labels: Optional[bool] = None,
|
| 194 |
+
do_resize: Optional[bool] = None,
|
| 195 |
+
size: Dict[str, int] = None,
|
| 196 |
+
resample: PILImageResampling = None,
|
| 197 |
+
do_center_crop: Optional[bool] = None,
|
| 198 |
+
crop_size: Dict[str, int] = None,
|
| 199 |
+
do_rescale: Optional[bool] = None,
|
| 200 |
+
rescale_factor: Optional[float] = None,
|
| 201 |
+
do_normalize: Optional[bool] = None,
|
| 202 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 203 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 204 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 205 |
+
):
|
| 206 |
+
if do_reduce_labels:
|
| 207 |
+
image = self.reduce_label(image)
|
| 208 |
+
|
| 209 |
+
if do_resize:
|
| 210 |
+
image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 211 |
+
|
| 212 |
+
if do_center_crop:
|
| 213 |
+
image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
|
| 214 |
+
|
| 215 |
+
if do_rescale:
|
| 216 |
+
image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 217 |
+
|
| 218 |
+
if do_normalize:
|
| 219 |
+
image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 220 |
+
|
| 221 |
+
return image
|
| 222 |
+
|
| 223 |
+
def _preprocess_image(
|
| 224 |
+
self,
|
| 225 |
+
image: ImageInput,
|
| 226 |
+
do_resize: Optional[bool] = None,
|
| 227 |
+
size: Dict[str, int] = None,
|
| 228 |
+
resample: PILImageResampling = None,
|
| 229 |
+
do_center_crop: Optional[bool] = None,
|
| 230 |
+
crop_size: Dict[str, int] = None,
|
| 231 |
+
do_rescale: Optional[bool] = None,
|
| 232 |
+
rescale_factor: Optional[float] = None,
|
| 233 |
+
do_normalize: Optional[bool] = None,
|
| 234 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 235 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 236 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 237 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 238 |
+
) -> np.ndarray:
|
| 239 |
+
"""Preprocesses a single image."""
|
| 240 |
+
# All transformations expect numpy arrays.
|
| 241 |
+
image = to_numpy_array(image)
|
| 242 |
+
if do_rescale and is_scaled_image(image):
|
| 243 |
+
logger.warning_once(
|
| 244 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 245 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 246 |
+
)
|
| 247 |
+
if input_data_format is None:
|
| 248 |
+
input_data_format = infer_channel_dimension_format(image)
|
| 249 |
+
image = self._preprocess(
|
| 250 |
+
image,
|
| 251 |
+
do_reduce_labels=False,
|
| 252 |
+
do_resize=do_resize,
|
| 253 |
+
size=size,
|
| 254 |
+
resample=resample,
|
| 255 |
+
do_center_crop=do_center_crop,
|
| 256 |
+
crop_size=crop_size,
|
| 257 |
+
do_rescale=do_rescale,
|
| 258 |
+
rescale_factor=rescale_factor,
|
| 259 |
+
do_normalize=do_normalize,
|
| 260 |
+
image_mean=image_mean,
|
| 261 |
+
image_std=image_std,
|
| 262 |
+
input_data_format=input_data_format,
|
| 263 |
+
)
|
| 264 |
+
if data_format is not None:
|
| 265 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 266 |
+
return image
|
| 267 |
+
|
| 268 |
+
def _preprocess_segmentation_map(
|
| 269 |
+
self,
|
| 270 |
+
segmentation_map: ImageInput,
|
| 271 |
+
do_resize: Optional[bool] = None,
|
| 272 |
+
size: Dict[str, int] = None,
|
| 273 |
+
resample: PILImageResampling = None,
|
| 274 |
+
do_center_crop: Optional[bool] = None,
|
| 275 |
+
crop_size: Dict[str, int] = None,
|
| 276 |
+
do_reduce_labels: Optional[bool] = None,
|
| 277 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 278 |
+
):
|
| 279 |
+
"""Preprocesses a single segmentation map."""
|
| 280 |
+
# All transformations expect numpy arrays.
|
| 281 |
+
segmentation_map = to_numpy_array(segmentation_map)
|
| 282 |
+
# Add an axis to the segmentation maps for transformations.
|
| 283 |
+
if segmentation_map.ndim == 2:
|
| 284 |
+
segmentation_map = segmentation_map[None, ...]
|
| 285 |
+
added_dimension = True
|
| 286 |
+
input_data_format = ChannelDimension.FIRST
|
| 287 |
+
else:
|
| 288 |
+
added_dimension = False
|
| 289 |
+
if input_data_format is None:
|
| 290 |
+
input_data_format = infer_channel_dimension_format(segmentation_map, num_channels=1)
|
| 291 |
+
segmentation_map = self._preprocess(
|
| 292 |
+
image=segmentation_map,
|
| 293 |
+
do_reduce_labels=do_reduce_labels,
|
| 294 |
+
do_resize=do_resize,
|
| 295 |
+
resample=resample,
|
| 296 |
+
size=size,
|
| 297 |
+
do_center_crop=do_center_crop,
|
| 298 |
+
crop_size=crop_size,
|
| 299 |
+
do_normalize=False,
|
| 300 |
+
do_rescale=False,
|
| 301 |
+
input_data_format=ChannelDimension.FIRST,
|
| 302 |
+
)
|
| 303 |
+
# Remove extra axis if added
|
| 304 |
+
if added_dimension:
|
| 305 |
+
segmentation_map = np.squeeze(segmentation_map, axis=0)
|
| 306 |
+
segmentation_map = segmentation_map.astype(np.int64)
|
| 307 |
+
return segmentation_map
|
| 308 |
+
|
| 309 |
+
def __call__(self, images, segmentation_maps=None, **kwargs):
|
| 310 |
+
# Overrides the `__call__` method of the `Preprocessor` class such that the images and segmentation maps can both
|
| 311 |
+
# be passed in as positional arguments.
|
| 312 |
+
return super().__call__(images, segmentation_maps=segmentation_maps, **kwargs)
|
| 313 |
+
|
| 314 |
+
@deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="4.41.0")
|
| 315 |
+
@filter_out_non_signature_kwargs()
|
| 316 |
+
def preprocess(
|
| 317 |
+
self,
|
| 318 |
+
images: ImageInput,
|
| 319 |
+
segmentation_maps: Optional[ImageInput] = None,
|
| 320 |
+
do_resize: Optional[bool] = None,
|
| 321 |
+
size: Dict[str, int] = None,
|
| 322 |
+
resample: PILImageResampling = None,
|
| 323 |
+
do_center_crop: Optional[bool] = None,
|
| 324 |
+
crop_size: Dict[str, int] = None,
|
| 325 |
+
do_rescale: Optional[bool] = None,
|
| 326 |
+
rescale_factor: Optional[float] = None,
|
| 327 |
+
do_normalize: Optional[bool] = None,
|
| 328 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 329 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 330 |
+
do_reduce_labels: Optional[bool] = None,
|
| 331 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 332 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
| 333 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 334 |
+
) -> PIL.Image.Image:
|
| 335 |
+
"""
|
| 336 |
+
Preprocess an image or batch of images.
|
| 337 |
+
|
| 338 |
+
Args:
|
| 339 |
+
images (`ImageInput`):
|
| 340 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 341 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 342 |
+
segmentation_maps (`ImageInput`, *optional*)
|
| 343 |
+
Segmentation maps to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 344 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 345 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 346 |
+
Whether to resize the image.
|
| 347 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 348 |
+
Size of the image after resizing.
|
| 349 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 350 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
|
| 351 |
+
has an effect if `do_resize` is set to `True`.
|
| 352 |
+
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
|
| 353 |
+
Whether to center crop the image.
|
| 354 |
+
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
|
| 355 |
+
Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be
|
| 356 |
+
padded with zeros and then cropped
|
| 357 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 358 |
+
Whether to rescale the image values between [0 - 1].
|
| 359 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 360 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 361 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 362 |
+
Whether to normalize the image.
|
| 363 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 364 |
+
Image mean.
|
| 365 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 366 |
+
Image standard deviation.
|
| 367 |
+
do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
|
| 368 |
+
Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
|
| 369 |
+
is used for background, and background itself is not included in all classes of a dataset (e.g.
|
| 370 |
+
ADE20k). The background label will be replaced by 255.
|
| 371 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 372 |
+
The type of tensors to return. Can be one of:
|
| 373 |
+
- Unset: Return a list of `np.ndarray`.
|
| 374 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 375 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 376 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 377 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 378 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 379 |
+
The channel dimension format for the output image. Can be one of:
|
| 380 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 381 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 382 |
+
- Unset: Use the channel dimension format of the input image.
|
| 383 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 384 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 385 |
+
from the input image. Can be one of:
|
| 386 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 387 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 388 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 389 |
+
"""
|
| 390 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 391 |
+
size = size if size is not None else self.size
|
| 392 |
+
size = get_size_dict(size, default_to_square=True, param_name="size")
|
| 393 |
+
resample = resample if resample is not None else self.resample
|
| 394 |
+
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
|
| 395 |
+
crop_size = crop_size if crop_size is not None else self.crop_size
|
| 396 |
+
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
|
| 397 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 398 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 399 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 400 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 401 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 402 |
+
do_reduce_labels = do_reduce_labels if do_reduce_labels is not None else self.do_reduce_labels
|
| 403 |
+
|
| 404 |
+
images = make_list_of_images(images)
|
| 405 |
+
|
| 406 |
+
if segmentation_maps is not None:
|
| 407 |
+
segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)
|
| 408 |
+
|
| 409 |
+
if segmentation_maps is not None and not valid_images(segmentation_maps):
|
| 410 |
+
raise ValueError(
|
| 411 |
+
"Invalid segmentation_maps type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 412 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 413 |
+
)
|
| 414 |
+
if not valid_images(images):
|
| 415 |
+
raise ValueError(
|
| 416 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 417 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
validate_preprocess_arguments(
|
| 421 |
+
do_rescale=do_rescale,
|
| 422 |
+
rescale_factor=rescale_factor,
|
| 423 |
+
do_normalize=do_normalize,
|
| 424 |
+
image_mean=image_mean,
|
| 425 |
+
image_std=image_std,
|
| 426 |
+
do_center_crop=do_center_crop,
|
| 427 |
+
crop_size=crop_size,
|
| 428 |
+
do_resize=do_resize,
|
| 429 |
+
size=size,
|
| 430 |
+
resample=resample,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
images = [
|
| 434 |
+
self._preprocess_image(
|
| 435 |
+
image=img,
|
| 436 |
+
do_resize=do_resize,
|
| 437 |
+
do_center_crop=do_center_crop,
|
| 438 |
+
do_rescale=do_rescale,
|
| 439 |
+
do_normalize=do_normalize,
|
| 440 |
+
resample=resample,
|
| 441 |
+
size=size,
|
| 442 |
+
rescale_factor=rescale_factor,
|
| 443 |
+
crop_size=crop_size,
|
| 444 |
+
image_mean=image_mean,
|
| 445 |
+
image_std=image_std,
|
| 446 |
+
data_format=data_format,
|
| 447 |
+
input_data_format=input_data_format,
|
| 448 |
+
)
|
| 449 |
+
for img in images
|
| 450 |
+
]
|
| 451 |
+
|
| 452 |
+
data = {"pixel_values": images}
|
| 453 |
+
|
| 454 |
+
if segmentation_maps is not None:
|
| 455 |
+
segmentation_maps = [
|
| 456 |
+
self._preprocess_segmentation_map(
|
| 457 |
+
segmentation_map=segmentation_map,
|
| 458 |
+
do_reduce_labels=do_reduce_labels,
|
| 459 |
+
do_resize=do_resize,
|
| 460 |
+
resample=resample,
|
| 461 |
+
size=size,
|
| 462 |
+
do_center_crop=do_center_crop,
|
| 463 |
+
crop_size=crop_size,
|
| 464 |
+
)
|
| 465 |
+
for segmentation_map in segmentation_maps
|
| 466 |
+
]
|
| 467 |
+
data["labels"] = segmentation_maps
|
| 468 |
+
|
| 469 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
| 470 |
+
|
| 471 |
+
def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None):
|
| 472 |
+
"""
|
| 473 |
+
Converts the output of [`BeitForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
|
| 474 |
+
|
| 475 |
+
Args:
|
| 476 |
+
outputs ([`BeitForSemanticSegmentation`]):
|
| 477 |
+
Raw outputs of the model.
|
| 478 |
+
target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
|
| 479 |
+
List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
|
| 480 |
+
predictions will not be resized.
|
| 481 |
+
|
| 482 |
+
Returns:
|
| 483 |
+
semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
|
| 484 |
+
segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
|
| 485 |
+
specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
|
| 486 |
+
"""
|
| 487 |
+
# TODO: add support for other frameworks
|
| 488 |
+
logits = outputs.logits
|
| 489 |
+
|
| 490 |
+
# Resize logits and compute semantic segmentation maps
|
| 491 |
+
if target_sizes is not None:
|
| 492 |
+
if len(logits) != len(target_sizes):
|
| 493 |
+
raise ValueError(
|
| 494 |
+
"Make sure that you pass in as many target sizes as the batch dimension of the logits"
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
if is_torch_tensor(target_sizes):
|
| 498 |
+
target_sizes = target_sizes.numpy()
|
| 499 |
+
|
| 500 |
+
semantic_segmentation = []
|
| 501 |
+
|
| 502 |
+
for idx in range(len(logits)):
|
| 503 |
+
resized_logits = torch.nn.functional.interpolate(
|
| 504 |
+
logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
|
| 505 |
+
)
|
| 506 |
+
semantic_map = resized_logits[0].argmax(dim=0)
|
| 507 |
+
semantic_segmentation.append(semantic_map)
|
| 508 |
+
else:
|
| 509 |
+
semantic_segmentation = logits.argmax(dim=1)
|
| 510 |
+
semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
|
| 511 |
+
|
| 512 |
+
return semantic_segmentation
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
__all__ = ["BeitImageProcessor"]
|
lib/python3.12/site-packages/transformers/models/beit/modeling_beit.py
ADDED
|
@@ -0,0 +1,1652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch BEiT model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
import math
|
| 19 |
+
import warnings
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import List, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.utils.checkpoint
|
| 25 |
+
from torch import Tensor, nn
|
| 26 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 27 |
+
|
| 28 |
+
from ...activations import ACT2FN
|
| 29 |
+
from ...modeling_outputs import (
|
| 30 |
+
BackboneOutput,
|
| 31 |
+
BaseModelOutput,
|
| 32 |
+
BaseModelOutputWithPooling,
|
| 33 |
+
ImageClassifierOutput,
|
| 34 |
+
MaskedLMOutput,
|
| 35 |
+
SemanticSegmenterOutput,
|
| 36 |
+
)
|
| 37 |
+
from ...modeling_utils import PreTrainedModel
|
| 38 |
+
from ...pytorch_utils import compile_compatible_method_lru_cache, 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 |
+
torch_int,
|
| 46 |
+
)
|
| 47 |
+
from ...utils.backbone_utils import BackboneMixin
|
| 48 |
+
from .configuration_beit import BeitConfig
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
logger = logging.get_logger(__name__)
|
| 52 |
+
|
| 53 |
+
# General docstring
|
| 54 |
+
_CONFIG_FOR_DOC = "BeitConfig"
|
| 55 |
+
|
| 56 |
+
# Base docstring
|
| 57 |
+
_CHECKPOINT_FOR_DOC = "microsoft/beit-base-patch16-224-pt22k"
|
| 58 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
|
| 59 |
+
|
| 60 |
+
# Image classification docstring
|
| 61 |
+
_IMAGE_CLASS_CHECKPOINT = "microsoft/beit-base-patch16-224"
|
| 62 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass
|
| 66 |
+
class BeitModelOutputWithPooling(BaseModelOutputWithPooling):
|
| 67 |
+
"""
|
| 68 |
+
Class for outputs of [`BeitModel`].
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 72 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 73 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
|
| 74 |
+
Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
|
| 75 |
+
*config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
|
| 76 |
+
will be returned.
|
| 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 + one for the output of each layer) of
|
| 79 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 80 |
+
|
| 81 |
+
Hidden-states of the model at the output of each layer plus the 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 |
+
|
| 91 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 92 |
+
"""
|
| 93 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 94 |
+
|
| 95 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 96 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 97 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 98 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 99 |
+
argument.
|
| 100 |
+
"""
|
| 101 |
+
if drop_prob == 0.0 or not training:
|
| 102 |
+
return input
|
| 103 |
+
keep_prob = 1 - drop_prob
|
| 104 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 105 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 106 |
+
random_tensor.floor_() # binarize
|
| 107 |
+
output = input.div(keep_prob) * random_tensor
|
| 108 |
+
return output
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class BeitDropPath(nn.Module):
|
| 112 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 113 |
+
|
| 114 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.drop_prob = drop_prob
|
| 117 |
+
|
| 118 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 119 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 120 |
+
|
| 121 |
+
def extra_repr(self) -> str:
|
| 122 |
+
return "p={}".format(self.drop_prob)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# Based on timm implementation, which can be found here:
|
| 126 |
+
# https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
|
| 127 |
+
class BeitEmbeddings(nn.Module):
|
| 128 |
+
"""
|
| 129 |
+
Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
|
| 130 |
+
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 134 |
+
super().__init__()
|
| 135 |
+
|
| 136 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 137 |
+
if config.use_mask_token:
|
| 138 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
|
| 139 |
+
else:
|
| 140 |
+
self.mask_token = None
|
| 141 |
+
self.patch_embeddings = BeitPatchEmbeddings(config)
|
| 142 |
+
self.patch_size = config.patch_size
|
| 143 |
+
self.image_size = (
|
| 144 |
+
config.image_size
|
| 145 |
+
if isinstance(config.image_size, collections.abc.Iterable)
|
| 146 |
+
else (config.image_size, config.image_size)
|
| 147 |
+
)
|
| 148 |
+
num_patches = self.patch_embeddings.num_patches
|
| 149 |
+
if config.use_absolute_position_embeddings:
|
| 150 |
+
self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
|
| 151 |
+
else:
|
| 152 |
+
self.position_embeddings = None
|
| 153 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 154 |
+
|
| 155 |
+
# Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
|
| 156 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 157 |
+
"""
|
| 158 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 159 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 160 |
+
|
| 161 |
+
Adapted from:
|
| 162 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 163 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
num_patches = embeddings.shape[1] - 1
|
| 167 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 168 |
+
|
| 169 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 170 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 171 |
+
return self.position_embeddings
|
| 172 |
+
|
| 173 |
+
class_pos_embed = self.position_embeddings[:, :1]
|
| 174 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 175 |
+
|
| 176 |
+
dim = embeddings.shape[-1]
|
| 177 |
+
|
| 178 |
+
new_height = height // self.patch_size
|
| 179 |
+
new_width = width // self.patch_size
|
| 180 |
+
|
| 181 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 182 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 183 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 184 |
+
|
| 185 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 186 |
+
patch_pos_embed,
|
| 187 |
+
size=(new_height, new_width),
|
| 188 |
+
mode="bicubic",
|
| 189 |
+
align_corners=False,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 193 |
+
|
| 194 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 195 |
+
|
| 196 |
+
def forward(
|
| 197 |
+
self,
|
| 198 |
+
pixel_values: torch.Tensor,
|
| 199 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 200 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 201 |
+
) -> torch.Tensor:
|
| 202 |
+
if self.position_embeddings is not None and interpolate_pos_encoding is not None:
|
| 203 |
+
warnings.warn(
|
| 204 |
+
"`interpolate_pos_encoding` argument has no effect for BEiTEmbeddings, embeddings are always "
|
| 205 |
+
"interpolated to the input image size. The argument will be removed in transformers v4.51.0."
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
_, _, height, width = pixel_values.shape
|
| 209 |
+
embeddings, (patch_height, patch_width) = self.patch_embeddings(pixel_values)
|
| 210 |
+
batch_size, seq_len, _ = embeddings.size()
|
| 211 |
+
|
| 212 |
+
if bool_masked_pos is not None:
|
| 213 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
|
| 214 |
+
# replace the masked visual tokens by mask_tokens
|
| 215 |
+
w = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
| 216 |
+
embeddings = embeddings * (1 - w) + mask_tokens * w
|
| 217 |
+
|
| 218 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 219 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 220 |
+
|
| 221 |
+
if self.position_embeddings is not None:
|
| 222 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 223 |
+
|
| 224 |
+
embeddings = self.dropout(embeddings)
|
| 225 |
+
|
| 226 |
+
return embeddings, (patch_height, patch_width)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class BeitPatchEmbeddings(nn.Module):
|
| 230 |
+
"""
|
| 231 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 232 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 233 |
+
Transformer.
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
def __init__(self, config):
|
| 237 |
+
super().__init__()
|
| 238 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 239 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 240 |
+
|
| 241 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 242 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 243 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 244 |
+
patch_shape = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
|
| 245 |
+
self.image_size = image_size
|
| 246 |
+
self.patch_size = patch_size
|
| 247 |
+
self.num_channels = num_channels
|
| 248 |
+
self.num_patches = num_patches
|
| 249 |
+
self.patch_shape = patch_shape
|
| 250 |
+
|
| 251 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 252 |
+
|
| 253 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 254 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 255 |
+
if num_channels != self.num_channels:
|
| 256 |
+
raise ValueError(
|
| 257 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
embeddings = self.projection(pixel_values)
|
| 261 |
+
patch_height, patch_width = embeddings.shape[2], embeddings.shape[3]
|
| 262 |
+
embeddings = embeddings.flatten(2).transpose(1, 2)
|
| 263 |
+
|
| 264 |
+
return embeddings, (patch_height, patch_width)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class BeitSelfAttention(nn.Module):
|
| 268 |
+
def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None) -> None:
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.config = config
|
| 271 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 272 |
+
raise ValueError(
|
| 273 |
+
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
|
| 274 |
+
f"heads {config.num_attention_heads}."
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
self.num_attention_heads = config.num_attention_heads
|
| 278 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 279 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 280 |
+
|
| 281 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 282 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
|
| 283 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 284 |
+
|
| 285 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 286 |
+
|
| 287 |
+
self.has_relative_position_bias = bool(window_size)
|
| 288 |
+
if self.has_relative_position_bias:
|
| 289 |
+
self.relative_position_bias = BeitRelativePositionBias(config, window_size=window_size)
|
| 290 |
+
|
| 291 |
+
def transpose_for_scores(self, x):
|
| 292 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 293 |
+
x = x.view(*new_x_shape)
|
| 294 |
+
return x.permute(0, 2, 1, 3)
|
| 295 |
+
|
| 296 |
+
def forward(
|
| 297 |
+
self,
|
| 298 |
+
hidden_states: torch.Tensor,
|
| 299 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 300 |
+
output_attentions: bool = False,
|
| 301 |
+
relative_position_bias: Optional[torch.Tensor] = None,
|
| 302 |
+
interpolate_pos_encoding: bool = False,
|
| 303 |
+
resolution: Optional[Tuple[int]] = None,
|
| 304 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
|
| 305 |
+
mixed_query_layer = self.query(hidden_states)
|
| 306 |
+
|
| 307 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 308 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 309 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 310 |
+
|
| 311 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 312 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 313 |
+
|
| 314 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 315 |
+
|
| 316 |
+
# Add relative position bias if present.
|
| 317 |
+
if self.has_relative_position_bias:
|
| 318 |
+
height, width = resolution
|
| 319 |
+
window_size = (height // self.config.patch_size, width // self.config.patch_size)
|
| 320 |
+
attention_scores = attention_scores + self.relative_position_bias(
|
| 321 |
+
window_size, interpolate_pos_encoding, dim_size=hidden_states.shape[1]
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
# Add shared relative position bias if provided.
|
| 325 |
+
if relative_position_bias is not None:
|
| 326 |
+
attention_scores = attention_scores + relative_position_bias
|
| 327 |
+
|
| 328 |
+
# Normalize the attention scores to probabilities.
|
| 329 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 330 |
+
|
| 331 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 332 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 333 |
+
attention_probs = self.dropout(attention_probs)
|
| 334 |
+
|
| 335 |
+
# Mask heads if we want to
|
| 336 |
+
if head_mask is not None:
|
| 337 |
+
attention_probs = attention_probs * head_mask
|
| 338 |
+
|
| 339 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 340 |
+
|
| 341 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 342 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 343 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 344 |
+
|
| 345 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 346 |
+
|
| 347 |
+
return outputs
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class BeitSdpaSelfAttention(BeitSelfAttention):
|
| 351 |
+
def forward(
|
| 352 |
+
self,
|
| 353 |
+
hidden_states: torch.Tensor,
|
| 354 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 355 |
+
output_attentions: bool = False,
|
| 356 |
+
relative_position_bias: Optional[torch.Tensor] = None,
|
| 357 |
+
interpolate_pos_encoding: bool = False,
|
| 358 |
+
resolution: Optional[Tuple[int]] = None,
|
| 359 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
|
| 360 |
+
if output_attentions or head_mask is not None:
|
| 361 |
+
logger.warning_once(
|
| 362 |
+
"`BeitSdpaSelfAttention` is used but `torch.nn.functional.scaled_dot_product_attention` does not "
|
| 363 |
+
"support `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, "
|
| 364 |
+
"but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. "
|
| 365 |
+
'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 366 |
+
)
|
| 367 |
+
return super().forward(
|
| 368 |
+
hidden_states=hidden_states,
|
| 369 |
+
head_mask=head_mask,
|
| 370 |
+
output_attentions=output_attentions,
|
| 371 |
+
relative_position_bias=relative_position_bias,
|
| 372 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 373 |
+
resolution=resolution,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
mixed_query_layer = self.query(hidden_states)
|
| 377 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 378 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 379 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 380 |
+
|
| 381 |
+
attn_bias = None
|
| 382 |
+
if self.has_relative_position_bias:
|
| 383 |
+
height, width = resolution
|
| 384 |
+
window_size = (height // self.config.patch_size, width // self.config.patch_size)
|
| 385 |
+
attn_bias = self.relative_position_bias(
|
| 386 |
+
window_size, interpolate_pos_encoding, dim_size=hidden_states.shape[1]
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
# Add shared relative position bias if provided.
|
| 390 |
+
if relative_position_bias is not None:
|
| 391 |
+
if attn_bias is None:
|
| 392 |
+
attn_bias = relative_position_bias
|
| 393 |
+
else:
|
| 394 |
+
attn_bias += relative_position_bias
|
| 395 |
+
|
| 396 |
+
scaling = 1 / math.sqrt(self.attention_head_size)
|
| 397 |
+
context_layer = torch.nn.functional.scaled_dot_product_attention(
|
| 398 |
+
query_layer,
|
| 399 |
+
key_layer,
|
| 400 |
+
value_layer,
|
| 401 |
+
attn_mask=attn_bias,
|
| 402 |
+
dropout_p=self.config.attention_probs_dropout_prob if self.training else 0.0,
|
| 403 |
+
is_causal=False,
|
| 404 |
+
scale=scaling,
|
| 405 |
+
)
|
| 406 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 407 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 408 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 409 |
+
return context_layer, None
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class BeitSelfOutput(nn.Module):
|
| 413 |
+
"""
|
| 414 |
+
The residual connection is defined in BeitLayer instead of here (as is the case with other models), due to the
|
| 415 |
+
layernorm applied before each block.
|
| 416 |
+
"""
|
| 417 |
+
|
| 418 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 419 |
+
super().__init__()
|
| 420 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 421 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 422 |
+
|
| 423 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor, gamma=None) -> torch.Tensor:
|
| 424 |
+
hidden_states = self.dense(hidden_states)
|
| 425 |
+
hidden_states = self.dropout(hidden_states)
|
| 426 |
+
|
| 427 |
+
return hidden_states
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
BEIT_SELF_ATTENTION_CLASSES = {
|
| 431 |
+
"eager": BeitSelfAttention,
|
| 432 |
+
"sdpa": BeitSdpaSelfAttention,
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class BeitAttention(nn.Module):
|
| 437 |
+
def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None) -> None:
|
| 438 |
+
super().__init__()
|
| 439 |
+
self.attention = BEIT_SELF_ATTENTION_CLASSES[config._attn_implementation](config, window_size=window_size)
|
| 440 |
+
self.output = BeitSelfOutput(config)
|
| 441 |
+
self.pruned_heads = set()
|
| 442 |
+
|
| 443 |
+
def prune_heads(self, heads):
|
| 444 |
+
if len(heads) == 0:
|
| 445 |
+
return
|
| 446 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 447 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
# Prune linear layers
|
| 451 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 452 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 453 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 454 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 455 |
+
|
| 456 |
+
# Update hyper params and store pruned heads
|
| 457 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 458 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 459 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 460 |
+
|
| 461 |
+
def forward(
|
| 462 |
+
self,
|
| 463 |
+
hidden_states: torch.Tensor,
|
| 464 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 465 |
+
output_attentions: bool = False,
|
| 466 |
+
relative_position_bias: Optional[torch.Tensor] = None,
|
| 467 |
+
interpolate_pos_encoding: bool = False,
|
| 468 |
+
resolution: Optional[Tuple[int]] = None,
|
| 469 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
|
| 470 |
+
self_outputs = self.attention(
|
| 471 |
+
hidden_states, head_mask, output_attentions, relative_position_bias, interpolate_pos_encoding, resolution
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 475 |
+
|
| 476 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 477 |
+
return outputs
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class BeitIntermediate(nn.Module):
|
| 481 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 482 |
+
super().__init__()
|
| 483 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 484 |
+
if isinstance(config.hidden_act, str):
|
| 485 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 486 |
+
else:
|
| 487 |
+
self.intermediate_act_fn = config.hidden_act
|
| 488 |
+
|
| 489 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 490 |
+
hidden_states = self.dense(hidden_states)
|
| 491 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 492 |
+
|
| 493 |
+
return hidden_states
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
class BeitOutput(nn.Module):
|
| 497 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 498 |
+
super().__init__()
|
| 499 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 500 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 501 |
+
|
| 502 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 503 |
+
hidden_states = self.dense(hidden_states)
|
| 504 |
+
hidden_states = self.dropout(hidden_states)
|
| 505 |
+
|
| 506 |
+
return hidden_states
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
class BeitLayer(nn.Module):
|
| 510 |
+
"""This corresponds to the Block class in the timm implementation."""
|
| 511 |
+
|
| 512 |
+
def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None, drop_path_rate: float = 0.0) -> None:
|
| 513 |
+
super().__init__()
|
| 514 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 515 |
+
self.seq_len_dim = 1
|
| 516 |
+
self.attention = BeitAttention(config, window_size=window_size)
|
| 517 |
+
self.intermediate = BeitIntermediate(config)
|
| 518 |
+
self.output = BeitOutput(config)
|
| 519 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 520 |
+
self.drop_path = BeitDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 521 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 522 |
+
|
| 523 |
+
init_values = config.layer_scale_init_value
|
| 524 |
+
if init_values > 0:
|
| 525 |
+
self.lambda_1 = nn.Parameter(init_values * torch.ones((config.hidden_size)), requires_grad=True)
|
| 526 |
+
self.lambda_2 = nn.Parameter(init_values * torch.ones((config.hidden_size)), requires_grad=True)
|
| 527 |
+
else:
|
| 528 |
+
self.lambda_1, self.lambda_2 = None, None
|
| 529 |
+
|
| 530 |
+
def forward(
|
| 531 |
+
self,
|
| 532 |
+
hidden_states: torch.Tensor,
|
| 533 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 534 |
+
output_attentions: bool = False,
|
| 535 |
+
relative_position_bias: Optional[torch.Tensor] = None,
|
| 536 |
+
interpolate_pos_encoding: bool = False,
|
| 537 |
+
resolution: Optional[Tuple[int]] = None,
|
| 538 |
+
) -> Union[Tuple[torch.Tensor], Tuple[torch.Tensor, torch.Tensor]]:
|
| 539 |
+
self_attention_outputs = self.attention(
|
| 540 |
+
self.layernorm_before(hidden_states), # in BEiT, layernorm is applied before self-attention
|
| 541 |
+
head_mask,
|
| 542 |
+
output_attentions=output_attentions,
|
| 543 |
+
relative_position_bias=relative_position_bias,
|
| 544 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 545 |
+
resolution=resolution,
|
| 546 |
+
)
|
| 547 |
+
attention_output = self_attention_outputs[0]
|
| 548 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 549 |
+
|
| 550 |
+
# apply lambda_1 if present
|
| 551 |
+
if self.lambda_1 is not None:
|
| 552 |
+
attention_output = self.lambda_1 * attention_output
|
| 553 |
+
|
| 554 |
+
# first residual connection
|
| 555 |
+
hidden_states = self.drop_path(attention_output) + hidden_states
|
| 556 |
+
|
| 557 |
+
# in BEiT, layernorm is also applied after self-attention
|
| 558 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 559 |
+
|
| 560 |
+
layer_output = self.intermediate(layer_output)
|
| 561 |
+
layer_output = self.output(layer_output)
|
| 562 |
+
|
| 563 |
+
if self.lambda_2 is not None:
|
| 564 |
+
layer_output = self.lambda_2 * layer_output
|
| 565 |
+
|
| 566 |
+
# second residual connection
|
| 567 |
+
layer_output = self.drop_path(layer_output) + hidden_states
|
| 568 |
+
|
| 569 |
+
outputs = (layer_output,) + outputs
|
| 570 |
+
|
| 571 |
+
return outputs
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
class BeitRelativePositionBias(nn.Module):
|
| 575 |
+
def __init__(self, config: BeitConfig, window_size: tuple) -> None:
|
| 576 |
+
super().__init__()
|
| 577 |
+
self.window_size = window_size
|
| 578 |
+
self.num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
| 579 |
+
self.relative_position_bias_table = nn.Parameter(
|
| 580 |
+
torch.zeros(self.num_relative_distance, config.num_attention_heads)
|
| 581 |
+
) # 2*Wh-1 * 2*Ww-1, nH
|
| 582 |
+
# cls to token & token 2 cls & cls to cls
|
| 583 |
+
|
| 584 |
+
@compile_compatible_method_lru_cache(maxsize=10)
|
| 585 |
+
def generate_relative_position_index(self, window_size: Tuple[int, int]) -> torch.Tensor:
|
| 586 |
+
"""
|
| 587 |
+
This method creates the relative position index, modified to support arbitrary window sizes,
|
| 588 |
+
as introduced in [MiDaS v3.1](https://arxiv.org/abs/2307.14460).
|
| 589 |
+
"""
|
| 590 |
+
num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
| 591 |
+
# cls to token & token 2 cls & cls to cls
|
| 592 |
+
# get pair-wise relative position index for each token inside the window
|
| 593 |
+
window_area = window_size[0] * window_size[1]
|
| 594 |
+
grid = torch.meshgrid(torch.arange(window_size[0]), torch.arange(window_size[1]), indexing="ij")
|
| 595 |
+
coords = torch.stack(grid) # 2, Wh, Ww
|
| 596 |
+
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
| 597 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
| 598 |
+
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
| 599 |
+
relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
| 600 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
| 601 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
| 602 |
+
relative_position_index = torch.zeros(size=(window_area + 1,) * 2, dtype=relative_coords.dtype)
|
| 603 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
| 604 |
+
relative_position_index[0, 0:] = num_relative_distance - 3
|
| 605 |
+
relative_position_index[0:, 0] = num_relative_distance - 2
|
| 606 |
+
relative_position_index[0, 0] = num_relative_distance - 1
|
| 607 |
+
return relative_position_index
|
| 608 |
+
|
| 609 |
+
def forward(self, window_size, interpolate_pos_encoding: bool = False, dim_size=None) -> torch.Tensor:
|
| 610 |
+
"""
|
| 611 |
+
Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes.
|
| 612 |
+
"""
|
| 613 |
+
old_height = 2 * self.window_size[0] - 1
|
| 614 |
+
old_width = 2 * self.window_size[1] - 1
|
| 615 |
+
|
| 616 |
+
new_height = 2 * window_size[0] - 1
|
| 617 |
+
new_width = 2 * window_size[1] - 1
|
| 618 |
+
|
| 619 |
+
old_relative_position_bias_table = self.relative_position_bias_table
|
| 620 |
+
|
| 621 |
+
old_num_relative_distance = self.num_relative_distance
|
| 622 |
+
new_num_relative_distance = new_height * new_width + 3
|
| 623 |
+
|
| 624 |
+
old_sub_table = old_relative_position_bias_table[: old_num_relative_distance - 3]
|
| 625 |
+
|
| 626 |
+
old_sub_table = old_sub_table.reshape(1, old_width, old_height, -1).permute(0, 3, 1, 2)
|
| 627 |
+
new_sub_table = nn.functional.interpolate(
|
| 628 |
+
old_sub_table, size=(torch_int(new_height), torch_int(new_width)), mode="bilinear"
|
| 629 |
+
)
|
| 630 |
+
new_sub_table = new_sub_table.permute(0, 2, 3, 1).reshape(new_num_relative_distance - 3, -1)
|
| 631 |
+
|
| 632 |
+
new_relative_position_bias_table = torch.cat(
|
| 633 |
+
[new_sub_table, old_relative_position_bias_table[old_num_relative_distance - 3 :]]
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
relative_position_index = self.generate_relative_position_index(window_size)
|
| 637 |
+
relative_position_bias = new_relative_position_bias_table[relative_position_index.view(-1)]
|
| 638 |
+
|
| 639 |
+
# patch_size*num_patches_height, patch_size*num_patches_width, num_attention_heads
|
| 640 |
+
relative_position_bias = relative_position_bias.view(
|
| 641 |
+
window_size[0] * window_size[1] + 1, window_size[0] * window_size[1] + 1, -1
|
| 642 |
+
)
|
| 643 |
+
# num_attention_heads, patch_size*num_patches_width, patch_size*num_patches_height
|
| 644 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
|
| 645 |
+
|
| 646 |
+
if interpolate_pos_encoding:
|
| 647 |
+
relative_position_bias = nn.functional.interpolate(
|
| 648 |
+
relative_position_bias.unsqueeze(1),
|
| 649 |
+
size=(dim_size, dim_size),
|
| 650 |
+
mode="bilinear",
|
| 651 |
+
align_corners=False,
|
| 652 |
+
).squeeze(1)
|
| 653 |
+
|
| 654 |
+
return relative_position_bias.unsqueeze(0)
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
class BeitEncoder(nn.Module):
|
| 658 |
+
def __init__(self, config: BeitConfig, window_size: Optional[tuple] = None) -> None:
|
| 659 |
+
super().__init__()
|
| 660 |
+
self.config = config
|
| 661 |
+
self.has_relative_position_bias = config.use_shared_relative_position_bias
|
| 662 |
+
if self.has_relative_position_bias:
|
| 663 |
+
self.relative_position_bias = BeitRelativePositionBias(config, window_size=window_size)
|
| 664 |
+
|
| 665 |
+
# stochastic depth decay rule
|
| 666 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers)]
|
| 667 |
+
self.layer = nn.ModuleList(
|
| 668 |
+
[
|
| 669 |
+
BeitLayer(
|
| 670 |
+
config,
|
| 671 |
+
window_size=window_size if config.use_relative_position_bias else None,
|
| 672 |
+
drop_path_rate=dpr[i],
|
| 673 |
+
)
|
| 674 |
+
for i in range(config.num_hidden_layers)
|
| 675 |
+
]
|
| 676 |
+
)
|
| 677 |
+
self.gradient_checkpointing = False
|
| 678 |
+
|
| 679 |
+
def forward(
|
| 680 |
+
self,
|
| 681 |
+
hidden_states: torch.Tensor,
|
| 682 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 683 |
+
output_attentions: bool = False,
|
| 684 |
+
output_hidden_states: bool = False,
|
| 685 |
+
interpolate_pos_encoding: bool = False,
|
| 686 |
+
resolution: Optional[Tuple[int, int]] = None,
|
| 687 |
+
return_dict: bool = True,
|
| 688 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 689 |
+
all_hidden_states = () if output_hidden_states else None
|
| 690 |
+
all_self_attentions = () if output_attentions else None
|
| 691 |
+
|
| 692 |
+
for i, layer_module in enumerate(self.layer):
|
| 693 |
+
if output_hidden_states:
|
| 694 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 695 |
+
|
| 696 |
+
if self.has_relative_position_bias:
|
| 697 |
+
height, width = resolution
|
| 698 |
+
window_size = (height // self.config.patch_size, width // self.config.patch_size)
|
| 699 |
+
relative_position_bias = self.relative_position_bias(
|
| 700 |
+
window_size, interpolate_pos_encoding=interpolate_pos_encoding, dim_size=hidden_states.shape[1]
|
| 701 |
+
)
|
| 702 |
+
else:
|
| 703 |
+
relative_position_bias = None
|
| 704 |
+
|
| 705 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 706 |
+
|
| 707 |
+
if self.gradient_checkpointing and self.training:
|
| 708 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 709 |
+
layer_module.__call__,
|
| 710 |
+
hidden_states,
|
| 711 |
+
layer_head_mask,
|
| 712 |
+
output_attentions,
|
| 713 |
+
relative_position_bias,
|
| 714 |
+
interpolate_pos_encoding,
|
| 715 |
+
resolution,
|
| 716 |
+
)
|
| 717 |
+
else:
|
| 718 |
+
layer_outputs = layer_module(
|
| 719 |
+
hidden_states,
|
| 720 |
+
layer_head_mask,
|
| 721 |
+
output_attentions,
|
| 722 |
+
relative_position_bias,
|
| 723 |
+
interpolate_pos_encoding,
|
| 724 |
+
resolution,
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
hidden_states = layer_outputs[0]
|
| 728 |
+
|
| 729 |
+
if output_attentions:
|
| 730 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 731 |
+
|
| 732 |
+
if output_hidden_states:
|
| 733 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 734 |
+
|
| 735 |
+
if not return_dict:
|
| 736 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 737 |
+
return BaseModelOutput(
|
| 738 |
+
last_hidden_state=hidden_states,
|
| 739 |
+
hidden_states=all_hidden_states,
|
| 740 |
+
attentions=all_self_attentions,
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
class BeitPreTrainedModel(PreTrainedModel):
|
| 745 |
+
"""
|
| 746 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 747 |
+
models.
|
| 748 |
+
"""
|
| 749 |
+
|
| 750 |
+
config_class = BeitConfig
|
| 751 |
+
base_model_prefix = "beit"
|
| 752 |
+
main_input_name = "pixel_values"
|
| 753 |
+
supports_gradient_checkpointing = True
|
| 754 |
+
_no_split_modules = ["BeitLayer"]
|
| 755 |
+
_keys_to_ignore_on_load_unexpected = [r".*relative_position_index.*"]
|
| 756 |
+
_supports_sdpa = True
|
| 757 |
+
|
| 758 |
+
def _init_weights(self, module):
|
| 759 |
+
"""Initialize the weights"""
|
| 760 |
+
if isinstance(module, (nn.Linear, nn.Conv2d, nn.ConvTranspose2d)):
|
| 761 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 762 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 763 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 764 |
+
if module.bias is not None:
|
| 765 |
+
module.bias.data.zero_()
|
| 766 |
+
elif isinstance(module, nn.Embedding):
|
| 767 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 768 |
+
if module.padding_idx is not None:
|
| 769 |
+
module.weight.data[module.padding_idx].zero_()
|
| 770 |
+
elif isinstance(module, nn.LayerNorm):
|
| 771 |
+
module.bias.data.zero_()
|
| 772 |
+
module.weight.data.fill_(1.0)
|
| 773 |
+
elif isinstance(module, BeitEmbeddings):
|
| 774 |
+
module.cls_token.data.zero_()
|
| 775 |
+
if module.mask_token is not None:
|
| 776 |
+
module.mask_token.data.zero_()
|
| 777 |
+
if module.position_embeddings is not None:
|
| 778 |
+
module.position_embeddings.data.zero_()
|
| 779 |
+
elif isinstance(module, BeitRelativePositionBias):
|
| 780 |
+
module.relative_position_bias_table.data.zero_()
|
| 781 |
+
elif isinstance(module, BeitLayer):
|
| 782 |
+
if module.lambda_1 is not None:
|
| 783 |
+
module.lambda_1.data.fill_(self.config.layer_scale_init_value)
|
| 784 |
+
module.lambda_2.data.fill_(self.config.layer_scale_init_value)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
BEIT_START_DOCSTRING = r"""
|
| 788 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 789 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 790 |
+
behavior.
|
| 791 |
+
|
| 792 |
+
Parameters:
|
| 793 |
+
config ([`BeitConfig`]): Model configuration class with all the parameters of the model.
|
| 794 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 795 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 796 |
+
"""
|
| 797 |
+
|
| 798 |
+
BEIT_INPUTS_DOCSTRING = r"""
|
| 799 |
+
Args:
|
| 800 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 801 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 802 |
+
[`BeitImageProcessor.__call__`] for details.
|
| 803 |
+
|
| 804 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 805 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 806 |
+
|
| 807 |
+
- 1 indicates the head is **not masked**,
|
| 808 |
+
- 0 indicates the head is **masked**.
|
| 809 |
+
|
| 810 |
+
output_attentions (`bool`, *optional*):
|
| 811 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 812 |
+
tensors for more detail.
|
| 813 |
+
output_hidden_states (`bool`, *optional*):
|
| 814 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 815 |
+
more detail.
|
| 816 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
|
| 817 |
+
Whether to interpolate the pre-trained position encodings.
|
| 818 |
+
return_dict (`bool`, *optional*):
|
| 819 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 820 |
+
"""
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
@add_start_docstrings(
|
| 824 |
+
"The bare Beit Model transformer outputting raw hidden-states without any specific head on top.",
|
| 825 |
+
BEIT_START_DOCSTRING,
|
| 826 |
+
)
|
| 827 |
+
class BeitModel(BeitPreTrainedModel):
|
| 828 |
+
def __init__(self, config: BeitConfig, add_pooling_layer: bool = True) -> None:
|
| 829 |
+
super().__init__(config)
|
| 830 |
+
self.config = config
|
| 831 |
+
|
| 832 |
+
self.embeddings = BeitEmbeddings(config)
|
| 833 |
+
self.encoder = BeitEncoder(config, window_size=self.embeddings.patch_embeddings.patch_shape)
|
| 834 |
+
|
| 835 |
+
self.layernorm = (
|
| 836 |
+
nn.Identity() if config.use_mean_pooling else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 837 |
+
)
|
| 838 |
+
self.pooler = BeitPooler(config) if add_pooling_layer else None
|
| 839 |
+
|
| 840 |
+
# Initialize weights and apply final processing
|
| 841 |
+
self.post_init()
|
| 842 |
+
|
| 843 |
+
def get_input_embeddings(self):
|
| 844 |
+
return self.embeddings.patch_embeddings
|
| 845 |
+
|
| 846 |
+
def _prune_heads(self, heads_to_prune):
|
| 847 |
+
"""
|
| 848 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 849 |
+
class PreTrainedModel
|
| 850 |
+
"""
|
| 851 |
+
for layer, heads in heads_to_prune.items():
|
| 852 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 853 |
+
|
| 854 |
+
@add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
|
| 855 |
+
@add_code_sample_docstrings(
|
| 856 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 857 |
+
output_type=BeitModelOutputWithPooling,
|
| 858 |
+
config_class=_CONFIG_FOR_DOC,
|
| 859 |
+
modality="vision",
|
| 860 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 861 |
+
)
|
| 862 |
+
def forward(
|
| 863 |
+
self,
|
| 864 |
+
pixel_values: torch.Tensor,
|
| 865 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 866 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 867 |
+
output_attentions: Optional[bool] = None,
|
| 868 |
+
output_hidden_states: Optional[bool] = None,
|
| 869 |
+
interpolate_pos_encoding: bool = False,
|
| 870 |
+
return_dict: Optional[bool] = None,
|
| 871 |
+
) -> Union[tuple, BeitModelOutputWithPooling]:
|
| 872 |
+
r"""
|
| 873 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
|
| 874 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 875 |
+
"""
|
| 876 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 877 |
+
output_hidden_states = (
|
| 878 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 879 |
+
)
|
| 880 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 881 |
+
|
| 882 |
+
# Prepare head mask if needed
|
| 883 |
+
# 1.0 in head_mask indicate we keep the head
|
| 884 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 885 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 886 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 887 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 888 |
+
|
| 889 |
+
embedding_output, _ = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 890 |
+
resolution = pixel_values.shape[2:]
|
| 891 |
+
|
| 892 |
+
encoder_outputs = self.encoder(
|
| 893 |
+
embedding_output,
|
| 894 |
+
head_mask=head_mask,
|
| 895 |
+
output_attentions=output_attentions,
|
| 896 |
+
output_hidden_states=output_hidden_states,
|
| 897 |
+
resolution=resolution,
|
| 898 |
+
return_dict=return_dict,
|
| 899 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 900 |
+
)
|
| 901 |
+
sequence_output = encoder_outputs[0]
|
| 902 |
+
sequence_output = self.layernorm(sequence_output)
|
| 903 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 904 |
+
|
| 905 |
+
if not return_dict:
|
| 906 |
+
head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
|
| 907 |
+
return head_outputs + encoder_outputs[1:]
|
| 908 |
+
|
| 909 |
+
return BeitModelOutputWithPooling(
|
| 910 |
+
last_hidden_state=sequence_output,
|
| 911 |
+
pooler_output=pooled_output,
|
| 912 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 913 |
+
attentions=encoder_outputs.attentions,
|
| 914 |
+
)
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
class BeitPooler(nn.Module):
|
| 918 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 919 |
+
super().__init__()
|
| 920 |
+
self.layernorm = (
|
| 921 |
+
nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) if config.use_mean_pooling else None
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 925 |
+
if self.layernorm is not None:
|
| 926 |
+
# Mean pool the final hidden states of the patch tokens
|
| 927 |
+
patch_tokens = hidden_states[:, 1:, :]
|
| 928 |
+
pooled_output = self.layernorm(patch_tokens.mean(1))
|
| 929 |
+
else:
|
| 930 |
+
# Pool by simply taking the final hidden state of the [CLS] token
|
| 931 |
+
pooled_output = hidden_states[:, 0]
|
| 932 |
+
|
| 933 |
+
return pooled_output
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
@add_start_docstrings(
|
| 937 |
+
"""Beit Model transformer with a 'language' modeling head on top. BEiT does masked image modeling by predicting
|
| 938 |
+
visual tokens of a Vector-Quantize Variational Autoencoder (VQ-VAE), whereas other vision models like ViT and DeiT
|
| 939 |
+
predict RGB pixel values. As a result, this class is incompatible with [`AutoModelForMaskedImageModeling`], so you
|
| 940 |
+
will need to use [`BeitForMaskedImageModeling`] directly if you wish to do masked image modeling with BEiT.""",
|
| 941 |
+
BEIT_START_DOCSTRING,
|
| 942 |
+
)
|
| 943 |
+
class BeitForMaskedImageModeling(BeitPreTrainedModel):
|
| 944 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 945 |
+
super().__init__(config)
|
| 946 |
+
|
| 947 |
+
self.num_labels = config.num_labels
|
| 948 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 949 |
+
|
| 950 |
+
# Classifier head
|
| 951 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 952 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
|
| 953 |
+
|
| 954 |
+
# Initialize weights and apply final processing
|
| 955 |
+
self.post_init()
|
| 956 |
+
|
| 957 |
+
@add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
|
| 958 |
+
@replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
|
| 959 |
+
def forward(
|
| 960 |
+
self,
|
| 961 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 962 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 963 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 964 |
+
labels: Optional[torch.Tensor] = None,
|
| 965 |
+
output_attentions: Optional[bool] = None,
|
| 966 |
+
output_hidden_states: Optional[bool] = None,
|
| 967 |
+
interpolate_pos_encoding: bool = False,
|
| 968 |
+
return_dict: Optional[bool] = None,
|
| 969 |
+
) -> Union[tuple, MaskedLMOutput]:
|
| 970 |
+
r"""
|
| 971 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
| 972 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 973 |
+
|
| 974 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 975 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 976 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 977 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 978 |
+
|
| 979 |
+
Returns:
|
| 980 |
+
|
| 981 |
+
Examples:
|
| 982 |
+
|
| 983 |
+
```python
|
| 984 |
+
>>> from transformers import AutoImageProcessor, BeitForMaskedImageModeling
|
| 985 |
+
>>> import torch
|
| 986 |
+
>>> from PIL import Image
|
| 987 |
+
>>> import requests
|
| 988 |
+
|
| 989 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 990 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 991 |
+
|
| 992 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 993 |
+
>>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 994 |
+
|
| 995 |
+
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
|
| 996 |
+
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
|
| 997 |
+
>>> # create random boolean mask of shape (batch_size, num_patches)
|
| 998 |
+
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
|
| 999 |
+
|
| 1000 |
+
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 1001 |
+
>>> loss, logits = outputs.loss, outputs.logits
|
| 1002 |
+
>>> list(logits.shape)
|
| 1003 |
+
[1, 196, 8192]
|
| 1004 |
+
```"""
|
| 1005 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1006 |
+
|
| 1007 |
+
outputs = self.beit(
|
| 1008 |
+
pixel_values,
|
| 1009 |
+
bool_masked_pos=bool_masked_pos,
|
| 1010 |
+
head_mask=head_mask,
|
| 1011 |
+
output_attentions=output_attentions,
|
| 1012 |
+
output_hidden_states=output_hidden_states,
|
| 1013 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1014 |
+
return_dict=return_dict,
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
sequence_output = outputs[0]
|
| 1018 |
+
sequence_output = self.layernorm(sequence_output)
|
| 1019 |
+
prediction_scores = self.lm_head(sequence_output[:, 1:])
|
| 1020 |
+
|
| 1021 |
+
masked_lm_loss = None
|
| 1022 |
+
if labels is not None:
|
| 1023 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 1024 |
+
masked_lm_loss = loss_fct(prediction_scores[bool_masked_pos], labels)
|
| 1025 |
+
|
| 1026 |
+
if not return_dict:
|
| 1027 |
+
output = (prediction_scores,) + outputs[1:]
|
| 1028 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1029 |
+
|
| 1030 |
+
return MaskedLMOutput(
|
| 1031 |
+
loss=masked_lm_loss,
|
| 1032 |
+
logits=prediction_scores,
|
| 1033 |
+
hidden_states=outputs.hidden_states,
|
| 1034 |
+
attentions=outputs.attentions,
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
|
| 1038 |
+
@add_start_docstrings(
|
| 1039 |
+
"""
|
| 1040 |
+
Beit Model transformer with an image classification head on top (a linear layer on top of the average of the final
|
| 1041 |
+
hidden states of the patch tokens) e.g. for ImageNet.
|
| 1042 |
+
""",
|
| 1043 |
+
BEIT_START_DOCSTRING,
|
| 1044 |
+
)
|
| 1045 |
+
class BeitForImageClassification(BeitPreTrainedModel):
|
| 1046 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 1047 |
+
super().__init__(config)
|
| 1048 |
+
|
| 1049 |
+
self.num_labels = config.num_labels
|
| 1050 |
+
self.beit = BeitModel(config, add_pooling_layer=True)
|
| 1051 |
+
|
| 1052 |
+
# Classifier head
|
| 1053 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 1054 |
+
|
| 1055 |
+
# Initialize weights and apply final processing
|
| 1056 |
+
self.post_init()
|
| 1057 |
+
|
| 1058 |
+
@add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
|
| 1059 |
+
@add_code_sample_docstrings(
|
| 1060 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 1061 |
+
output_type=ImageClassifierOutput,
|
| 1062 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1063 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 1064 |
+
)
|
| 1065 |
+
def forward(
|
| 1066 |
+
self,
|
| 1067 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1068 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1069 |
+
labels: Optional[torch.Tensor] = None,
|
| 1070 |
+
output_attentions: Optional[bool] = None,
|
| 1071 |
+
output_hidden_states: Optional[bool] = None,
|
| 1072 |
+
interpolate_pos_encoding: bool = False,
|
| 1073 |
+
return_dict: Optional[bool] = None,
|
| 1074 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
| 1075 |
+
r"""
|
| 1076 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1077 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 1078 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1079 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1080 |
+
"""
|
| 1081 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1082 |
+
outputs = self.beit(
|
| 1083 |
+
pixel_values,
|
| 1084 |
+
head_mask=head_mask,
|
| 1085 |
+
output_attentions=output_attentions,
|
| 1086 |
+
output_hidden_states=output_hidden_states,
|
| 1087 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1088 |
+
return_dict=return_dict,
|
| 1089 |
+
)
|
| 1090 |
+
|
| 1091 |
+
pooled_output = outputs.pooler_output if return_dict else outputs[1]
|
| 1092 |
+
|
| 1093 |
+
logits = self.classifier(pooled_output)
|
| 1094 |
+
|
| 1095 |
+
loss = None
|
| 1096 |
+
if labels is not None:
|
| 1097 |
+
if self.config.problem_type is None:
|
| 1098 |
+
if self.num_labels == 1:
|
| 1099 |
+
self.config.problem_type = "regression"
|
| 1100 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1101 |
+
self.config.problem_type = "single_label_classification"
|
| 1102 |
+
else:
|
| 1103 |
+
self.config.problem_type = "multi_label_classification"
|
| 1104 |
+
|
| 1105 |
+
if self.config.problem_type == "regression":
|
| 1106 |
+
loss_fct = MSELoss()
|
| 1107 |
+
if self.num_labels == 1:
|
| 1108 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1109 |
+
else:
|
| 1110 |
+
loss = loss_fct(logits, labels)
|
| 1111 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1112 |
+
loss_fct = CrossEntropyLoss()
|
| 1113 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1114 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1115 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1116 |
+
loss = loss_fct(logits, labels)
|
| 1117 |
+
if not return_dict:
|
| 1118 |
+
output = (logits,) + outputs[2:]
|
| 1119 |
+
return ((loss,) + output) if loss is not None else output
|
| 1120 |
+
|
| 1121 |
+
return ImageClassifierOutput(
|
| 1122 |
+
loss=loss,
|
| 1123 |
+
logits=logits,
|
| 1124 |
+
hidden_states=outputs.hidden_states,
|
| 1125 |
+
attentions=outputs.attentions,
|
| 1126 |
+
)
|
| 1127 |
+
|
| 1128 |
+
|
| 1129 |
+
class BeitConvModule(nn.Module):
|
| 1130 |
+
"""
|
| 1131 |
+
A convolutional block that bundles conv/norm/activation layers. This block simplifies the usage of convolution
|
| 1132 |
+
layers, which are commonly used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).
|
| 1133 |
+
|
| 1134 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 1135 |
+
"""
|
| 1136 |
+
|
| 1137 |
+
def __init__(
|
| 1138 |
+
self,
|
| 1139 |
+
in_channels: int,
|
| 1140 |
+
out_channels: int,
|
| 1141 |
+
kernel_size: Union[int, Tuple[int, int]],
|
| 1142 |
+
padding: Union[int, Tuple[int, int], str] = 0,
|
| 1143 |
+
bias: bool = False,
|
| 1144 |
+
dilation: Union[int, Tuple[int, int]] = 1,
|
| 1145 |
+
) -> None:
|
| 1146 |
+
super().__init__()
|
| 1147 |
+
self.conv = nn.Conv2d(
|
| 1148 |
+
in_channels=in_channels,
|
| 1149 |
+
out_channels=out_channels,
|
| 1150 |
+
kernel_size=kernel_size,
|
| 1151 |
+
padding=padding,
|
| 1152 |
+
bias=bias,
|
| 1153 |
+
dilation=dilation,
|
| 1154 |
+
)
|
| 1155 |
+
self.bn = nn.BatchNorm2d(out_channels)
|
| 1156 |
+
self.activation = nn.ReLU()
|
| 1157 |
+
|
| 1158 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 1159 |
+
output = self.conv(input)
|
| 1160 |
+
output = self.bn(output)
|
| 1161 |
+
output = self.activation(output)
|
| 1162 |
+
|
| 1163 |
+
return output
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
class BeitPyramidPoolingBlock(nn.Module):
|
| 1167 |
+
def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None:
|
| 1168 |
+
super().__init__()
|
| 1169 |
+
self.layers = [
|
| 1170 |
+
nn.AdaptiveAvgPool2d(pool_scale),
|
| 1171 |
+
BeitConvModule(in_channels, channels, kernel_size=1),
|
| 1172 |
+
]
|
| 1173 |
+
for i, layer in enumerate(self.layers):
|
| 1174 |
+
self.add_module(str(i), layer)
|
| 1175 |
+
|
| 1176 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 1177 |
+
hidden_state = input
|
| 1178 |
+
for layer in self.layers:
|
| 1179 |
+
hidden_state = layer(hidden_state)
|
| 1180 |
+
return hidden_state
|
| 1181 |
+
|
| 1182 |
+
|
| 1183 |
+
class BeitPyramidPoolingModule(nn.Module):
|
| 1184 |
+
"""
|
| 1185 |
+
Pyramid Pooling Module (PPM) used in PSPNet.
|
| 1186 |
+
|
| 1187 |
+
Args:
|
| 1188 |
+
pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid
|
| 1189 |
+
Module.
|
| 1190 |
+
in_channels (int): Input channels.
|
| 1191 |
+
channels (int): Channels after modules, before conv_seg.
|
| 1192 |
+
align_corners (bool): align_corners argument of F.interpolate.
|
| 1193 |
+
|
| 1194 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 1195 |
+
"""
|
| 1196 |
+
|
| 1197 |
+
def __init__(self, pool_scales: Tuple[int, ...], in_channels: int, channels: int, align_corners: bool) -> None:
|
| 1198 |
+
super().__init__()
|
| 1199 |
+
self.pool_scales = pool_scales
|
| 1200 |
+
self.align_corners = align_corners
|
| 1201 |
+
self.in_channels = in_channels
|
| 1202 |
+
self.channels = channels
|
| 1203 |
+
self.blocks = []
|
| 1204 |
+
for i, pool_scale in enumerate(pool_scales):
|
| 1205 |
+
block = BeitPyramidPoolingBlock(pool_scale=pool_scale, in_channels=in_channels, channels=channels)
|
| 1206 |
+
self.blocks.append(block)
|
| 1207 |
+
self.add_module(str(i), block)
|
| 1208 |
+
|
| 1209 |
+
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
|
| 1210 |
+
ppm_outs = []
|
| 1211 |
+
for ppm in self.blocks:
|
| 1212 |
+
ppm_out = ppm(x)
|
| 1213 |
+
upsampled_ppm_out = nn.functional.interpolate(
|
| 1214 |
+
ppm_out, size=x.size()[2:], mode="bilinear", align_corners=self.align_corners
|
| 1215 |
+
)
|
| 1216 |
+
ppm_outs.append(upsampled_ppm_out)
|
| 1217 |
+
return ppm_outs
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
class BeitUperHead(nn.Module):
|
| 1221 |
+
"""
|
| 1222 |
+
Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
|
| 1223 |
+
[UPerNet](https://arxiv.org/abs/1807.10221).
|
| 1224 |
+
|
| 1225 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 1226 |
+
"""
|
| 1227 |
+
|
| 1228 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 1229 |
+
super().__init__()
|
| 1230 |
+
|
| 1231 |
+
self.pool_scales = config.pool_scales # e.g. (1, 2, 3, 6)
|
| 1232 |
+
self.in_channels = [config.hidden_size] * 4 # e.g. [768, 768, 768, 768]
|
| 1233 |
+
self.channels = config.hidden_size
|
| 1234 |
+
self.align_corners = False
|
| 1235 |
+
self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
|
| 1236 |
+
|
| 1237 |
+
# PSP Module
|
| 1238 |
+
self.psp_modules = BeitPyramidPoolingModule(
|
| 1239 |
+
self.pool_scales,
|
| 1240 |
+
self.in_channels[-1],
|
| 1241 |
+
self.channels,
|
| 1242 |
+
align_corners=self.align_corners,
|
| 1243 |
+
)
|
| 1244 |
+
self.bottleneck = BeitConvModule(
|
| 1245 |
+
self.in_channels[-1] + len(self.pool_scales) * self.channels,
|
| 1246 |
+
self.channels,
|
| 1247 |
+
kernel_size=3,
|
| 1248 |
+
padding=1,
|
| 1249 |
+
)
|
| 1250 |
+
# FPN Module
|
| 1251 |
+
self.lateral_convs = nn.ModuleList()
|
| 1252 |
+
self.fpn_convs = nn.ModuleList()
|
| 1253 |
+
for in_channels in self.in_channels[:-1]: # skip the top layer
|
| 1254 |
+
l_conv = BeitConvModule(in_channels, self.channels, kernel_size=1)
|
| 1255 |
+
fpn_conv = BeitConvModule(self.channels, self.channels, kernel_size=3, padding=1)
|
| 1256 |
+
self.lateral_convs.append(l_conv)
|
| 1257 |
+
self.fpn_convs.append(fpn_conv)
|
| 1258 |
+
|
| 1259 |
+
self.fpn_bottleneck = BeitConvModule(
|
| 1260 |
+
len(self.in_channels) * self.channels,
|
| 1261 |
+
self.channels,
|
| 1262 |
+
kernel_size=3,
|
| 1263 |
+
padding=1,
|
| 1264 |
+
)
|
| 1265 |
+
|
| 1266 |
+
def psp_forward(self, inputs):
|
| 1267 |
+
x = inputs[-1]
|
| 1268 |
+
psp_outs = [x]
|
| 1269 |
+
psp_outs.extend(self.psp_modules(x))
|
| 1270 |
+
psp_outs = torch.cat(psp_outs, dim=1)
|
| 1271 |
+
output = self.bottleneck(psp_outs)
|
| 1272 |
+
|
| 1273 |
+
return output
|
| 1274 |
+
|
| 1275 |
+
def forward(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
|
| 1276 |
+
# build laterals
|
| 1277 |
+
laterals = [lateral_conv(encoder_hidden_states[i]) for i, lateral_conv in enumerate(self.lateral_convs)]
|
| 1278 |
+
|
| 1279 |
+
laterals.append(self.psp_forward(encoder_hidden_states))
|
| 1280 |
+
|
| 1281 |
+
# build top-down path
|
| 1282 |
+
used_backbone_levels = len(laterals)
|
| 1283 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 1284 |
+
prev_shape = laterals[i - 1].shape[2:]
|
| 1285 |
+
laterals[i - 1] = laterals[i - 1] + nn.functional.interpolate(
|
| 1286 |
+
laterals[i], size=prev_shape, mode="bilinear", align_corners=self.align_corners
|
| 1287 |
+
)
|
| 1288 |
+
|
| 1289 |
+
# build outputs
|
| 1290 |
+
fpn_outs = [self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels - 1)]
|
| 1291 |
+
# append psp feature
|
| 1292 |
+
fpn_outs.append(laterals[-1])
|
| 1293 |
+
|
| 1294 |
+
for i in range(used_backbone_levels - 1, 0, -1):
|
| 1295 |
+
fpn_outs[i] = nn.functional.interpolate(
|
| 1296 |
+
fpn_outs[i], size=fpn_outs[0].shape[2:], mode="bilinear", align_corners=self.align_corners
|
| 1297 |
+
)
|
| 1298 |
+
fpn_outs = torch.cat(fpn_outs, dim=1)
|
| 1299 |
+
output = self.fpn_bottleneck(fpn_outs)
|
| 1300 |
+
output = self.classifier(output)
|
| 1301 |
+
|
| 1302 |
+
return output
|
| 1303 |
+
|
| 1304 |
+
|
| 1305 |
+
class BeitFCNHead(nn.Module):
|
| 1306 |
+
"""
|
| 1307 |
+
Fully Convolution Networks for Semantic Segmentation. This head is implemented of
|
| 1308 |
+
[FCNNet](https://arxiv.org/abs/1411.4038>).
|
| 1309 |
+
|
| 1310 |
+
Args:
|
| 1311 |
+
config (BeitConfig): Configuration.
|
| 1312 |
+
in_channels
|
| 1313 |
+
kernel_size (int): The kernel size for convs in the head. Default: 3.
|
| 1314 |
+
dilation (int): The dilation rate for convs in the head. Default: 1.
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
|
| 1318 |
+
"""
|
| 1319 |
+
|
| 1320 |
+
def __init__(
|
| 1321 |
+
self, config: BeitConfig, in_index: int = 2, kernel_size: int = 3, dilation: Union[int, Tuple[int, int]] = 1
|
| 1322 |
+
) -> None:
|
| 1323 |
+
super().__init__()
|
| 1324 |
+
self.in_channels = config.hidden_size
|
| 1325 |
+
self.channels = config.auxiliary_channels
|
| 1326 |
+
self.num_convs = config.auxiliary_num_convs
|
| 1327 |
+
self.concat_input = config.auxiliary_concat_input
|
| 1328 |
+
self.in_index = in_index
|
| 1329 |
+
|
| 1330 |
+
conv_padding = (kernel_size // 2) * dilation
|
| 1331 |
+
convs = []
|
| 1332 |
+
convs.append(
|
| 1333 |
+
BeitConvModule(
|
| 1334 |
+
self.in_channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
|
| 1335 |
+
)
|
| 1336 |
+
)
|
| 1337 |
+
for i in range(self.num_convs - 1):
|
| 1338 |
+
convs.append(
|
| 1339 |
+
BeitConvModule(
|
| 1340 |
+
self.channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
|
| 1341 |
+
)
|
| 1342 |
+
)
|
| 1343 |
+
if self.num_convs == 0:
|
| 1344 |
+
self.convs = nn.Identity()
|
| 1345 |
+
else:
|
| 1346 |
+
self.convs = nn.Sequential(*convs)
|
| 1347 |
+
if self.concat_input:
|
| 1348 |
+
self.conv_cat = BeitConvModule(
|
| 1349 |
+
self.in_channels + self.channels, self.channels, kernel_size=kernel_size, padding=kernel_size // 2
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
|
| 1353 |
+
|
| 1354 |
+
def forward(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
|
| 1355 |
+
# just take the relevant feature maps
|
| 1356 |
+
hidden_states = encoder_hidden_states[self.in_index]
|
| 1357 |
+
output = self.convs(hidden_states)
|
| 1358 |
+
if self.concat_input:
|
| 1359 |
+
output = self.conv_cat(torch.cat([hidden_states, output], dim=1))
|
| 1360 |
+
output = self.classifier(output)
|
| 1361 |
+
return output
|
| 1362 |
+
|
| 1363 |
+
|
| 1364 |
+
@add_start_docstrings(
|
| 1365 |
+
"""
|
| 1366 |
+
Beit Model transformer with a semantic segmentation head on top e.g. for ADE20k, CityScapes.
|
| 1367 |
+
""",
|
| 1368 |
+
BEIT_START_DOCSTRING,
|
| 1369 |
+
)
|
| 1370 |
+
class BeitForSemanticSegmentation(BeitPreTrainedModel):
|
| 1371 |
+
def __init__(self, config: BeitConfig) -> None:
|
| 1372 |
+
super().__init__(config)
|
| 1373 |
+
|
| 1374 |
+
self.num_labels = config.num_labels
|
| 1375 |
+
self.beit = BeitModel(config, add_pooling_layer=False)
|
| 1376 |
+
|
| 1377 |
+
# FPNs
|
| 1378 |
+
if len(self.config.out_indices) != 4:
|
| 1379 |
+
raise ValueError(
|
| 1380 |
+
"BeitForSemanticSegmentation requires config.out_indices to be a list of 4 integers, "
|
| 1381 |
+
"specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of "
|
| 1382 |
+
"a base-sized architecture."
|
| 1383 |
+
)
|
| 1384 |
+
self.fpn1 = nn.Sequential(
|
| 1385 |
+
nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
|
| 1386 |
+
nn.BatchNorm2d(config.hidden_size),
|
| 1387 |
+
nn.GELU(),
|
| 1388 |
+
nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
|
| 1389 |
+
)
|
| 1390 |
+
self.fpn2 = nn.Sequential(
|
| 1391 |
+
nn.ConvTranspose2d(config.hidden_size, config.hidden_size, kernel_size=2, stride=2),
|
| 1392 |
+
)
|
| 1393 |
+
self.fpn3 = nn.Identity()
|
| 1394 |
+
self.fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
|
| 1395 |
+
|
| 1396 |
+
# Semantic segmentation head(s)
|
| 1397 |
+
self.decode_head = BeitUperHead(config)
|
| 1398 |
+
self.auxiliary_head = BeitFCNHead(config) if config.use_auxiliary_head else None
|
| 1399 |
+
|
| 1400 |
+
# Initialize weights and apply final processing
|
| 1401 |
+
self.post_init()
|
| 1402 |
+
|
| 1403 |
+
def compute_loss(self, logits, auxiliary_logits, labels):
|
| 1404 |
+
# upsample logits to the images' original size
|
| 1405 |
+
upsampled_logits = nn.functional.interpolate(
|
| 1406 |
+
logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
|
| 1407 |
+
)
|
| 1408 |
+
if auxiliary_logits is not None:
|
| 1409 |
+
upsampled_auxiliary_logits = nn.functional.interpolate(
|
| 1410 |
+
auxiliary_logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
|
| 1411 |
+
)
|
| 1412 |
+
# compute weighted loss
|
| 1413 |
+
loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
|
| 1414 |
+
main_loss = loss_fct(upsampled_logits, labels)
|
| 1415 |
+
loss = main_loss
|
| 1416 |
+
if auxiliary_logits is not None:
|
| 1417 |
+
auxiliary_loss = loss_fct(upsampled_auxiliary_logits, labels)
|
| 1418 |
+
loss += self.config.auxiliary_loss_weight * auxiliary_loss
|
| 1419 |
+
|
| 1420 |
+
return loss
|
| 1421 |
+
|
| 1422 |
+
@add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
|
| 1423 |
+
@replace_return_docstrings(output_type=SemanticSegmenterOutput, config_class=_CONFIG_FOR_DOC)
|
| 1424 |
+
def forward(
|
| 1425 |
+
self,
|
| 1426 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1427 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1428 |
+
labels: Optional[torch.Tensor] = None,
|
| 1429 |
+
output_attentions: Optional[bool] = None,
|
| 1430 |
+
output_hidden_states: Optional[bool] = None,
|
| 1431 |
+
interpolate_pos_encoding: bool = False,
|
| 1432 |
+
return_dict: Optional[bool] = None,
|
| 1433 |
+
) -> Union[tuple, SemanticSegmenterOutput]:
|
| 1434 |
+
r"""
|
| 1435 |
+
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
|
| 1436 |
+
Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
|
| 1437 |
+
config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
|
| 1438 |
+
|
| 1439 |
+
Returns:
|
| 1440 |
+
|
| 1441 |
+
Examples:
|
| 1442 |
+
|
| 1443 |
+
```python
|
| 1444 |
+
>>> from transformers import AutoImageProcessor, BeitForSemanticSegmentation
|
| 1445 |
+
>>> from PIL import Image
|
| 1446 |
+
>>> import requests
|
| 1447 |
+
|
| 1448 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1449 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1450 |
+
|
| 1451 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
|
| 1452 |
+
>>> model = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640")
|
| 1453 |
+
|
| 1454 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 1455 |
+
>>> outputs = model(**inputs)
|
| 1456 |
+
>>> # logits are of shape (batch_size, num_labels, height, width)
|
| 1457 |
+
>>> logits = outputs.logits
|
| 1458 |
+
```"""
|
| 1459 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1460 |
+
output_hidden_states = (
|
| 1461 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1462 |
+
)
|
| 1463 |
+
|
| 1464 |
+
if labels is not None and self.config.num_labels == 1:
|
| 1465 |
+
raise ValueError("The number of labels should be greater than one")
|
| 1466 |
+
|
| 1467 |
+
outputs = self.beit(
|
| 1468 |
+
pixel_values,
|
| 1469 |
+
head_mask=head_mask,
|
| 1470 |
+
output_attentions=output_attentions,
|
| 1471 |
+
output_hidden_states=True, # we need the intermediate hidden states
|
| 1472 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1473 |
+
return_dict=return_dict,
|
| 1474 |
+
)
|
| 1475 |
+
|
| 1476 |
+
encoder_hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 1477 |
+
|
| 1478 |
+
# only keep certain features, and reshape
|
| 1479 |
+
# note that we do +1 as the encoder_hidden_states also includes the initial embeddings
|
| 1480 |
+
features = [feature for idx, feature in enumerate(encoder_hidden_states) if idx + 1 in self.config.out_indices]
|
| 1481 |
+
batch_size = pixel_values.shape[0]
|
| 1482 |
+
patch_resolution = self.config.image_size // self.config.patch_size
|
| 1483 |
+
features = [
|
| 1484 |
+
x[:, 1:, :].permute(0, 2, 1).reshape(batch_size, -1, patch_resolution, patch_resolution) for x in features
|
| 1485 |
+
]
|
| 1486 |
+
|
| 1487 |
+
# apply FPNs
|
| 1488 |
+
ops = [self.fpn1, self.fpn2, self.fpn3, self.fpn4]
|
| 1489 |
+
for i in range(len(features)):
|
| 1490 |
+
features[i] = ops[i](features[i])
|
| 1491 |
+
|
| 1492 |
+
logits = self.decode_head(features)
|
| 1493 |
+
|
| 1494 |
+
auxiliary_logits = None
|
| 1495 |
+
if self.auxiliary_head is not None:
|
| 1496 |
+
auxiliary_logits = self.auxiliary_head(features)
|
| 1497 |
+
|
| 1498 |
+
loss = None
|
| 1499 |
+
if labels is not None:
|
| 1500 |
+
loss = self.compute_loss(logits, auxiliary_logits, labels)
|
| 1501 |
+
|
| 1502 |
+
if not return_dict:
|
| 1503 |
+
if output_hidden_states:
|
| 1504 |
+
output = (logits,) + outputs[1:]
|
| 1505 |
+
else:
|
| 1506 |
+
output = (logits,) + outputs[2:]
|
| 1507 |
+
return ((loss,) + output) if loss is not None else output
|
| 1508 |
+
|
| 1509 |
+
return SemanticSegmenterOutput(
|
| 1510 |
+
loss=loss,
|
| 1511 |
+
logits=logits,
|
| 1512 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 1513 |
+
attentions=outputs.attentions,
|
| 1514 |
+
)
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
@add_start_docstrings(
|
| 1518 |
+
"""
|
| 1519 |
+
BEiT backbone, to be used with frameworks like DETR and MaskFormer.
|
| 1520 |
+
""",
|
| 1521 |
+
BEIT_START_DOCSTRING,
|
| 1522 |
+
)
|
| 1523 |
+
class BeitBackbone(BeitPreTrainedModel, BackboneMixin):
|
| 1524 |
+
def __init__(self, config):
|
| 1525 |
+
super().__init__(config)
|
| 1526 |
+
super()._init_backbone(config)
|
| 1527 |
+
|
| 1528 |
+
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
|
| 1529 |
+
self.embeddings = BeitEmbeddings(config)
|
| 1530 |
+
self.encoder = BeitEncoder(config, window_size=self.embeddings.patch_embeddings.patch_shape)
|
| 1531 |
+
|
| 1532 |
+
if config.add_fpn:
|
| 1533 |
+
if len(self.config.out_indices) != 4:
|
| 1534 |
+
raise ValueError(
|
| 1535 |
+
"BeitBackbone requires config.out_indices to be a list of 4 integers, "
|
| 1536 |
+
"specifying which features to use from the backbone. One can use [3, 5, 7, 11] in case of "
|
| 1537 |
+
"a base-sized architecture."
|
| 1538 |
+
)
|
| 1539 |
+
hidden_size = config.hidden_size
|
| 1540 |
+
self.fpn1 = nn.Sequential(
|
| 1541 |
+
nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=2, stride=2),
|
| 1542 |
+
nn.BatchNorm2d(hidden_size, eps=config.batch_norm_eps),
|
| 1543 |
+
nn.GELU(),
|
| 1544 |
+
nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=2, stride=2),
|
| 1545 |
+
)
|
| 1546 |
+
|
| 1547 |
+
self.fpn2 = nn.Sequential(nn.ConvTranspose2d(hidden_size, hidden_size, kernel_size=2, stride=2))
|
| 1548 |
+
self.fpn3 = nn.Identity()
|
| 1549 |
+
self.fpn4 = nn.MaxPool2d(kernel_size=2, stride=2)
|
| 1550 |
+
|
| 1551 |
+
# initialize weights and apply final processing
|
| 1552 |
+
self.post_init()
|
| 1553 |
+
|
| 1554 |
+
def get_input_embeddings(self):
|
| 1555 |
+
return self.embeddings.patch_embeddings
|
| 1556 |
+
|
| 1557 |
+
@add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING)
|
| 1558 |
+
@replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
|
| 1559 |
+
def forward(
|
| 1560 |
+
self,
|
| 1561 |
+
pixel_values: Tensor,
|
| 1562 |
+
output_hidden_states: Optional[bool] = None,
|
| 1563 |
+
output_attentions: Optional[bool] = None,
|
| 1564 |
+
return_dict: Optional[bool] = None,
|
| 1565 |
+
) -> BackboneOutput:
|
| 1566 |
+
"""
|
| 1567 |
+
Returns:
|
| 1568 |
+
|
| 1569 |
+
Examples:
|
| 1570 |
+
|
| 1571 |
+
```python
|
| 1572 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 1573 |
+
>>> import torch
|
| 1574 |
+
>>> from PIL import Image
|
| 1575 |
+
>>> import requests
|
| 1576 |
+
|
| 1577 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1578 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1579 |
+
|
| 1580 |
+
>>> processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224")
|
| 1581 |
+
>>> model = AutoBackbone.from_pretrained(
|
| 1582 |
+
... "microsoft/beit-base-patch16-224", out_features=["stage1", "stage2", "stage3", "stage4"]
|
| 1583 |
+
... )
|
| 1584 |
+
|
| 1585 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 1586 |
+
|
| 1587 |
+
>>> outputs = model(**inputs)
|
| 1588 |
+
>>> feature_maps = outputs.feature_maps
|
| 1589 |
+
>>> list(feature_maps[-1].shape)
|
| 1590 |
+
[1, 768, 14, 14]
|
| 1591 |
+
```"""
|
| 1592 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1593 |
+
output_hidden_states = (
|
| 1594 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1595 |
+
)
|
| 1596 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1597 |
+
|
| 1598 |
+
batch_size = pixel_values.shape[0]
|
| 1599 |
+
embedding_output, (patch_height, patch_width) = self.embeddings(pixel_values)
|
| 1600 |
+
resolution = pixel_values.shape[2:]
|
| 1601 |
+
|
| 1602 |
+
outputs = self.encoder(
|
| 1603 |
+
embedding_output,
|
| 1604 |
+
output_hidden_states=True,
|
| 1605 |
+
output_attentions=output_attentions,
|
| 1606 |
+
resolution=resolution,
|
| 1607 |
+
return_dict=return_dict,
|
| 1608 |
+
)
|
| 1609 |
+
|
| 1610 |
+
hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 1611 |
+
|
| 1612 |
+
feature_maps = ()
|
| 1613 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 1614 |
+
if stage in self.out_features:
|
| 1615 |
+
if self.config.reshape_hidden_states:
|
| 1616 |
+
hidden_state = hidden_state[:, 1:, :]
|
| 1617 |
+
hidden_state = hidden_state.permute(0, 2, 1)
|
| 1618 |
+
hidden_state = hidden_state.reshape(batch_size, -1, patch_height, patch_width)
|
| 1619 |
+
|
| 1620 |
+
feature_maps += (hidden_state,)
|
| 1621 |
+
|
| 1622 |
+
if self.config.add_fpn:
|
| 1623 |
+
feature_maps = [
|
| 1624 |
+
self.fpn1(feature_maps[0]),
|
| 1625 |
+
self.fpn2(feature_maps[1]),
|
| 1626 |
+
self.fpn3(feature_maps[2]),
|
| 1627 |
+
self.fpn4(feature_maps[3]),
|
| 1628 |
+
]
|
| 1629 |
+
feature_maps = tuple(feature_maps)
|
| 1630 |
+
|
| 1631 |
+
if not return_dict:
|
| 1632 |
+
if output_hidden_states:
|
| 1633 |
+
output = (feature_maps,) + outputs[1:]
|
| 1634 |
+
else:
|
| 1635 |
+
output = (feature_maps,) + outputs[2:]
|
| 1636 |
+
return output
|
| 1637 |
+
|
| 1638 |
+
return BackboneOutput(
|
| 1639 |
+
feature_maps=feature_maps,
|
| 1640 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 1641 |
+
attentions=outputs.attentions,
|
| 1642 |
+
)
|
| 1643 |
+
|
| 1644 |
+
|
| 1645 |
+
__all__ = [
|
| 1646 |
+
"BeitForImageClassification",
|
| 1647 |
+
"BeitForMaskedImageModeling",
|
| 1648 |
+
"BeitForSemanticSegmentation",
|
| 1649 |
+
"BeitModel",
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 Microsoft Research 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 |
+
|
| 17 |
+
from typing import Callable, List, Optional, Tuple
|
| 18 |
+
|
| 19 |
+
import flax
|
| 20 |
+
import flax.linen as nn
|
| 21 |
+
import jax
|
| 22 |
+
import jax.numpy as jnp
|
| 23 |
+
import numpy as np
|
| 24 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 25 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 26 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 27 |
+
|
| 28 |
+
from ...modeling_flax_outputs import (
|
| 29 |
+
FlaxBaseModelOutput,
|
| 30 |
+
FlaxBaseModelOutputWithPooling,
|
| 31 |
+
FlaxMaskedLMOutput,
|
| 32 |
+
FlaxSequenceClassifierOutput,
|
| 33 |
+
)
|
| 34 |
+
from ...modeling_flax_utils import (
|
| 35 |
+
ACT2FN,
|
| 36 |
+
FlaxPreTrainedModel,
|
| 37 |
+
append_replace_return_docstrings,
|
| 38 |
+
overwrite_call_docstring,
|
| 39 |
+
)
|
| 40 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward
|
| 41 |
+
from .configuration_beit import BeitConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@flax.struct.dataclass
|
| 45 |
+
class FlaxBeitModelOutputWithPooling(FlaxBaseModelOutputWithPooling):
|
| 46 |
+
"""
|
| 47 |
+
Class for outputs of [`FlaxBeitModel`].
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 51 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 52 |
+
pooler_output (`jnp.ndarray` of shape `(batch_size, hidden_size)`):
|
| 53 |
+
Average of the last layer hidden states of the patch tokens (excluding the *[CLS]* token) if
|
| 54 |
+
*config.use_mean_pooling* is set to True. If set to False, then the final hidden state of the *[CLS]* token
|
| 55 |
+
will be returned.
|
| 56 |
+
hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 57 |
+
Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 58 |
+
`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
|
| 59 |
+
the initial embedding outputs.
|
| 60 |
+
attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 61 |
+
Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 62 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 63 |
+
the self-attention heads.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
BEIT_START_DOCSTRING = r"""
|
| 68 |
+
|
| 69 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 70 |
+
library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
|
| 71 |
+
|
| 72 |
+
This model is also a
|
| 73 |
+
[flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
|
| 74 |
+
a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
|
| 75 |
+
behavior.
|
| 76 |
+
|
| 77 |
+
Finally, this model supports inherent JAX features such as:
|
| 78 |
+
|
| 79 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 80 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 81 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 82 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 83 |
+
|
| 84 |
+
Parameters:
|
| 85 |
+
config ([`BeitConfig`]): Model configuration class with all the parameters of the model.
|
| 86 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 87 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 88 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 89 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 90 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 91 |
+
|
| 92 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 93 |
+
specified all the computation will be performed with the given `dtype`.
|
| 94 |
+
|
| 95 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 96 |
+
parameters.**
|
| 97 |
+
|
| 98 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 99 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
BEIT_INPUTS_DOCSTRING = r"""
|
| 103 |
+
Args:
|
| 104 |
+
pixel_values (`numpy.ndarray` of shape `(batch_size, num_channels, height, width)`):
|
| 105 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 106 |
+
[`AutoImageProcessor.__call__`] for details.
|
| 107 |
+
|
| 108 |
+
output_attentions (`bool`, *optional*):
|
| 109 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 110 |
+
tensors for more detail.
|
| 111 |
+
output_hidden_states (`bool`, *optional*):
|
| 112 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 113 |
+
more detail.
|
| 114 |
+
return_dict (`bool`, *optional*):
|
| 115 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def relative_position_index_init(window_size: Tuple[int, int]) -> jnp.ndarray:
|
| 120 |
+
"""
|
| 121 |
+
get pair-wise relative position index for each token inside the window
|
| 122 |
+
"""
|
| 123 |
+
num_relative_distance = (2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3
|
| 124 |
+
|
| 125 |
+
coords_h = np.arange(window_size[0])
|
| 126 |
+
coords_w = np.arange(window_size[1])
|
| 127 |
+
coords = np.stack(np.meshgrid(coords_h, coords_w, indexing="ij")) # 2, Wh, Ww
|
| 128 |
+
coords_flatten = np.reshape(coords, (2, -1))
|
| 129 |
+
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
| 130 |
+
relative_coords = np.transpose(relative_coords, (1, 2, 0)) # Wh*Ww, Wh*Ww, 2
|
| 131 |
+
relative_coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
| 132 |
+
relative_coords[:, :, 1] += window_size[1] - 1
|
| 133 |
+
relative_coords[:, :, 0] *= 2 * window_size[1] - 1
|
| 134 |
+
|
| 135 |
+
relative_position_index = np.zeros(shape=(window_size[0] * window_size[1] + 1,) * 2, dtype=relative_coords.dtype)
|
| 136 |
+
relative_position_index[1:, 1:] = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
| 137 |
+
relative_position_index[0, 0:] = num_relative_distance - 3
|
| 138 |
+
relative_position_index[0:, 0] = num_relative_distance - 2
|
| 139 |
+
relative_position_index[0, 0] = num_relative_distance - 1
|
| 140 |
+
return jnp.array(relative_position_index)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def ones_with_scale(key, shape, scale, dtype=jnp.float32):
|
| 144 |
+
return jnp.ones(shape, dtype) * scale
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class FlaxBeitDropPath(nn.Module):
|
| 148 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 149 |
+
|
| 150 |
+
rate: float
|
| 151 |
+
|
| 152 |
+
@nn.module.compact
|
| 153 |
+
def __call__(self, inputs, deterministic: Optional[bool] = True):
|
| 154 |
+
if self.rate == 0.0:
|
| 155 |
+
return inputs
|
| 156 |
+
keep_prob = 1.0 - self.rate
|
| 157 |
+
if deterministic:
|
| 158 |
+
return inputs
|
| 159 |
+
else:
|
| 160 |
+
shape = (inputs.shape[0],) + (1,) * (inputs.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 161 |
+
rng = self.make_rng("droppath")
|
| 162 |
+
random_tensor = keep_prob + jax.random.uniform(rng, shape=shape, dtype=inputs.dtype)
|
| 163 |
+
binary_tensor = jnp.floor(random_tensor)
|
| 164 |
+
output = inputs / keep_prob * binary_tensor
|
| 165 |
+
return output
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class FlaxBeitPatchEmbeddings(nn.Module):
|
| 169 |
+
config: BeitConfig
|
| 170 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 171 |
+
|
| 172 |
+
def setup(self):
|
| 173 |
+
self.num_channels = self.config.num_channels
|
| 174 |
+
image_size = self.config.image_size
|
| 175 |
+
patch_size = self.config.patch_size
|
| 176 |
+
num_patches = (image_size // patch_size) * (image_size // patch_size)
|
| 177 |
+
patch_shape = (image_size // patch_size, image_size // patch_size)
|
| 178 |
+
self.num_patches = num_patches
|
| 179 |
+
self.patch_shape = patch_shape
|
| 180 |
+
self.projection = nn.Conv(
|
| 181 |
+
self.config.hidden_size,
|
| 182 |
+
kernel_size=(patch_size, patch_size),
|
| 183 |
+
strides=(patch_size, patch_size),
|
| 184 |
+
padding="VALID",
|
| 185 |
+
dtype=self.dtype,
|
| 186 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def __call__(self, pixel_values):
|
| 190 |
+
num_channels = pixel_values.shape[-1]
|
| 191 |
+
if num_channels != self.num_channels:
|
| 192 |
+
raise ValueError(
|
| 193 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 194 |
+
)
|
| 195 |
+
embeddings = self.projection(pixel_values)
|
| 196 |
+
batch_size, _, _, channels = embeddings.shape
|
| 197 |
+
return jnp.reshape(embeddings, (batch_size, -1, channels))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class FlaxBeitEmbeddings(nn.Module):
|
| 201 |
+
"""Construct the CLS token, position and patch embeddings."""
|
| 202 |
+
|
| 203 |
+
config: BeitConfig
|
| 204 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 205 |
+
|
| 206 |
+
def setup(self):
|
| 207 |
+
self.cls_token = self.param("cls_token", nn.initializers.zeros, (1, 1, self.config.hidden_size))
|
| 208 |
+
if self.config.use_mask_token:
|
| 209 |
+
self.mask_token = self.param("mask_token", nn.initializers.zeros, (1, 1, self.config.hidden_size))
|
| 210 |
+
self.patch_embeddings = FlaxBeitPatchEmbeddings(self.config, dtype=self.dtype)
|
| 211 |
+
num_patches = self.patch_embeddings.num_patches
|
| 212 |
+
if self.config.use_absolute_position_embeddings:
|
| 213 |
+
self.position_embeddings = self.param(
|
| 214 |
+
"position_embeddings", nn.initializers.zeros, (1, num_patches + 1, self.config.hidden_size)
|
| 215 |
+
)
|
| 216 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 217 |
+
|
| 218 |
+
def __call__(self, pixel_values, bool_masked_pos=None, deterministic=True):
|
| 219 |
+
embeddings = self.patch_embeddings(pixel_values)
|
| 220 |
+
batch_size, seq_len, _ = embeddings.shape
|
| 221 |
+
|
| 222 |
+
cls_tokens = jnp.broadcast_to(self.cls_token, (batch_size, 1, self.config.hidden_size))
|
| 223 |
+
cls_tokens = cls_tokens.astype(embeddings.dtype)
|
| 224 |
+
|
| 225 |
+
if bool_masked_pos is not None:
|
| 226 |
+
mask_tokens = jnp.broadcast_to(self.mask_token, (batch_size, seq_len, self.config.hidden_size))
|
| 227 |
+
mask_tokens = mask_tokens.astype(embeddings.dtype)
|
| 228 |
+
# replace the masked visual tokens by mask_tokens
|
| 229 |
+
w = jnp.expand_dims(bool_masked_pos, axis=-1)
|
| 230 |
+
embeddings = embeddings * (1 - w) + mask_tokens * w
|
| 231 |
+
|
| 232 |
+
embeddings = jnp.concatenate((cls_tokens, embeddings), axis=1)
|
| 233 |
+
|
| 234 |
+
if self.config.use_absolute_position_embeddings:
|
| 235 |
+
embeddings = embeddings + self.position_embeddings.astype(embeddings.dtype)
|
| 236 |
+
|
| 237 |
+
embeddings = self.dropout(embeddings, deterministic=deterministic)
|
| 238 |
+
return embeddings
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class FlaxBeitRelativePositionBias(nn.Module):
|
| 242 |
+
config: BeitConfig
|
| 243 |
+
window_size: Tuple[int, int]
|
| 244 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 245 |
+
|
| 246 |
+
def setup(self):
|
| 247 |
+
num_relative_distance = (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1) + 3
|
| 248 |
+
self.relative_position_bias_table = self.param(
|
| 249 |
+
"relative_position_bias_table",
|
| 250 |
+
nn.initializers.zeros,
|
| 251 |
+
(num_relative_distance, self.config.num_attention_heads),
|
| 252 |
+
) # 2*Wh-1 * 2*Ww-1, nH
|
| 253 |
+
# cls to token & token 2 cls & cls to cls
|
| 254 |
+
|
| 255 |
+
self.relative_position_index = relative_position_index_init(self.window_size)
|
| 256 |
+
|
| 257 |
+
def __call__(self):
|
| 258 |
+
index = self.relative_position_index.reshape(-1)
|
| 259 |
+
shape = (self.window_size[0] * self.window_size[1] + 1, self.window_size[0] * self.window_size[1] + 1, -1)
|
| 260 |
+
relative_position_bias = self.relative_position_bias_table[index].reshape(shape) # Wh*Ww,Wh*Ww,nH
|
| 261 |
+
return jnp.transpose(relative_position_bias, (2, 0, 1))
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class FlaxBeitSelfAttention(nn.Module):
|
| 265 |
+
config: BeitConfig
|
| 266 |
+
window_size: Tuple[int, int]
|
| 267 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 268 |
+
|
| 269 |
+
def setup(self):
|
| 270 |
+
if self.config.hidden_size % self.config.num_attention_heads != 0 and not hasattr(
|
| 271 |
+
self.config, "embedding_size"
|
| 272 |
+
):
|
| 273 |
+
raise ValueError(
|
| 274 |
+
f"The hidden size {self.config.hidden_size} is not a multiple of the number of attention "
|
| 275 |
+
f"heads {self.config.num_attention_heads}."
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
self.query = nn.Dense(
|
| 279 |
+
self.config.hidden_size,
|
| 280 |
+
dtype=self.dtype,
|
| 281 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 282 |
+
)
|
| 283 |
+
self.key = nn.Dense(
|
| 284 |
+
self.config.hidden_size,
|
| 285 |
+
dtype=self.dtype,
|
| 286 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 287 |
+
use_bias=False,
|
| 288 |
+
)
|
| 289 |
+
self.value = nn.Dense(
|
| 290 |
+
self.config.hidden_size,
|
| 291 |
+
dtype=self.dtype,
|
| 292 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
self.relative_position_bias = (
|
| 296 |
+
FlaxBeitRelativePositionBias(self.config, window_size=self.window_size, dtype=self.dtype)
|
| 297 |
+
if self.window_size
|
| 298 |
+
else None
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
def __call__(
|
| 302 |
+
self, hidden_states, relative_position_bias=None, deterministic: bool = True, output_attentions: bool = False
|
| 303 |
+
):
|
| 304 |
+
head_dim = self.config.hidden_size // self.config.num_attention_heads
|
| 305 |
+
|
| 306 |
+
query_states = self.query(hidden_states).reshape(
|
| 307 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 308 |
+
)
|
| 309 |
+
value_states = self.value(hidden_states).reshape(
|
| 310 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 311 |
+
)
|
| 312 |
+
key_states = self.key(hidden_states).reshape(
|
| 313 |
+
hidden_states.shape[:2] + (self.config.num_attention_heads, head_dim)
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
dropout_rng = None
|
| 317 |
+
if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
|
| 318 |
+
dropout_rng = self.make_rng("dropout")
|
| 319 |
+
|
| 320 |
+
attention_bias = jnp.array(0.0, dtype=self.dtype)
|
| 321 |
+
# Add relative position bias if present.
|
| 322 |
+
if self.relative_position_bias is not None:
|
| 323 |
+
attention_bias = jnp.expand_dims(self.relative_position_bias(), 0)
|
| 324 |
+
attention_bias = attention_bias.astype(query_states.dtype)
|
| 325 |
+
|
| 326 |
+
# Add shared relative position bias if provided.
|
| 327 |
+
if relative_position_bias is not None:
|
| 328 |
+
attention_bias = attention_bias + relative_position_bias.astype(attention_bias.dtype)
|
| 329 |
+
|
| 330 |
+
attn_weights = dot_product_attention_weights(
|
| 331 |
+
query_states,
|
| 332 |
+
key_states,
|
| 333 |
+
bias=attention_bias,
|
| 334 |
+
dropout_rng=dropout_rng,
|
| 335 |
+
dropout_rate=self.config.attention_probs_dropout_prob,
|
| 336 |
+
broadcast_dropout=True,
|
| 337 |
+
deterministic=deterministic,
|
| 338 |
+
dtype=self.dtype,
|
| 339 |
+
precision=None,
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
|
| 343 |
+
attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
|
| 344 |
+
|
| 345 |
+
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
|
| 346 |
+
return outputs
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class FlaxBeitSelfOutput(nn.Module):
|
| 350 |
+
config: BeitConfig
|
| 351 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 352 |
+
|
| 353 |
+
def setup(self):
|
| 354 |
+
self.dense = nn.Dense(
|
| 355 |
+
self.config.hidden_size,
|
| 356 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 357 |
+
dtype=self.dtype,
|
| 358 |
+
)
|
| 359 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 360 |
+
|
| 361 |
+
def __call__(self, hidden_states, deterministic: bool = True):
|
| 362 |
+
hidden_states = self.dense(hidden_states)
|
| 363 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 364 |
+
return hidden_states
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class FlaxBeitAttention(nn.Module):
|
| 368 |
+
config: BeitConfig
|
| 369 |
+
window_size: Tuple[int, int]
|
| 370 |
+
dtype: jnp.dtype = jnp.float32
|
| 371 |
+
|
| 372 |
+
def setup(self):
|
| 373 |
+
self.attention = FlaxBeitSelfAttention(self.config, self.window_size, dtype=self.dtype)
|
| 374 |
+
self.output = FlaxBeitSelfOutput(self.config, dtype=self.dtype)
|
| 375 |
+
|
| 376 |
+
def __call__(
|
| 377 |
+
self, hidden_states, relative_position_bias=None, deterministic=True, output_attentions: bool = False
|
| 378 |
+
):
|
| 379 |
+
attn_outputs = self.attention(
|
| 380 |
+
hidden_states, relative_position_bias, deterministic=deterministic, output_attentions=output_attentions
|
| 381 |
+
)
|
| 382 |
+
attn_output = attn_outputs[0]
|
| 383 |
+
attn_output = self.output(attn_output, deterministic=deterministic)
|
| 384 |
+
|
| 385 |
+
outputs = (attn_output,)
|
| 386 |
+
|
| 387 |
+
if output_attentions:
|
| 388 |
+
outputs += (attn_outputs[1],)
|
| 389 |
+
|
| 390 |
+
return outputs
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class FlaxBeitIntermediate(nn.Module):
|
| 394 |
+
config: BeitConfig
|
| 395 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 396 |
+
|
| 397 |
+
def setup(self):
|
| 398 |
+
self.dense = nn.Dense(
|
| 399 |
+
self.config.intermediate_size,
|
| 400 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 401 |
+
dtype=self.dtype,
|
| 402 |
+
)
|
| 403 |
+
self.activation = ACT2FN[self.config.hidden_act]
|
| 404 |
+
|
| 405 |
+
def __call__(self, hidden_states):
|
| 406 |
+
hidden_states = self.dense(hidden_states)
|
| 407 |
+
hidden_states = self.activation(hidden_states)
|
| 408 |
+
|
| 409 |
+
return hidden_states
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class FlaxBeitOutput(nn.Module):
|
| 413 |
+
config: BeitConfig
|
| 414 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 415 |
+
|
| 416 |
+
def setup(self):
|
| 417 |
+
self.dense = nn.Dense(
|
| 418 |
+
self.config.hidden_size,
|
| 419 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 420 |
+
dtype=self.dtype,
|
| 421 |
+
)
|
| 422 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 423 |
+
|
| 424 |
+
def __call__(self, hidden_states, deterministic: bool = True):
|
| 425 |
+
hidden_states = self.dense(hidden_states)
|
| 426 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 427 |
+
|
| 428 |
+
return hidden_states
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class FlaxBeitLayer(nn.Module):
|
| 432 |
+
config: BeitConfig
|
| 433 |
+
window_size: Tuple[int, int]
|
| 434 |
+
drop_path_rate: float
|
| 435 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 436 |
+
|
| 437 |
+
def setup(self):
|
| 438 |
+
self.attention = FlaxBeitAttention(self.config, self.window_size, dtype=self.dtype)
|
| 439 |
+
self.intermediate = FlaxBeitIntermediate(self.config, dtype=self.dtype)
|
| 440 |
+
self.output = FlaxBeitOutput(self.config, dtype=self.dtype)
|
| 441 |
+
self.layernorm_before = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 442 |
+
self.drop_path = FlaxBeitDropPath(rate=self.drop_path_rate)
|
| 443 |
+
self.layernorm_after = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 444 |
+
|
| 445 |
+
self.init_values = self.config.layer_scale_init_value
|
| 446 |
+
if self.init_values > 0:
|
| 447 |
+
self.lambda_1 = self.param("lambda_1", ones_with_scale, (self.config.hidden_size), self.init_values)
|
| 448 |
+
self.lambda_2 = self.param("lambda_2", ones_with_scale, (self.config.hidden_size), self.init_values)
|
| 449 |
+
else:
|
| 450 |
+
self.lambda_1 = None
|
| 451 |
+
self.lambda_2 = None
|
| 452 |
+
|
| 453 |
+
def __call__(
|
| 454 |
+
self, hidden_states, relative_position_bias=None, deterministic: bool = True, output_attentions: bool = False
|
| 455 |
+
):
|
| 456 |
+
self_attention_outputs = self.attention(
|
| 457 |
+
self.layernorm_before(hidden_states), # in BEiT, layernorm is applied before self-attention
|
| 458 |
+
relative_position_bias,
|
| 459 |
+
deterministic=deterministic,
|
| 460 |
+
output_attentions=output_attentions,
|
| 461 |
+
)
|
| 462 |
+
attention_output = self_attention_outputs[0]
|
| 463 |
+
|
| 464 |
+
# apply lambda_1 if present
|
| 465 |
+
if self.lambda_1 is not None:
|
| 466 |
+
attention_output = self.lambda_1.astype(attention_output.dtype) * attention_output
|
| 467 |
+
|
| 468 |
+
# first residual connection
|
| 469 |
+
hidden_states = self.drop_path(attention_output, deterministic=deterministic) + hidden_states
|
| 470 |
+
|
| 471 |
+
# in BEiT, layernorm is also applied after self-attention
|
| 472 |
+
layer_output = self.layernorm_after(hidden_states)
|
| 473 |
+
|
| 474 |
+
layer_output = self.intermediate(layer_output)
|
| 475 |
+
layer_output = self.output(layer_output, deterministic=deterministic)
|
| 476 |
+
|
| 477 |
+
# apply lambda_2 if present
|
| 478 |
+
if self.lambda_2 is not None:
|
| 479 |
+
layer_output = self.lambda_2.astype(layer_output.dtype) * layer_output
|
| 480 |
+
|
| 481 |
+
# second residual connection
|
| 482 |
+
layer_output = self.drop_path(layer_output, deterministic=deterministic) + hidden_states
|
| 483 |
+
|
| 484 |
+
outputs = (layer_output,)
|
| 485 |
+
|
| 486 |
+
if output_attentions:
|
| 487 |
+
outputs += (self_attention_outputs[1],)
|
| 488 |
+
|
| 489 |
+
return outputs
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class FlaxBeitLayerCollection(nn.Module):
|
| 493 |
+
config: BeitConfig
|
| 494 |
+
window_size: Tuple[int, int]
|
| 495 |
+
drop_path_rates: List[float]
|
| 496 |
+
relative_position_bias: Callable[[], jnp.ndarray]
|
| 497 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 498 |
+
|
| 499 |
+
def setup(self):
|
| 500 |
+
self.layers = [
|
| 501 |
+
FlaxBeitLayer(
|
| 502 |
+
self.config,
|
| 503 |
+
window_size=self.window_size if self.config.use_relative_position_bias else None,
|
| 504 |
+
drop_path_rate=self.drop_path_rates[i],
|
| 505 |
+
name=str(i),
|
| 506 |
+
dtype=self.dtype,
|
| 507 |
+
)
|
| 508 |
+
for i in range(self.config.num_hidden_layers)
|
| 509 |
+
]
|
| 510 |
+
|
| 511 |
+
def __call__(
|
| 512 |
+
self,
|
| 513 |
+
hidden_states,
|
| 514 |
+
deterministic: bool = True,
|
| 515 |
+
output_attentions: bool = False,
|
| 516 |
+
output_hidden_states: bool = False,
|
| 517 |
+
return_dict: bool = True,
|
| 518 |
+
):
|
| 519 |
+
all_attentions = () if output_attentions else None
|
| 520 |
+
all_hidden_states = () if output_hidden_states else None
|
| 521 |
+
|
| 522 |
+
for i, layer in enumerate(self.layers):
|
| 523 |
+
if output_hidden_states:
|
| 524 |
+
all_hidden_states += (hidden_states,)
|
| 525 |
+
relative_position_bias = self.relative_position_bias() if self.relative_position_bias is not None else None
|
| 526 |
+
layer_outputs = layer(
|
| 527 |
+
hidden_states, relative_position_bias, deterministic=deterministic, output_attentions=output_attentions
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
hidden_states = layer_outputs[0]
|
| 531 |
+
|
| 532 |
+
if output_attentions:
|
| 533 |
+
all_attentions += (layer_outputs[1],)
|
| 534 |
+
|
| 535 |
+
if output_hidden_states:
|
| 536 |
+
all_hidden_states += (hidden_states,)
|
| 537 |
+
|
| 538 |
+
outputs = (hidden_states,)
|
| 539 |
+
if not return_dict:
|
| 540 |
+
return tuple(v for v in outputs if v is not None)
|
| 541 |
+
|
| 542 |
+
return FlaxBaseModelOutput(
|
| 543 |
+
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
class FlaxBeitEncoder(nn.Module):
|
| 548 |
+
config: BeitConfig
|
| 549 |
+
window_size: Tuple[int, int]
|
| 550 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 551 |
+
|
| 552 |
+
def setup(self):
|
| 553 |
+
if self.config.use_shared_relative_position_bias:
|
| 554 |
+
self.relative_position_bias = FlaxBeitRelativePositionBias(
|
| 555 |
+
config=self.config, window_size=self.window_size, dtype=self.dtype
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
# stochastic depth decay rule
|
| 559 |
+
drop_path_rates = list(np.linspace(0, self.config.drop_path_rate, self.config.num_hidden_layers))
|
| 560 |
+
self.layer = FlaxBeitLayerCollection(
|
| 561 |
+
self.config,
|
| 562 |
+
window_size=self.window_size,
|
| 563 |
+
drop_path_rates=drop_path_rates,
|
| 564 |
+
relative_position_bias=self.relative_position_bias
|
| 565 |
+
if self.config.use_shared_relative_position_bias
|
| 566 |
+
else None,
|
| 567 |
+
dtype=self.dtype,
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
def __call__(
|
| 571 |
+
self,
|
| 572 |
+
hidden_states,
|
| 573 |
+
deterministic: bool = True,
|
| 574 |
+
output_attentions: bool = False,
|
| 575 |
+
output_hidden_states: bool = False,
|
| 576 |
+
return_dict: bool = True,
|
| 577 |
+
):
|
| 578 |
+
return self.layer(
|
| 579 |
+
hidden_states,
|
| 580 |
+
deterministic=deterministic,
|
| 581 |
+
output_attentions=output_attentions,
|
| 582 |
+
output_hidden_states=output_hidden_states,
|
| 583 |
+
return_dict=return_dict,
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
class FlaxBeitPreTrainedModel(FlaxPreTrainedModel):
|
| 588 |
+
"""
|
| 589 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 590 |
+
models.
|
| 591 |
+
"""
|
| 592 |
+
|
| 593 |
+
config_class = BeitConfig
|
| 594 |
+
base_model_prefix = "beit"
|
| 595 |
+
main_input_name = "pixel_values"
|
| 596 |
+
module_class: nn.Module = None
|
| 597 |
+
|
| 598 |
+
def __init__(
|
| 599 |
+
self,
|
| 600 |
+
config: BeitConfig,
|
| 601 |
+
input_shape=None,
|
| 602 |
+
seed: int = 0,
|
| 603 |
+
dtype: jnp.dtype = jnp.float32,
|
| 604 |
+
_do_init: bool = True,
|
| 605 |
+
**kwargs,
|
| 606 |
+
):
|
| 607 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 608 |
+
if input_shape is None:
|
| 609 |
+
input_shape = (1, config.image_size, config.image_size, config.num_channels)
|
| 610 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 611 |
+
|
| 612 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 613 |
+
# init input tensors
|
| 614 |
+
pixel_values = jnp.zeros(input_shape, dtype=self.dtype)
|
| 615 |
+
|
| 616 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 617 |
+
dropout_rng, droppath_rng = jax.random.split(dropout_rng)
|
| 618 |
+
rngs = {"params": params_rng, "dropout": dropout_rng, "droppath": droppath_rng}
|
| 619 |
+
|
| 620 |
+
random_params = self.module.init(rngs, pixel_values, return_dict=False)["params"]
|
| 621 |
+
|
| 622 |
+
if params is not None:
|
| 623 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 624 |
+
params = flatten_dict(unfreeze(params))
|
| 625 |
+
for missing_key in self._missing_keys:
|
| 626 |
+
params[missing_key] = random_params[missing_key]
|
| 627 |
+
self._missing_keys = set()
|
| 628 |
+
return freeze(unflatten_dict(params))
|
| 629 |
+
else:
|
| 630 |
+
return random_params
|
| 631 |
+
|
| 632 |
+
@add_start_docstrings_to_model_forward(BEIT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 633 |
+
def __call__(
|
| 634 |
+
self,
|
| 635 |
+
pixel_values,
|
| 636 |
+
bool_masked_pos=None,
|
| 637 |
+
params: dict = None,
|
| 638 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 639 |
+
train: bool = False,
|
| 640 |
+
output_attentions: Optional[bool] = None,
|
| 641 |
+
output_hidden_states: Optional[bool] = None,
|
| 642 |
+
return_dict: Optional[bool] = None,
|
| 643 |
+
):
|
| 644 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 645 |
+
output_hidden_states = (
|
| 646 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 647 |
+
)
|
| 648 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 649 |
+
|
| 650 |
+
pixel_values = jnp.transpose(pixel_values, (0, 2, 3, 1))
|
| 651 |
+
# Handle any PRNG if needed
|
| 652 |
+
rngs = {}
|
| 653 |
+
if dropout_rng is not None:
|
| 654 |
+
dropout_rng, droppath_rng = jax.random.split(dropout_rng)
|
| 655 |
+
rngs["dropout"] = dropout_rng
|
| 656 |
+
rngs["droppath"] = droppath_rng
|
| 657 |
+
|
| 658 |
+
return self.module.apply(
|
| 659 |
+
{"params": params or self.params},
|
| 660 |
+
jnp.array(pixel_values, dtype=jnp.float32),
|
| 661 |
+
bool_masked_pos,
|
| 662 |
+
not train,
|
| 663 |
+
output_attentions,
|
| 664 |
+
output_hidden_states,
|
| 665 |
+
return_dict,
|
| 666 |
+
rngs=rngs,
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
class FlaxBeitPooler(nn.Module):
|
| 671 |
+
config: BeitConfig
|
| 672 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 673 |
+
|
| 674 |
+
def setup(self):
|
| 675 |
+
if self.config.use_mean_pooling:
|
| 676 |
+
self.layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 677 |
+
|
| 678 |
+
def __call__(self, hidden_states):
|
| 679 |
+
if self.config.use_mean_pooling:
|
| 680 |
+
# Mean pool the final hidden states of the patch tokens
|
| 681 |
+
patch_tokens = hidden_states[:, 1:, :]
|
| 682 |
+
pooled_output = self.layernorm(jnp.mean(patch_tokens, axis=1))
|
| 683 |
+
else:
|
| 684 |
+
# Pool by simply taking the final hidden state of the [CLS] token
|
| 685 |
+
pooled_output = hidden_states[:, 0]
|
| 686 |
+
|
| 687 |
+
return pooled_output
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
class FlaxBeitModule(nn.Module):
|
| 691 |
+
config: BeitConfig
|
| 692 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 693 |
+
add_pooling_layer: bool = True
|
| 694 |
+
|
| 695 |
+
def setup(self):
|
| 696 |
+
self.embeddings = FlaxBeitEmbeddings(self.config, dtype=self.dtype)
|
| 697 |
+
self.encoder = FlaxBeitEncoder(
|
| 698 |
+
self.config, window_size=self.embeddings.patch_embeddings.patch_shape, dtype=self.dtype
|
| 699 |
+
)
|
| 700 |
+
if not self.config.use_mean_pooling:
|
| 701 |
+
self.layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 702 |
+
self.pooler = FlaxBeitPooler(self.config, dtype=self.dtype) if self.add_pooling_layer else None
|
| 703 |
+
|
| 704 |
+
def __call__(
|
| 705 |
+
self,
|
| 706 |
+
pixel_values,
|
| 707 |
+
bool_masked_pos=None,
|
| 708 |
+
deterministic: bool = True,
|
| 709 |
+
output_attentions: bool = False,
|
| 710 |
+
output_hidden_states: bool = False,
|
| 711 |
+
return_dict: bool = True,
|
| 712 |
+
):
|
| 713 |
+
hidden_states = self.embeddings(pixel_values, bool_masked_pos, deterministic=deterministic)
|
| 714 |
+
|
| 715 |
+
outputs = self.encoder(
|
| 716 |
+
hidden_states,
|
| 717 |
+
deterministic=deterministic,
|
| 718 |
+
output_attentions=output_attentions,
|
| 719 |
+
output_hidden_states=output_hidden_states,
|
| 720 |
+
return_dict=return_dict,
|
| 721 |
+
)
|
| 722 |
+
hidden_states = outputs[0]
|
| 723 |
+
if not self.config.use_mean_pooling:
|
| 724 |
+
hidden_states = self.layernorm(hidden_states)
|
| 725 |
+
pooled = self.pooler(hidden_states) if self.add_pooling_layer else None
|
| 726 |
+
|
| 727 |
+
if not return_dict:
|
| 728 |
+
# if pooled is None, don't return it
|
| 729 |
+
if pooled is None:
|
| 730 |
+
return (hidden_states,) + outputs[1:]
|
| 731 |
+
return (hidden_states, pooled) + outputs[1:]
|
| 732 |
+
|
| 733 |
+
return FlaxBeitModelOutputWithPooling(
|
| 734 |
+
last_hidden_state=hidden_states,
|
| 735 |
+
pooler_output=pooled,
|
| 736 |
+
hidden_states=outputs.hidden_states,
|
| 737 |
+
attentions=outputs.attentions,
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
@add_start_docstrings(
|
| 742 |
+
"The bare Beit Model transformer outputting raw hidden-states without any specific head on top.",
|
| 743 |
+
BEIT_START_DOCSTRING,
|
| 744 |
+
)
|
| 745 |
+
class FlaxBeitModel(FlaxBeitPreTrainedModel):
|
| 746 |
+
module_class = FlaxBeitModule
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
FLAX_BEIT_MODEL_DOCSTRING = """
|
| 750 |
+
Returns:
|
| 751 |
+
|
| 752 |
+
Examples:
|
| 753 |
+
|
| 754 |
+
```python
|
| 755 |
+
>>> from transformers import AutoImageProcessor, FlaxBeitModel
|
| 756 |
+
>>> from PIL import Image
|
| 757 |
+
>>> import requests
|
| 758 |
+
|
| 759 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 760 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 761 |
+
|
| 762 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k-ft22k")
|
| 763 |
+
>>> model = FlaxBeitModel.from_pretrained("microsoft/beit-base-patch16-224-pt22k-ft22k")
|
| 764 |
+
|
| 765 |
+
>>> inputs = image_processor(images=image, return_tensors="np")
|
| 766 |
+
>>> outputs = model(**inputs)
|
| 767 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 768 |
+
```
|
| 769 |
+
"""
|
| 770 |
+
|
| 771 |
+
overwrite_call_docstring(FlaxBeitModel, FLAX_BEIT_MODEL_DOCSTRING)
|
| 772 |
+
append_replace_return_docstrings(FlaxBeitModel, output_type=FlaxBeitModelOutputWithPooling, config_class=BeitConfig)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
class FlaxBeitForMaskedImageModelingModule(nn.Module):
|
| 776 |
+
config: BeitConfig
|
| 777 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 778 |
+
|
| 779 |
+
def setup(self):
|
| 780 |
+
self.beit = FlaxBeitModule(self.config, add_pooling_layer=False, dtype=self.dtype)
|
| 781 |
+
|
| 782 |
+
# Classifier head
|
| 783 |
+
self.layernorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 784 |
+
self.lm_head = nn.Dense(
|
| 785 |
+
self.config.vocab_size,
|
| 786 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 787 |
+
dtype=self.dtype,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
def __call__(
|
| 791 |
+
self,
|
| 792 |
+
pixel_values=None,
|
| 793 |
+
bool_masked_pos=None,
|
| 794 |
+
deterministic: bool = True,
|
| 795 |
+
output_attentions=None,
|
| 796 |
+
output_hidden_states=None,
|
| 797 |
+
return_dict=None,
|
| 798 |
+
):
|
| 799 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 800 |
+
|
| 801 |
+
outputs = self.beit(
|
| 802 |
+
pixel_values,
|
| 803 |
+
bool_masked_pos,
|
| 804 |
+
deterministic=deterministic,
|
| 805 |
+
output_attentions=output_attentions,
|
| 806 |
+
output_hidden_states=output_hidden_states,
|
| 807 |
+
return_dict=return_dict,
|
| 808 |
+
)
|
| 809 |
+
|
| 810 |
+
sequence_output = outputs[0]
|
| 811 |
+
sequence_output = self.layernorm(sequence_output)
|
| 812 |
+
prediction_scores = self.lm_head(sequence_output[:, 1:])
|
| 813 |
+
|
| 814 |
+
if not return_dict:
|
| 815 |
+
output = (prediction_scores,) + outputs[2:]
|
| 816 |
+
return output
|
| 817 |
+
|
| 818 |
+
return FlaxMaskedLMOutput(
|
| 819 |
+
logits=prediction_scores,
|
| 820 |
+
hidden_states=outputs.hidden_states,
|
| 821 |
+
attentions=outputs.attentions,
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
@add_start_docstrings(
|
| 826 |
+
"Beit Model transformer with a 'language' modeling head on top (to predict visual tokens).",
|
| 827 |
+
BEIT_START_DOCSTRING,
|
| 828 |
+
)
|
| 829 |
+
class FlaxBeitForMaskedImageModeling(FlaxBeitPreTrainedModel):
|
| 830 |
+
module_class = FlaxBeitForMaskedImageModelingModule
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
FLAX_BEIT_MLM_DOCSTRING = """
|
| 834 |
+
bool_masked_pos (`numpy.ndarray` of shape `(batch_size, num_patches)`):
|
| 835 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
| 836 |
+
|
| 837 |
+
Returns:
|
| 838 |
+
|
| 839 |
+
Examples:
|
| 840 |
+
|
| 841 |
+
```python
|
| 842 |
+
>>> from transformers import AutoImageProcessor, BeitForMaskedImageModeling
|
| 843 |
+
>>> from PIL import Image
|
| 844 |
+
>>> import requests
|
| 845 |
+
|
| 846 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 847 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 848 |
+
|
| 849 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 850 |
+
>>> model = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k")
|
| 851 |
+
|
| 852 |
+
>>> inputs = image_processor(images=image, return_tensors="np")
|
| 853 |
+
>>> outputs = model(**inputs)
|
| 854 |
+
>>> logits = outputs.logits
|
| 855 |
+
```
|
| 856 |
+
"""
|
| 857 |
+
|
| 858 |
+
overwrite_call_docstring(FlaxBeitForMaskedImageModeling, FLAX_BEIT_MLM_DOCSTRING)
|
| 859 |
+
append_replace_return_docstrings(
|
| 860 |
+
FlaxBeitForMaskedImageModeling, output_type=FlaxMaskedLMOutput, config_class=BeitConfig
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
class FlaxBeitForImageClassificationModule(nn.Module):
|
| 865 |
+
config: BeitConfig
|
| 866 |
+
dtype: jnp.dtype = jnp.float32
|
| 867 |
+
|
| 868 |
+
def setup(self):
|
| 869 |
+
self.beit = FlaxBeitModule(config=self.config, dtype=self.dtype, add_pooling_layer=True)
|
| 870 |
+
self.classifier = nn.Dense(
|
| 871 |
+
self.config.num_labels,
|
| 872 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 873 |
+
dtype=self.dtype,
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
def __call__(
|
| 877 |
+
self,
|
| 878 |
+
pixel_values=None,
|
| 879 |
+
bool_masked_pos=None,
|
| 880 |
+
deterministic: bool = True,
|
| 881 |
+
output_attentions=None,
|
| 882 |
+
output_hidden_states=None,
|
| 883 |
+
return_dict=None,
|
| 884 |
+
):
|
| 885 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 886 |
+
|
| 887 |
+
outputs = self.beit(
|
| 888 |
+
pixel_values,
|
| 889 |
+
deterministic=deterministic,
|
| 890 |
+
output_attentions=output_attentions,
|
| 891 |
+
output_hidden_states=output_hidden_states,
|
| 892 |
+
return_dict=return_dict,
|
| 893 |
+
)
|
| 894 |
+
|
| 895 |
+
pooled_output = outputs[1]
|
| 896 |
+
logits = self.classifier(pooled_output)
|
| 897 |
+
|
| 898 |
+
if not return_dict:
|
| 899 |
+
output = (logits,) + outputs[2:]
|
| 900 |
+
return output
|
| 901 |
+
|
| 902 |
+
return FlaxSequenceClassifierOutput(
|
| 903 |
+
logits=logits,
|
| 904 |
+
hidden_states=outputs.hidden_states,
|
| 905 |
+
attentions=outputs.attentions,
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
@add_start_docstrings(
|
| 910 |
+
"""
|
| 911 |
+
Beit Model transformer with an image classification head on top (a linear layer on top of the average of the final
|
| 912 |
+
hidden states of the patch tokens) e.g. for ImageNet.
|
| 913 |
+
""",
|
| 914 |
+
BEIT_START_DOCSTRING,
|
| 915 |
+
)
|
| 916 |
+
class FlaxBeitForImageClassification(FlaxBeitPreTrainedModel):
|
| 917 |
+
module_class = FlaxBeitForImageClassificationModule
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
FLAX_BEIT_CLASSIF_DOCSTRING = """
|
| 921 |
+
Returns:
|
| 922 |
+
|
| 923 |
+
Example:
|
| 924 |
+
|
| 925 |
+
```python
|
| 926 |
+
>>> from transformers import AutoImageProcessor, FlaxBeitForImageClassification
|
| 927 |
+
>>> from PIL import Image
|
| 928 |
+
>>> import requests
|
| 929 |
+
|
| 930 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 931 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 932 |
+
|
| 933 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/beit-base-patch16-224")
|
| 934 |
+
>>> model = FlaxBeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224")
|
| 935 |
+
|
| 936 |
+
>>> inputs = image_processor(images=image, return_tensors="np")
|
| 937 |
+
>>> outputs = model(**inputs)
|
| 938 |
+
>>> logits = outputs.logits
|
| 939 |
+
>>> # model predicts one of the 1000 ImageNet classes
|
| 940 |
+
>>> predicted_class_idx = logits.argmax(-1).item()
|
| 941 |
+
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
|
| 942 |
+
```
|
| 943 |
+
"""
|
| 944 |
+
|
| 945 |
+
overwrite_call_docstring(FlaxBeitForImageClassification, FLAX_BEIT_CLASSIF_DOCSTRING)
|
| 946 |
+
append_replace_return_docstrings(
|
| 947 |
+
FlaxBeitForImageClassification, output_type=FlaxSequenceClassifierOutput, config_class=BeitConfig
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
__all__ = [
|
| 952 |
+
"FlaxBeitForImageClassification",
|
| 953 |
+
"FlaxBeitForMaskedImageModeling",
|
| 954 |
+
"FlaxBeitModel",
|
| 955 |
+
"FlaxBeitPreTrainedModel",
|
| 956 |
+
]
|
lib/python3.12/site-packages/transformers/models/bert_generation/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_bert_generation import *
|
| 22 |
+
from .modeling_bert_generation import *
|
| 23 |
+
from .tokenization_bert_generation import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (737 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-312.pyc
ADDED
|
Binary file (5.93 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-312.pyc
ADDED
|
Binary file (49.5 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-312.pyc
ADDED
|
Binary file (9.07 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/bert_generation/configuration_bert_generation.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The Google AI Language 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 |
+
"""BertGeneration model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class BertGenerationConfig(PretrainedConfig):
|
| 21 |
+
r"""
|
| 22 |
+
This is the configuration class to store the configuration of a [`BertGenerationPreTrainedModel`]. It is used to
|
| 23 |
+
instantiate a BertGeneration model according to the specified arguments, defining the model architecture.
|
| 24 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the BertGeneration
|
| 25 |
+
[google/bert_for_seq_generation_L-24_bbc_encoder](https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder)
|
| 26 |
+
architecture.
|
| 27 |
+
|
| 28 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 29 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
vocab_size (`int`, *optional*, defaults to 50358):
|
| 33 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 34 |
+
`inputs_ids` passed when calling [`BertGeneration`].
|
| 35 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
| 36 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 37 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
| 38 |
+
Number of hidden layers in the Transformer encoder.
|
| 39 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 40 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
| 42 |
+
Dimensionality of the "intermediate" (often called feed-forward) layer in the Transformer encoder.
|
| 43 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 44 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 45 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 46 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 47 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 48 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 49 |
+
The dropout ratio for the attention probabilities.
|
| 50 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 51 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 52 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 53 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 54 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 55 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 56 |
+
The epsilon used by the layer normalization layers.
|
| 57 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 58 |
+
Padding token id.
|
| 59 |
+
bos_token_id (`int`, *optional*, defaults to 2):
|
| 60 |
+
Beginning of stream token id.
|
| 61 |
+
eos_token_id (`int`, *optional*, defaults to 1):
|
| 62 |
+
End of stream token id.
|
| 63 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 64 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 65 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 66 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 67 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 68 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 69 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 71 |
+
relevant if `config.is_decoder=True`.
|
| 72 |
+
|
| 73 |
+
Examples:
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
>>> from transformers import BertGenerationConfig, BertGenerationEncoder
|
| 77 |
+
|
| 78 |
+
>>> # Initializing a BertGeneration config
|
| 79 |
+
>>> configuration = BertGenerationConfig()
|
| 80 |
+
|
| 81 |
+
>>> # Initializing a model (with random weights) from the config
|
| 82 |
+
>>> model = BertGenerationEncoder(configuration)
|
| 83 |
+
|
| 84 |
+
>>> # Accessing the model configuration
|
| 85 |
+
>>> configuration = model.config
|
| 86 |
+
```"""
|
| 87 |
+
|
| 88 |
+
model_type = "bert-generation"
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
vocab_size=50358,
|
| 93 |
+
hidden_size=1024,
|
| 94 |
+
num_hidden_layers=24,
|
| 95 |
+
num_attention_heads=16,
|
| 96 |
+
intermediate_size=4096,
|
| 97 |
+
hidden_act="gelu",
|
| 98 |
+
hidden_dropout_prob=0.1,
|
| 99 |
+
attention_probs_dropout_prob=0.1,
|
| 100 |
+
max_position_embeddings=512,
|
| 101 |
+
initializer_range=0.02,
|
| 102 |
+
layer_norm_eps=1e-12,
|
| 103 |
+
pad_token_id=0,
|
| 104 |
+
bos_token_id=2,
|
| 105 |
+
eos_token_id=1,
|
| 106 |
+
position_embedding_type="absolute",
|
| 107 |
+
use_cache=True,
|
| 108 |
+
**kwargs,
|
| 109 |
+
):
|
| 110 |
+
super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
| 111 |
+
|
| 112 |
+
self.vocab_size = vocab_size
|
| 113 |
+
self.hidden_size = hidden_size
|
| 114 |
+
self.num_hidden_layers = num_hidden_layers
|
| 115 |
+
self.num_attention_heads = num_attention_heads
|
| 116 |
+
self.hidden_act = hidden_act
|
| 117 |
+
self.intermediate_size = intermediate_size
|
| 118 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 119 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 120 |
+
self.max_position_embeddings = max_position_embeddings
|
| 121 |
+
self.initializer_range = initializer_range
|
| 122 |
+
self.layer_norm_eps = layer_norm_eps
|
| 123 |
+
self.position_embedding_type = position_embedding_type
|
| 124 |
+
self.use_cache = use_cache
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
__all__ = ["B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|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The Google AI Language 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 |
+
"""PyTorch BERT model specific for generation."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from typing import Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from ...activations import ACT2FN
|
| 25 |
+
from ...generation import GenerationMixin
|
| 26 |
+
from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
|
| 27 |
+
from ...modeling_utils import PreTrainedModel
|
| 28 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 29 |
+
from ...utils import (
|
| 30 |
+
add_code_sample_docstrings,
|
| 31 |
+
add_start_docstrings,
|
| 32 |
+
add_start_docstrings_to_model_forward,
|
| 33 |
+
logging,
|
| 34 |
+
replace_return_docstrings,
|
| 35 |
+
)
|
| 36 |
+
from .configuration_bert_generation import BertGenerationConfig
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__)
|
| 40 |
+
|
| 41 |
+
_CHECKPOINT_FOR_DOC = "google/bert_for_seq_generation_L-24_bbc_encoder"
|
| 42 |
+
_CONFIG_FOR_DOC = "BertGenerationConfig"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->BertGeneration
|
| 46 |
+
class BertGenerationSelfOutput(nn.Module):
|
| 47 |
+
def __init__(self, config):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 50 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 51 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 52 |
+
|
| 53 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 54 |
+
hidden_states = self.dense(hidden_states)
|
| 55 |
+
hidden_states = self.dropout(hidden_states)
|
| 56 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 57 |
+
return hidden_states
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->BertGeneration
|
| 61 |
+
class BertGenerationSelfAttention(nn.Module):
|
| 62 |
+
def __init__(self, config, position_embedding_type=None):
|
| 63 |
+
super().__init__()
|
| 64 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 65 |
+
raise ValueError(
|
| 66 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 67 |
+
f"heads ({config.num_attention_heads})"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
self.num_attention_heads = config.num_attention_heads
|
| 71 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 72 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 73 |
+
|
| 74 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 75 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 76 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 77 |
+
|
| 78 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 79 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 80 |
+
config, "position_embedding_type", "absolute"
|
| 81 |
+
)
|
| 82 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 83 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 84 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 85 |
+
|
| 86 |
+
self.is_decoder = config.is_decoder
|
| 87 |
+
|
| 88 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 89 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 90 |
+
x = x.view(new_x_shape)
|
| 91 |
+
return x.permute(0, 2, 1, 3)
|
| 92 |
+
|
| 93 |
+
def forward(
|
| 94 |
+
self,
|
| 95 |
+
hidden_states: torch.Tensor,
|
| 96 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 97 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 98 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 99 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 100 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 101 |
+
output_attentions: Optional[bool] = False,
|
| 102 |
+
) -> Tuple[torch.Tensor]:
|
| 103 |
+
mixed_query_layer = self.query(hidden_states)
|
| 104 |
+
|
| 105 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 106 |
+
# and values come from an encoder; the attention mask needs to be
|
| 107 |
+
# such that the encoder's padding tokens are not attended to.
|
| 108 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 109 |
+
|
| 110 |
+
if is_cross_attention and past_key_value is not None:
|
| 111 |
+
# reuse k,v, cross_attentions
|
| 112 |
+
key_layer = past_key_value[0]
|
| 113 |
+
value_layer = past_key_value[1]
|
| 114 |
+
attention_mask = encoder_attention_mask
|
| 115 |
+
elif is_cross_attention:
|
| 116 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 117 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 118 |
+
attention_mask = encoder_attention_mask
|
| 119 |
+
elif past_key_value is not None:
|
| 120 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 121 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 122 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 123 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 124 |
+
else:
|
| 125 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 126 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 127 |
+
|
| 128 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 129 |
+
|
| 130 |
+
use_cache = past_key_value is not None
|
| 131 |
+
if self.is_decoder:
|
| 132 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 133 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 134 |
+
# key/value_states (first "if" case)
|
| 135 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 136 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 137 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 138 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 139 |
+
past_key_value = (key_layer, value_layer)
|
| 140 |
+
|
| 141 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 142 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 143 |
+
|
| 144 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 145 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 146 |
+
if use_cache:
|
| 147 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 148 |
+
-1, 1
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 152 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 153 |
+
distance = position_ids_l - position_ids_r
|
| 154 |
+
|
| 155 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 156 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 157 |
+
|
| 158 |
+
if self.position_embedding_type == "relative_key":
|
| 159 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 160 |
+
attention_scores = attention_scores + relative_position_scores
|
| 161 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 162 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 163 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 164 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 165 |
+
|
| 166 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 167 |
+
if attention_mask is not None:
|
| 168 |
+
# Apply the attention mask is (precomputed for all layers in BertGenerationModel forward() function)
|
| 169 |
+
attention_scores = attention_scores + attention_mask
|
| 170 |
+
|
| 171 |
+
# Normalize the attention scores to probabilities.
|
| 172 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 173 |
+
|
| 174 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 175 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 176 |
+
attention_probs = self.dropout(attention_probs)
|
| 177 |
+
|
| 178 |
+
# Mask heads if we want to
|
| 179 |
+
if head_mask is not None:
|
| 180 |
+
attention_probs = attention_probs * head_mask
|
| 181 |
+
|
| 182 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 183 |
+
|
| 184 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 185 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 186 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 187 |
+
|
| 188 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 189 |
+
|
| 190 |
+
if self.is_decoder:
|
| 191 |
+
outputs = outputs + (past_key_value,)
|
| 192 |
+
return outputs
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
BERT_GENERATION_SELF_ATTENTION_CLASSES = {
|
| 196 |
+
"eager": BertGenerationSelfAttention,
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->BertGeneration,BERT->BERT_GENERATION
|
| 201 |
+
class BertGenerationAttention(nn.Module):
|
| 202 |
+
def __init__(self, config, position_embedding_type=None):
|
| 203 |
+
super().__init__()
|
| 204 |
+
self.self = BERT_GENERATION_SELF_ATTENTION_CLASSES[config._attn_implementation](
|
| 205 |
+
config, position_embedding_type=position_embedding_type
|
| 206 |
+
)
|
| 207 |
+
self.output = BertGenerationSelfOutput(config)
|
| 208 |
+
self.pruned_heads = set()
|
| 209 |
+
|
| 210 |
+
def prune_heads(self, heads):
|
| 211 |
+
if len(heads) == 0:
|
| 212 |
+
return
|
| 213 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 214 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# Prune linear layers
|
| 218 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 219 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 220 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 221 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 222 |
+
|
| 223 |
+
# Update hyper params and store pruned heads
|
| 224 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 225 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 226 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 227 |
+
|
| 228 |
+
def forward(
|
| 229 |
+
self,
|
| 230 |
+
hidden_states: torch.Tensor,
|
| 231 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 232 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 233 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 234 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 235 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 236 |
+
output_attentions: Optional[bool] = False,
|
| 237 |
+
) -> Tuple[torch.Tensor]:
|
| 238 |
+
self_outputs = self.self(
|
| 239 |
+
hidden_states,
|
| 240 |
+
attention_mask,
|
| 241 |
+
head_mask,
|
| 242 |
+
encoder_hidden_states,
|
| 243 |
+
encoder_attention_mask,
|
| 244 |
+
past_key_value,
|
| 245 |
+
output_attentions,
|
| 246 |
+
)
|
| 247 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 248 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 249 |
+
return outputs
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->BertGeneration
|
| 253 |
+
class BertGenerationIntermediate(nn.Module):
|
| 254 |
+
def __init__(self, config):
|
| 255 |
+
super().__init__()
|
| 256 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 257 |
+
if isinstance(config.hidden_act, str):
|
| 258 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 259 |
+
else:
|
| 260 |
+
self.intermediate_act_fn = config.hidden_act
|
| 261 |
+
|
| 262 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 263 |
+
hidden_states = self.dense(hidden_states)
|
| 264 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 265 |
+
return hidden_states
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BertGeneration
|
| 269 |
+
class BertGenerationOutput(nn.Module):
|
| 270 |
+
def __init__(self, config):
|
| 271 |
+
super().__init__()
|
| 272 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 273 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 274 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 275 |
+
|
| 276 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 277 |
+
hidden_states = self.dense(hidden_states)
|
| 278 |
+
hidden_states = self.dropout(hidden_states)
|
| 279 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 280 |
+
return hidden_states
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->BertGeneration
|
| 284 |
+
class BertGenerationLayer(nn.Module):
|
| 285 |
+
def __init__(self, config):
|
| 286 |
+
super().__init__()
|
| 287 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 288 |
+
self.seq_len_dim = 1
|
| 289 |
+
self.attention = BertGenerationAttention(config)
|
| 290 |
+
self.is_decoder = config.is_decoder
|
| 291 |
+
self.add_cross_attention = config.add_cross_attention
|
| 292 |
+
if self.add_cross_attention:
|
| 293 |
+
if not self.is_decoder:
|
| 294 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 295 |
+
self.crossattention = BertGenerationAttention(config, position_embedding_type="absolute")
|
| 296 |
+
self.intermediate = BertGenerationIntermediate(config)
|
| 297 |
+
self.output = BertGenerationOutput(config)
|
| 298 |
+
|
| 299 |
+
def forward(
|
| 300 |
+
self,
|
| 301 |
+
hidden_states: torch.Tensor,
|
| 302 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 303 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 304 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 305 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 306 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 307 |
+
output_attentions: Optional[bool] = False,
|
| 308 |
+
) -> Tuple[torch.Tensor]:
|
| 309 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 310 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 311 |
+
self_attention_outputs = self.attention(
|
| 312 |
+
hidden_states,
|
| 313 |
+
attention_mask,
|
| 314 |
+
head_mask,
|
| 315 |
+
output_attentions=output_attentions,
|
| 316 |
+
past_key_value=self_attn_past_key_value,
|
| 317 |
+
)
|
| 318 |
+
attention_output = self_attention_outputs[0]
|
| 319 |
+
|
| 320 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 321 |
+
if self.is_decoder:
|
| 322 |
+
outputs = self_attention_outputs[1:-1]
|
| 323 |
+
present_key_value = self_attention_outputs[-1]
|
| 324 |
+
else:
|
| 325 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 326 |
+
|
| 327 |
+
cross_attn_present_key_value = None
|
| 328 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 329 |
+
if not hasattr(self, "crossattention"):
|
| 330 |
+
raise ValueError(
|
| 331 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 332 |
+
" by setting `config.add_cross_attention=True`"
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 336 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 337 |
+
cross_attention_outputs = self.crossattention(
|
| 338 |
+
attention_output,
|
| 339 |
+
attention_mask,
|
| 340 |
+
head_mask,
|
| 341 |
+
encoder_hidden_states,
|
| 342 |
+
encoder_attention_mask,
|
| 343 |
+
cross_attn_past_key_value,
|
| 344 |
+
output_attentions,
|
| 345 |
+
)
|
| 346 |
+
attention_output = cross_attention_outputs[0]
|
| 347 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 348 |
+
|
| 349 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 350 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 351 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 352 |
+
|
| 353 |
+
layer_output = apply_chunking_to_forward(
|
| 354 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 355 |
+
)
|
| 356 |
+
outputs = (layer_output,) + outputs
|
| 357 |
+
|
| 358 |
+
# if decoder, return the attn key/values as the last output
|
| 359 |
+
if self.is_decoder:
|
| 360 |
+
outputs = outputs + (present_key_value,)
|
| 361 |
+
|
| 362 |
+
return outputs
|
| 363 |
+
|
| 364 |
+
def feed_forward_chunk(self, attention_output):
|
| 365 |
+
intermediate_output = self.intermediate(attention_output)
|
| 366 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 367 |
+
return layer_output
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->BertGeneration
|
| 371 |
+
class BertEncoder(nn.Module):
|
| 372 |
+
def __init__(self, config):
|
| 373 |
+
super().__init__()
|
| 374 |
+
self.config = config
|
| 375 |
+
self.layer = nn.ModuleList([BertGenerationLayer(config) for _ in range(config.num_hidden_layers)])
|
| 376 |
+
self.gradient_checkpointing = False
|
| 377 |
+
|
| 378 |
+
def forward(
|
| 379 |
+
self,
|
| 380 |
+
hidden_states: torch.Tensor,
|
| 381 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 382 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 383 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 384 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 385 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 386 |
+
use_cache: Optional[bool] = None,
|
| 387 |
+
output_attentions: Optional[bool] = False,
|
| 388 |
+
output_hidden_states: Optional[bool] = False,
|
| 389 |
+
return_dict: Optional[bool] = True,
|
| 390 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 391 |
+
all_hidden_states = () if output_hidden_states else None
|
| 392 |
+
all_self_attentions = () if output_attentions else None
|
| 393 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 394 |
+
|
| 395 |
+
if self.gradient_checkpointing and self.training:
|
| 396 |
+
if use_cache:
|
| 397 |
+
logger.warning_once(
|
| 398 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 399 |
+
)
|
| 400 |
+
use_cache = False
|
| 401 |
+
|
| 402 |
+
next_decoder_cache = () if use_cache else None
|
| 403 |
+
for i, layer_module in enumerate(self.layer):
|
| 404 |
+
if output_hidden_states:
|
| 405 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 406 |
+
|
| 407 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 408 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 409 |
+
|
| 410 |
+
if self.gradient_checkpointing and self.training:
|
| 411 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 412 |
+
layer_module.__call__,
|
| 413 |
+
hidden_states,
|
| 414 |
+
attention_mask,
|
| 415 |
+
layer_head_mask,
|
| 416 |
+
encoder_hidden_states,
|
| 417 |
+
encoder_attention_mask,
|
| 418 |
+
past_key_value,
|
| 419 |
+
output_attentions,
|
| 420 |
+
)
|
| 421 |
+
else:
|
| 422 |
+
layer_outputs = layer_module(
|
| 423 |
+
hidden_states,
|
| 424 |
+
attention_mask,
|
| 425 |
+
layer_head_mask,
|
| 426 |
+
encoder_hidden_states,
|
| 427 |
+
encoder_attention_mask,
|
| 428 |
+
past_key_value,
|
| 429 |
+
output_attentions,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
hidden_states = layer_outputs[0]
|
| 433 |
+
if use_cache:
|
| 434 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 435 |
+
if output_attentions:
|
| 436 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 437 |
+
if self.config.add_cross_attention:
|
| 438 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 439 |
+
|
| 440 |
+
if output_hidden_states:
|
| 441 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 442 |
+
|
| 443 |
+
if not return_dict:
|
| 444 |
+
return tuple(
|
| 445 |
+
v
|
| 446 |
+
for v in [
|
| 447 |
+
hidden_states,
|
| 448 |
+
next_decoder_cache,
|
| 449 |
+
all_hidden_states,
|
| 450 |
+
all_self_attentions,
|
| 451 |
+
all_cross_attentions,
|
| 452 |
+
]
|
| 453 |
+
if v is not None
|
| 454 |
+
)
|
| 455 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 456 |
+
last_hidden_state=hidden_states,
|
| 457 |
+
past_key_values=next_decoder_cache,
|
| 458 |
+
hidden_states=all_hidden_states,
|
| 459 |
+
attentions=all_self_attentions,
|
| 460 |
+
cross_attentions=all_cross_attentions,
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def load_tf_weights_in_bert_generation(
|
| 465 |
+
model, tf_hub_path, model_class, is_encoder_named_decoder=False, is_encoder=False
|
| 466 |
+
):
|
| 467 |
+
try:
|
| 468 |
+
import numpy as np
|
| 469 |
+
import tensorflow.compat.v1 as tf
|
| 470 |
+
import tensorflow_hub as hub
|
| 471 |
+
import tensorflow_text # noqa: F401
|
| 472 |
+
|
| 473 |
+
tf.disable_eager_execution()
|
| 474 |
+
except ImportError:
|
| 475 |
+
logger.error(
|
| 476 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 477 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 478 |
+
)
|
| 479 |
+
raise
|
| 480 |
+
tf_model = hub.Module(tf_hub_path)
|
| 481 |
+
init = tf.global_variables_initializer()
|
| 482 |
+
with tf.Session() as sess:
|
| 483 |
+
init.run()
|
| 484 |
+
all_variables = tf_model.variable_map
|
| 485 |
+
keep_track_variables = all_variables.copy()
|
| 486 |
+
for key in list(all_variables.keys()):
|
| 487 |
+
if "global" in key:
|
| 488 |
+
logger.info(f"Skipping {key}...")
|
| 489 |
+
continue
|
| 490 |
+
if not is_encoder:
|
| 491 |
+
model_pointer = getattr(model, model_class)
|
| 492 |
+
else:
|
| 493 |
+
model_pointer = model
|
| 494 |
+
is_embedding = False
|
| 495 |
+
logger.info(f"Trying to match {key}...")
|
| 496 |
+
# remove start_string = "module/bert/"
|
| 497 |
+
sub_layers = key.split("/")[2:]
|
| 498 |
+
if is_encoder_named_decoder and sub_layers[0] == "encoder":
|
| 499 |
+
logger.info(f"Skipping encoder layer {key} for decoder")
|
| 500 |
+
continue
|
| 501 |
+
if is_encoder and sub_layers[0] == "decoder":
|
| 502 |
+
logger.info(f"Skipping decoder layer {key} for encoder")
|
| 503 |
+
continue
|
| 504 |
+
for i, sub_layer in enumerate(sub_layers):
|
| 505 |
+
if sub_layer == "embeddings":
|
| 506 |
+
is_embedding = True
|
| 507 |
+
elif sub_layer == "LayerNorm":
|
| 508 |
+
is_embedding = False
|
| 509 |
+
if "layer" in sub_layer:
|
| 510 |
+
model_pointer = model_pointer.layer[int(sub_layer.split("_")[-1])]
|
| 511 |
+
elif sub_layer in ["kernel", "gamma"]:
|
| 512 |
+
model_pointer = model_pointer.weight
|
| 513 |
+
elif sub_layer == "beta":
|
| 514 |
+
model_pointer = model_pointer.bias
|
| 515 |
+
elif sub_layer == "encdec":
|
| 516 |
+
model_pointer = model_pointer.crossattention.self
|
| 517 |
+
elif sub_layer == "encdec_output":
|
| 518 |
+
model_pointer = model_pointer.crossattention.output
|
| 519 |
+
elif is_encoder_named_decoder and sub_layer == "decoder":
|
| 520 |
+
model_pointer = model_pointer.encoder
|
| 521 |
+
else:
|
| 522 |
+
if sub_layer == "attention" and "encdec" in sub_layers[i + 1]:
|
| 523 |
+
continue
|
| 524 |
+
try:
|
| 525 |
+
model_pointer = getattr(model_pointer, sub_layer)
|
| 526 |
+
except AttributeError:
|
| 527 |
+
logger.info(f"Skipping to initialize {key} at {sub_layer}...")
|
| 528 |
+
raise AttributeError
|
| 529 |
+
|
| 530 |
+
array = np.asarray(sess.run(all_variables[key]))
|
| 531 |
+
if not is_embedding:
|
| 532 |
+
logger.info(f"Transposing numpy weight of shape {array.shape} for {key}")
|
| 533 |
+
array = np.transpose(array)
|
| 534 |
+
else:
|
| 535 |
+
model_pointer = model_pointer.weight
|
| 536 |
+
|
| 537 |
+
if model_pointer.shape != array.shape:
|
| 538 |
+
raise ValueError(f"Pointer shape {model_pointer.shape} and array shape {array.shape} mismatched")
|
| 539 |
+
logger.info(f"Initialize PyTorch weight {key}")
|
| 540 |
+
|
| 541 |
+
model_pointer.data = torch.from_numpy(array.astype(np.float32))
|
| 542 |
+
keep_track_variables.pop(key, None)
|
| 543 |
+
|
| 544 |
+
logger.info(f"Weights not copied to PyTorch model: {', '.join(keep_track_variables.keys())}")
|
| 545 |
+
return model
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
class BertGenerationEmbeddings(nn.Module):
|
| 549 |
+
"""Construct the embeddings from word and position embeddings."""
|
| 550 |
+
|
| 551 |
+
def __init__(self, config):
|
| 552 |
+
super().__init__()
|
| 553 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 554 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 555 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 556 |
+
# any TensorFlow checkpoint file
|
| 557 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 558 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 559 |
+
|
| 560 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 561 |
+
self.register_buffer(
|
| 562 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
|
| 566 |
+
if input_ids is not None:
|
| 567 |
+
input_shape = input_ids.size()
|
| 568 |
+
else:
|
| 569 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 570 |
+
|
| 571 |
+
seq_length = input_shape[1]
|
| 572 |
+
|
| 573 |
+
if position_ids is None:
|
| 574 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 575 |
+
|
| 576 |
+
if inputs_embeds is None:
|
| 577 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 578 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 579 |
+
|
| 580 |
+
embeddings = inputs_embeds + position_embeddings
|
| 581 |
+
embeddings = self.LayerNorm(embeddings)
|
| 582 |
+
embeddings = self.dropout(embeddings)
|
| 583 |
+
return embeddings
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
class BertGenerationPreTrainedModel(PreTrainedModel):
|
| 587 |
+
"""
|
| 588 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 589 |
+
models.
|
| 590 |
+
"""
|
| 591 |
+
|
| 592 |
+
config_class = BertGenerationConfig
|
| 593 |
+
base_model_prefix = "bert"
|
| 594 |
+
supports_gradient_checkpointing = True
|
| 595 |
+
|
| 596 |
+
def _init_weights(self, module):
|
| 597 |
+
"""Initialize the weights"""
|
| 598 |
+
if isinstance(module, nn.Linear):
|
| 599 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 600 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 601 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 602 |
+
if module.bias is not None:
|
| 603 |
+
module.bias.data.zero_()
|
| 604 |
+
elif isinstance(module, nn.Embedding):
|
| 605 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 606 |
+
if module.padding_idx is not None:
|
| 607 |
+
module.weight.data[module.padding_idx].zero_()
|
| 608 |
+
elif isinstance(module, nn.LayerNorm):
|
| 609 |
+
module.bias.data.zero_()
|
| 610 |
+
module.weight.data.fill_(1.0)
|
| 611 |
+
elif isinstance(module, BertGenerationOnlyLMHead):
|
| 612 |
+
module.bias.data.zero_()
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
BERT_GENERATION_START_DOCSTRING = r"""
|
| 616 |
+
|
| 617 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 618 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 619 |
+
etc.)
|
| 620 |
+
|
| 621 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 622 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 623 |
+
and behavior.
|
| 624 |
+
|
| 625 |
+
Parameters:
|
| 626 |
+
config ([`BertGenerationConfig`]): Model configuration class with all the parameters of the model.
|
| 627 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 628 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 629 |
+
"""
|
| 630 |
+
|
| 631 |
+
BERT_GENERATION_INPUTS_DOCSTRING = r"""
|
| 632 |
+
Args:
|
| 633 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 634 |
+
Indices of input sequence tokens in the vocabulary.
|
| 635 |
+
|
| 636 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 637 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 638 |
+
|
| 639 |
+
[What are input IDs?](../glossary#input-ids)
|
| 640 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
| 641 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 642 |
+
|
| 643 |
+
- 1 for tokens that are **not masked**,
|
| 644 |
+
- 0 for tokens that are **masked**.
|
| 645 |
+
|
| 646 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 647 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 648 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 649 |
+
config.max_position_embeddings - 1]`.
|
| 650 |
+
|
| 651 |
+
[What are position IDs?](../glossary#position-ids)
|
| 652 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 653 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 654 |
+
|
| 655 |
+
- 1 indicates the head is **not masked**,
|
| 656 |
+
- 0 indicates the head is **masked**.
|
| 657 |
+
|
| 658 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 659 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 660 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 661 |
+
model's internal embedding lookup matrix.
|
| 662 |
+
output_attentions (`bool`, *optional*):
|
| 663 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 664 |
+
tensors for more detail.
|
| 665 |
+
output_hidden_states (`bool`, *optional*):
|
| 666 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 667 |
+
more detail.
|
| 668 |
+
return_dict (`bool`, *optional*):
|
| 669 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 670 |
+
"""
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
@add_start_docstrings(
|
| 674 |
+
"The bare BertGeneration model transformer outputting raw hidden-states without any specific head on top.",
|
| 675 |
+
BERT_GENERATION_START_DOCSTRING,
|
| 676 |
+
)
|
| 677 |
+
class BertGenerationEncoder(BertGenerationPreTrainedModel):
|
| 678 |
+
"""
|
| 679 |
+
|
| 680 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 681 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 682 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 683 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
| 684 |
+
|
| 685 |
+
This model should be used when leveraging Bert or Roberta checkpoints for the [`EncoderDecoderModel`] class as
|
| 686 |
+
described in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461)
|
| 687 |
+
by Sascha Rothe, Shashi Narayan, and Aliaksei Severyn.
|
| 688 |
+
|
| 689 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 690 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 691 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 692 |
+
"""
|
| 693 |
+
|
| 694 |
+
def __init__(self, config):
|
| 695 |
+
super().__init__(config)
|
| 696 |
+
self.config = config
|
| 697 |
+
|
| 698 |
+
self.embeddings = BertGenerationEmbeddings(config)
|
| 699 |
+
self.encoder = BertEncoder(config)
|
| 700 |
+
|
| 701 |
+
# Initialize weights and apply final processing
|
| 702 |
+
self.post_init()
|
| 703 |
+
|
| 704 |
+
def get_input_embeddings(self):
|
| 705 |
+
return self.embeddings.word_embeddings
|
| 706 |
+
|
| 707 |
+
def set_input_embeddings(self, value):
|
| 708 |
+
self.embeddings.word_embeddings = value
|
| 709 |
+
|
| 710 |
+
def _prune_heads(self, heads_to_prune):
|
| 711 |
+
"""
|
| 712 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 713 |
+
class PreTrainedModel
|
| 714 |
+
"""
|
| 715 |
+
for layer, heads in heads_to_prune.items():
|
| 716 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 717 |
+
|
| 718 |
+
@add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 719 |
+
@add_code_sample_docstrings(
|
| 720 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 721 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
| 722 |
+
config_class=_CONFIG_FOR_DOC,
|
| 723 |
+
)
|
| 724 |
+
def forward(
|
| 725 |
+
self,
|
| 726 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 727 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 728 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 729 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 730 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 731 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 732 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 733 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 734 |
+
use_cache: Optional[bool] = None,
|
| 735 |
+
output_attentions: Optional[bool] = None,
|
| 736 |
+
output_hidden_states: Optional[bool] = None,
|
| 737 |
+
return_dict: Optional[bool] = None,
|
| 738 |
+
**kwargs, # NOOP kwargs, for now
|
| 739 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
| 740 |
+
r"""
|
| 741 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 742 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 743 |
+
the model is configured as a decoder.
|
| 744 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 745 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 746 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: `1` for
|
| 747 |
+
tokens that are NOT MASKED, `0` for MASKED tokens.
|
| 748 |
+
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)`):
|
| 749 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 750 |
+
|
| 751 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 752 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 753 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 754 |
+
use_cache (`bool`, *optional*):
|
| 755 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 756 |
+
`past_key_values`).
|
| 757 |
+
"""
|
| 758 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 759 |
+
output_hidden_states = (
|
| 760 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 761 |
+
)
|
| 762 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 763 |
+
|
| 764 |
+
if self.config.is_decoder:
|
| 765 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 766 |
+
else:
|
| 767 |
+
use_cache = False
|
| 768 |
+
|
| 769 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 770 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 771 |
+
elif input_ids is not None:
|
| 772 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 773 |
+
input_shape = input_ids.size()
|
| 774 |
+
elif inputs_embeds is not None:
|
| 775 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 776 |
+
else:
|
| 777 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 778 |
+
|
| 779 |
+
batch_size, seq_length = input_shape
|
| 780 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 781 |
+
|
| 782 |
+
# past_key_values_length
|
| 783 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 784 |
+
|
| 785 |
+
if attention_mask is None:
|
| 786 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
| 787 |
+
|
| 788 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 789 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 790 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 791 |
+
|
| 792 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 793 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 794 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 795 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 796 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 797 |
+
if encoder_attention_mask is None:
|
| 798 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 799 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 800 |
+
else:
|
| 801 |
+
encoder_extended_attention_mask = None
|
| 802 |
+
|
| 803 |
+
# Prepare head mask if needed
|
| 804 |
+
# 1.0 in head_mask indicate we keep the head
|
| 805 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 806 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 807 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 808 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 809 |
+
|
| 810 |
+
embedding_output = self.embeddings(
|
| 811 |
+
input_ids=input_ids,
|
| 812 |
+
position_ids=position_ids,
|
| 813 |
+
inputs_embeds=inputs_embeds,
|
| 814 |
+
past_key_values_length=past_key_values_length,
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
encoder_outputs = self.encoder(
|
| 818 |
+
embedding_output,
|
| 819 |
+
attention_mask=extended_attention_mask,
|
| 820 |
+
head_mask=head_mask,
|
| 821 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 822 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 823 |
+
past_key_values=past_key_values,
|
| 824 |
+
use_cache=use_cache,
|
| 825 |
+
output_attentions=output_attentions,
|
| 826 |
+
output_hidden_states=output_hidden_states,
|
| 827 |
+
return_dict=return_dict,
|
| 828 |
+
)
|
| 829 |
+
sequence_output = encoder_outputs[0]
|
| 830 |
+
|
| 831 |
+
if not return_dict:
|
| 832 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 833 |
+
|
| 834 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 835 |
+
last_hidden_state=sequence_output,
|
| 836 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 837 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 838 |
+
attentions=encoder_outputs.attentions,
|
| 839 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
class BertGenerationOnlyLMHead(nn.Module):
|
| 844 |
+
def __init__(self, config):
|
| 845 |
+
super().__init__()
|
| 846 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
|
| 847 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 848 |
+
self.decoder.bias = self.bias
|
| 849 |
+
|
| 850 |
+
def forward(self, hidden_states):
|
| 851 |
+
logits = self.decoder(hidden_states)
|
| 852 |
+
return logits
|
| 853 |
+
|
| 854 |
+
def _tie_weights(self):
|
| 855 |
+
# For accelerate compatibility and to not break backward compatibility
|
| 856 |
+
if self.decoder.bias.device.type == "meta":
|
| 857 |
+
self.decoder.bias = self.bias
|
| 858 |
+
else:
|
| 859 |
+
# To tie those two weights if they get disconnected (on TPU or when the bias is resized)
|
| 860 |
+
self.bias = self.decoder.bias
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
@add_start_docstrings(
|
| 864 |
+
"""BertGeneration Model with a `language modeling` head on top for CLM fine-tuning.""",
|
| 865 |
+
BERT_GENERATION_START_DOCSTRING,
|
| 866 |
+
)
|
| 867 |
+
class BertGenerationDecoder(BertGenerationPreTrainedModel, GenerationMixin):
|
| 868 |
+
_tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
|
| 869 |
+
|
| 870 |
+
def __init__(self, config):
|
| 871 |
+
super().__init__(config)
|
| 872 |
+
|
| 873 |
+
if not config.is_decoder:
|
| 874 |
+
logger.warning("If you want to use `BertGenerationDecoder` as a standalone, add `is_decoder=True.`")
|
| 875 |
+
|
| 876 |
+
self.bert = BertGenerationEncoder(config)
|
| 877 |
+
self.lm_head = BertGenerationOnlyLMHead(config)
|
| 878 |
+
|
| 879 |
+
# Initialize weights and apply final processing
|
| 880 |
+
self.post_init()
|
| 881 |
+
|
| 882 |
+
def get_output_embeddings(self):
|
| 883 |
+
return self.lm_head.decoder
|
| 884 |
+
|
| 885 |
+
def set_output_embeddings(self, new_embeddings):
|
| 886 |
+
self.lm_head.decoder = new_embeddings
|
| 887 |
+
self.lm_head.bias = new_embeddings.bias
|
| 888 |
+
|
| 889 |
+
@add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 890 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
| 891 |
+
def forward(
|
| 892 |
+
self,
|
| 893 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 894 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 895 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 896 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 897 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 898 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 899 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 900 |
+
labels: Optional[torch.Tensor] = None,
|
| 901 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 902 |
+
use_cache: Optional[bool] = None,
|
| 903 |
+
output_attentions: Optional[bool] = None,
|
| 904 |
+
output_hidden_states: Optional[bool] = None,
|
| 905 |
+
return_dict: Optional[bool] = None,
|
| 906 |
+
**kwargs,
|
| 907 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
| 908 |
+
r"""
|
| 909 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 910 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 911 |
+
the model is configured as a decoder.
|
| 912 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 913 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 914 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 915 |
+
|
| 916 |
+
- 1 for tokens that are **not masked**,
|
| 917 |
+
- 0 for tokens that are **masked**.
|
| 918 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 919 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 920 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 921 |
+
ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 922 |
+
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)`):
|
| 923 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 924 |
+
|
| 925 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 926 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 927 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 928 |
+
use_cache (`bool`, *optional*):
|
| 929 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 930 |
+
`past_key_values`).
|
| 931 |
+
|
| 932 |
+
Returns:
|
| 933 |
+
|
| 934 |
+
Example:
|
| 935 |
+
|
| 936 |
+
```python
|
| 937 |
+
>>> from transformers import AutoTokenizer, BertGenerationDecoder, BertGenerationConfig
|
| 938 |
+
>>> import torch
|
| 939 |
+
|
| 940 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
|
| 941 |
+
>>> config = BertGenerationConfig.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
|
| 942 |
+
>>> config.is_decoder = True
|
| 943 |
+
>>> model = BertGenerationDecoder.from_pretrained(
|
| 944 |
+
... "google/bert_for_seq_generation_L-24_bbc_encoder", config=config
|
| 945 |
+
... )
|
| 946 |
+
|
| 947 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_token_type_ids=False, return_tensors="pt")
|
| 948 |
+
>>> outputs = model(**inputs)
|
| 949 |
+
|
| 950 |
+
>>> prediction_logits = outputs.logits
|
| 951 |
+
```"""
|
| 952 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 953 |
+
if labels is not None:
|
| 954 |
+
use_cache = False
|
| 955 |
+
|
| 956 |
+
outputs = self.bert(
|
| 957 |
+
input_ids,
|
| 958 |
+
attention_mask=attention_mask,
|
| 959 |
+
position_ids=position_ids,
|
| 960 |
+
head_mask=head_mask,
|
| 961 |
+
inputs_embeds=inputs_embeds,
|
| 962 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 963 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 964 |
+
past_key_values=past_key_values,
|
| 965 |
+
use_cache=use_cache,
|
| 966 |
+
output_attentions=output_attentions,
|
| 967 |
+
output_hidden_states=output_hidden_states,
|
| 968 |
+
return_dict=return_dict,
|
| 969 |
+
**kwargs,
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
sequence_output = outputs[0]
|
| 973 |
+
prediction_scores = self.lm_head(sequence_output)
|
| 974 |
+
|
| 975 |
+
lm_loss = None
|
| 976 |
+
if labels is not None:
|
| 977 |
+
lm_loss = self.loss_function(
|
| 978 |
+
prediction_scores,
|
| 979 |
+
labels,
|
| 980 |
+
vocab_size=self.config.vocab_size,
|
| 981 |
+
**kwargs,
|
| 982 |
+
)
|
| 983 |
+
|
| 984 |
+
if not return_dict:
|
| 985 |
+
output = (prediction_scores,) + outputs[1:]
|
| 986 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
| 987 |
+
|
| 988 |
+
return CausalLMOutputWithCrossAttentions(
|
| 989 |
+
loss=lm_loss,
|
| 990 |
+
logits=prediction_scores,
|
| 991 |
+
past_key_values=outputs.past_key_values,
|
| 992 |
+
hidden_states=outputs.hidden_states,
|
| 993 |
+
attentions=outputs.attentions,
|
| 994 |
+
cross_attentions=outputs.cross_attentions,
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 998 |
+
reordered_past = ()
|
| 999 |
+
for layer_past in past_key_values:
|
| 1000 |
+
reordered_past += (
|
| 1001 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1002 |
+
)
|
| 1003 |
+
return reordered_past
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
__all__ = [
|
| 1007 |
+
"BertGenerationDecoder",
|
| 1008 |
+
"BertGenerationEncoder",
|
| 1009 |
+
"BertGenerationPreTrainedModel",
|
| 1010 |
+
"load_tf_weights_in_bert_generation",
|
| 1011 |
+
]
|
lib/python3.12/site-packages/transformers/models/bert_generation/tokenization_bert_generation.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Tokenization class for model BertGeneration."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from shutil import copyfile
|
| 19 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import sentencepiece as spm
|
| 22 |
+
|
| 23 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 24 |
+
from ...utils import logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class BertGenerationTokenizer(PreTrainedTokenizer):
|
| 33 |
+
"""
|
| 34 |
+
Construct a BertGeneration tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
|
| 35 |
+
|
| 36 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 37 |
+
this superclass for more information regarding those methods.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
vocab_file (`str`):
|
| 41 |
+
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
|
| 42 |
+
contains the vocabulary necessary to instantiate a tokenizer.
|
| 43 |
+
bos_token (`str`, *optional*, defaults to `"<s>"`):
|
| 44 |
+
The begin of sequence token.
|
| 45 |
+
eos_token (`str`, *optional*, defaults to `"</s>"`):
|
| 46 |
+
The end of sequence token.
|
| 47 |
+
unk_token (`str`, *optional*, defaults to `"<unk>"`):
|
| 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 |
+
pad_token (`str`, *optional*, defaults to `"<pad>"`):
|
| 51 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 52 |
+
sep_token (`str`, *optional*, defaults to `"<::::>"`):
|
| 53 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 54 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 55 |
+
token of a sequence built with special tokens.
|
| 56 |
+
sp_model_kwargs (`dict`, *optional*):
|
| 57 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
| 58 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
| 59 |
+
to set:
|
| 60 |
+
|
| 61 |
+
- `enable_sampling`: Enable subword regularization.
|
| 62 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
| 63 |
+
|
| 64 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
| 65 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
| 66 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
| 67 |
+
using forward-filtering-and-backward-sampling algorithm.
|
| 68 |
+
|
| 69 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
| 70 |
+
BPE-dropout.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 74 |
+
prefix_tokens: List[int] = []
|
| 75 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
vocab_file,
|
| 80 |
+
bos_token="<s>",
|
| 81 |
+
eos_token="</s>",
|
| 82 |
+
unk_token="<unk>",
|
| 83 |
+
pad_token="<pad>",
|
| 84 |
+
sep_token="<::::>",
|
| 85 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
| 86 |
+
**kwargs,
|
| 87 |
+
) -> None:
|
| 88 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
| 89 |
+
|
| 90 |
+
self.vocab_file = vocab_file
|
| 91 |
+
|
| 92 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 93 |
+
self.sp_model.Load(vocab_file)
|
| 94 |
+
|
| 95 |
+
# Add extra_ids to the special token list
|
| 96 |
+
super().__init__(
|
| 97 |
+
bos_token=bos_token,
|
| 98 |
+
eos_token=eos_token,
|
| 99 |
+
unk_token=unk_token,
|
| 100 |
+
pad_token=pad_token,
|
| 101 |
+
sep_token=sep_token,
|
| 102 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
| 103 |
+
**kwargs,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def vocab_size(self):
|
| 108 |
+
return self.sp_model.get_piece_size()
|
| 109 |
+
|
| 110 |
+
def get_vocab(self):
|
| 111 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
| 112 |
+
vocab.update(self.added_tokens_encoder)
|
| 113 |
+
return vocab
|
| 114 |
+
|
| 115 |
+
def __getstate__(self):
|
| 116 |
+
state = self.__dict__.copy()
|
| 117 |
+
state["sp_model"] = None
|
| 118 |
+
return state
|
| 119 |
+
|
| 120 |
+
def __setstate__(self, d):
|
| 121 |
+
self.__dict__ = d
|
| 122 |
+
|
| 123 |
+
# for backward compatibility
|
| 124 |
+
if not hasattr(self, "sp_model_kwargs"):
|
| 125 |
+
self.sp_model_kwargs = {}
|
| 126 |
+
|
| 127 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
| 128 |
+
self.sp_model.Load(self.vocab_file)
|
| 129 |
+
|
| 130 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 131 |
+
"""Take as input a string and return a list of strings (tokens) for words/sub-words"""
|
| 132 |
+
return self.sp_model.encode(text, out_type=str)
|
| 133 |
+
|
| 134 |
+
def _convert_token_to_id(self, token):
|
| 135 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 136 |
+
return self.sp_model.piece_to_id(token)
|
| 137 |
+
|
| 138 |
+
def _convert_id_to_token(self, index):
|
| 139 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 140 |
+
token = self.sp_model.IdToPiece(index)
|
| 141 |
+
return token
|
| 142 |
+
|
| 143 |
+
def convert_tokens_to_string(self, tokens):
|
| 144 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 145 |
+
current_sub_tokens = []
|
| 146 |
+
out_string = ""
|
| 147 |
+
for token in tokens:
|
| 148 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
| 149 |
+
if token in self.all_special_tokens:
|
| 150 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
| 151 |
+
current_sub_tokens = []
|
| 152 |
+
else:
|
| 153 |
+
current_sub_tokens.append(token)
|
| 154 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
| 155 |
+
return out_string.strip()
|
| 156 |
+
|
| 157 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 158 |
+
if not os.path.isdir(save_directory):
|
| 159 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 160 |
+
return
|
| 161 |
+
out_vocab_file = os.path.join(
|
| 162 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
| 166 |
+
copyfile(self.vocab_file, out_vocab_file)
|
| 167 |
+
elif not os.path.isfile(self.vocab_file):
|
| 168 |
+
with open(out_vocab_file, "wb") as fi:
|
| 169 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
| 170 |
+
fi.write(content_spiece_model)
|
| 171 |
+
|
| 172 |
+
return (out_vocab_file,)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
__all__ = ["BertGenerationTokenizer"]
|
lib/python3.12/site-packages/transformers/models/blip_2/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_blip_2 import *
|
| 22 |
+
from .modeling_blip_2 import *
|
| 23 |
+
from .processing_blip_2 import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (699 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-312.pyc
ADDED
|
Binary file (15.6 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-312.pyc
ADDED
|
Binary file (8.53 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/blip_2/configuration_blip_2.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""BLIP-2 model configuration"""
|
| 16 |
+
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
from ...configuration_utils import PretrainedConfig
|
| 20 |
+
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
|
| 21 |
+
from ...utils import logging
|
| 22 |
+
from ..auto import CONFIG_MAPPING, AutoConfig
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Blip2VisionConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`Blip2VisionModel`]. It is used to instantiate a
|
| 31 |
+
BLIP-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
|
| 32 |
+
configuration defaults will yield a similar configuration to that of the BLIP-2
|
| 33 |
+
[Salesforce/blip2-opt-2.7b](https://huggingface.co/Salesforce/blip2-opt-2.7b) architecture.
|
| 34 |
+
|
| 35 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 36 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 1408):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
intermediate_size (`int`, *optional*, defaults to 6144):
|
| 42 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 43 |
+
num_hidden_layers (`int`, *optional*, defaults to 39):
|
| 44 |
+
Number of hidden layers in the Transformer encoder.
|
| 45 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
| 46 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 47 |
+
image_size (`int`, *optional*, defaults to 224):
|
| 48 |
+
The size (resolution) of each image.
|
| 49 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 50 |
+
The size (resolution) of each patch.
|
| 51 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 52 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 53 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported. layer_norm_eps (`float`, *optional*, defaults
|
| 54 |
+
to 1e-5): The epsilon used by the layer normalization layers.
|
| 55 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 56 |
+
The dropout ratio for the attention probabilities.
|
| 57 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 58 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 59 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether to add a bias to the queries and values in the self-attention layers.
|
| 61 |
+
|
| 62 |
+
Example:
|
| 63 |
+
|
| 64 |
+
```python
|
| 65 |
+
>>> from transformers import Blip2VisionConfig, Blip2VisionModel
|
| 66 |
+
|
| 67 |
+
>>> # Initializing a Blip2VisionConfig with Salesforce/blip2-opt-2.7b style configuration
|
| 68 |
+
>>> configuration = Blip2VisionConfig()
|
| 69 |
+
|
| 70 |
+
>>> # Initializing a Blip2VisionModel (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
|
| 71 |
+
>>> model = Blip2VisionModel(configuration)
|
| 72 |
+
|
| 73 |
+
>>> # Accessing the model configuration
|
| 74 |
+
>>> configuration = model.config
|
| 75 |
+
```"""
|
| 76 |
+
|
| 77 |
+
model_type = "blip_2_vision_model"
|
| 78 |
+
base_config_key = "vision_config"
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
hidden_size=1408,
|
| 83 |
+
intermediate_size=6144,
|
| 84 |
+
num_hidden_layers=39,
|
| 85 |
+
num_attention_heads=16,
|
| 86 |
+
image_size=224,
|
| 87 |
+
patch_size=14,
|
| 88 |
+
hidden_act="gelu",
|
| 89 |
+
layer_norm_eps=1e-6,
|
| 90 |
+
attention_dropout=0.0,
|
| 91 |
+
initializer_range=1e-10,
|
| 92 |
+
qkv_bias=True,
|
| 93 |
+
**kwargs,
|
| 94 |
+
):
|
| 95 |
+
super().__init__(**kwargs)
|
| 96 |
+
|
| 97 |
+
self.hidden_size = hidden_size
|
| 98 |
+
self.intermediate_size = intermediate_size
|
| 99 |
+
self.num_hidden_layers = num_hidden_layers
|
| 100 |
+
self.num_attention_heads = num_attention_heads
|
| 101 |
+
self.patch_size = patch_size
|
| 102 |
+
self.image_size = image_size
|
| 103 |
+
self.initializer_range = initializer_range
|
| 104 |
+
self.attention_dropout = attention_dropout
|
| 105 |
+
self.layer_norm_eps = layer_norm_eps
|
| 106 |
+
self.hidden_act = hidden_act
|
| 107 |
+
self.qkv_bias = qkv_bias
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class Blip2QFormerConfig(PretrainedConfig):
|
| 111 |
+
r"""
|
| 112 |
+
This is the configuration class to store the configuration of a [`Blip2QFormerModel`]. It is used to instantiate a
|
| 113 |
+
BLIP-2 Querying Transformer (Q-Former) model according to the specified arguments, defining the model architecture.
|
| 114 |
+
Instantiating a configuration with the defaults will yield a similar configuration to that of the BLIP-2
|
| 115 |
+
[Salesforce/blip2-opt-2.7b](https://huggingface.co/Salesforce/blip2-opt-2.7b) architecture. Configuration objects
|
| 116 |
+
inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from
|
| 117 |
+
[`PretrainedConfig`] for more information.
|
| 118 |
+
|
| 119 |
+
Note that [`Blip2QFormerModel`] is very similar to [`BertLMHeadModel`] with interleaved cross-attention.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 123 |
+
Vocabulary size of the Q-Former model. Defines the number of different tokens that can be represented by
|
| 124 |
+
the `inputs_ids` passed when calling the model.
|
| 125 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 126 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 127 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 128 |
+
Number of hidden layers in the Transformer encoder.
|
| 129 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 130 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 131 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 132 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 133 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 134 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 135 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 136 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 137 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 138 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 139 |
+
The dropout ratio for the attention probabilities.
|
| 140 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 141 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 142 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 143 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 144 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 145 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 146 |
+
The epsilon used by the layer normalization layers.
|
| 147 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 148 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 149 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 150 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 151 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 152 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 153 |
+
cross_attention_frequency (`int`, *optional*, defaults to 2):
|
| 154 |
+
The frequency of adding cross-attention to the Transformer layers.
|
| 155 |
+
encoder_hidden_size (`int`, *optional*, defaults to 1408):
|
| 156 |
+
The hidden size of the hidden states for cross-attention.
|
| 157 |
+
use_qformer_text_input (`bool`, *optional*, defaults to `False`):
|
| 158 |
+
Whether to use BERT-style embeddings.
|
| 159 |
+
|
| 160 |
+
Examples:
|
| 161 |
+
|
| 162 |
+
```python
|
| 163 |
+
>>> from transformers import Blip2QFormerConfig, Blip2QFormerModel
|
| 164 |
+
|
| 165 |
+
>>> # Initializing a BLIP-2 Salesforce/blip2-opt-2.7b style configuration
|
| 166 |
+
>>> configuration = Blip2QFormerConfig()
|
| 167 |
+
|
| 168 |
+
>>> # Initializing a model (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
|
| 169 |
+
>>> model = Blip2QFormerModel(configuration)
|
| 170 |
+
>>> # Accessing the model configuration
|
| 171 |
+
>>> configuration = model.config
|
| 172 |
+
```"""
|
| 173 |
+
|
| 174 |
+
model_type = "blip_2_qformer"
|
| 175 |
+
base_config_key = "qformer_config"
|
| 176 |
+
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
vocab_size=30522,
|
| 180 |
+
hidden_size=768,
|
| 181 |
+
num_hidden_layers=12,
|
| 182 |
+
num_attention_heads=12,
|
| 183 |
+
intermediate_size=3072,
|
| 184 |
+
hidden_act="gelu",
|
| 185 |
+
hidden_dropout_prob=0.1,
|
| 186 |
+
attention_probs_dropout_prob=0.1,
|
| 187 |
+
max_position_embeddings=512,
|
| 188 |
+
initializer_range=0.02,
|
| 189 |
+
layer_norm_eps=1e-12,
|
| 190 |
+
pad_token_id=0,
|
| 191 |
+
position_embedding_type="absolute",
|
| 192 |
+
cross_attention_frequency=2,
|
| 193 |
+
encoder_hidden_size=1408,
|
| 194 |
+
use_qformer_text_input=False,
|
| 195 |
+
**kwargs,
|
| 196 |
+
):
|
| 197 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 198 |
+
|
| 199 |
+
self.vocab_size = vocab_size
|
| 200 |
+
self.hidden_size = hidden_size
|
| 201 |
+
self.num_hidden_layers = num_hidden_layers
|
| 202 |
+
self.num_attention_heads = num_attention_heads
|
| 203 |
+
self.hidden_act = hidden_act
|
| 204 |
+
self.intermediate_size = intermediate_size
|
| 205 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 206 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 207 |
+
self.max_position_embeddings = max_position_embeddings
|
| 208 |
+
self.initializer_range = initializer_range
|
| 209 |
+
self.layer_norm_eps = layer_norm_eps
|
| 210 |
+
self.position_embedding_type = position_embedding_type
|
| 211 |
+
self.cross_attention_frequency = cross_attention_frequency
|
| 212 |
+
self.encoder_hidden_size = encoder_hidden_size
|
| 213 |
+
self.use_qformer_text_input = use_qformer_text_input
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class Blip2Config(PretrainedConfig):
|
| 217 |
+
r"""
|
| 218 |
+
[`Blip2Config`] is the configuration class to store the configuration of a [`Blip2ForConditionalGeneration`]. It is
|
| 219 |
+
used to instantiate a BLIP-2 model according to the specified arguments, defining the vision model, Q-Former model
|
| 220 |
+
and language model configs. Instantiating a configuration with the defaults will yield a similar configuration to
|
| 221 |
+
that of the BLIP-2 [Salesforce/blip2-opt-2.7b](https://huggingface.co/Salesforce/blip2-opt-2.7b) architecture.
|
| 222 |
+
|
| 223 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 224 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 225 |
+
|
| 226 |
+
Args:
|
| 227 |
+
vision_config (`dict`, *optional*):
|
| 228 |
+
Dictionary of configuration options used to initialize [`Blip2VisionConfig`].
|
| 229 |
+
qformer_config (`dict`, *optional*):
|
| 230 |
+
Dictionary of configuration options used to initialize [`Blip2QFormerConfig`].
|
| 231 |
+
text_config (`dict`, *optional*):
|
| 232 |
+
Dictionary of configuration options used to initialize any [`PretrainedConfig`].
|
| 233 |
+
num_query_tokens (`int`, *optional*, defaults to 32):
|
| 234 |
+
The number of query tokens passed through the Transformer.
|
| 235 |
+
image_text_hidden_size (`int`, *optional*, defaults to 256):
|
| 236 |
+
Dimentionality of the hidden state of the image-text fusion layer.
|
| 237 |
+
|
| 238 |
+
image_token_index (`int`, *optional*):
|
| 239 |
+
Token index of special image token.
|
| 240 |
+
kwargs (*optional*):
|
| 241 |
+
Dictionary of keyword arguments.
|
| 242 |
+
|
| 243 |
+
Example:
|
| 244 |
+
|
| 245 |
+
```python
|
| 246 |
+
>>> from transformers import (
|
| 247 |
+
... Blip2VisionConfig,
|
| 248 |
+
... Blip2QFormerConfig,
|
| 249 |
+
... OPTConfig,
|
| 250 |
+
... Blip2Config,
|
| 251 |
+
... Blip2ForConditionalGeneration,
|
| 252 |
+
... )
|
| 253 |
+
|
| 254 |
+
>>> # Initializing a Blip2Config with Salesforce/blip2-opt-2.7b style configuration
|
| 255 |
+
>>> configuration = Blip2Config()
|
| 256 |
+
|
| 257 |
+
>>> # Initializing a Blip2ForConditionalGeneration (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
|
| 258 |
+
>>> model = Blip2ForConditionalGeneration(configuration)
|
| 259 |
+
|
| 260 |
+
>>> # Accessing the model configuration
|
| 261 |
+
>>> configuration = model.config
|
| 262 |
+
|
| 263 |
+
>>> # We can also initialize a Blip2Config from a Blip2VisionConfig, Blip2QFormerConfig and any PretrainedConfig
|
| 264 |
+
|
| 265 |
+
>>> # Initializing BLIP-2 vision, BLIP-2 Q-Former and language model configurations
|
| 266 |
+
>>> vision_config = Blip2VisionConfig()
|
| 267 |
+
>>> qformer_config = Blip2QFormerConfig()
|
| 268 |
+
>>> text_config = OPTConfig()
|
| 269 |
+
|
| 270 |
+
>>> config = Blip2Config.from_text_vision_configs(vision_config, qformer_config, text_config)
|
| 271 |
+
```"""
|
| 272 |
+
|
| 273 |
+
model_type = "blip-2"
|
| 274 |
+
sub_configs = {"text_config": AutoConfig, "qformer_config": Blip2QFormerConfig, "vision_config": Blip2VisionConfig}
|
| 275 |
+
|
| 276 |
+
def __init__(
|
| 277 |
+
self,
|
| 278 |
+
vision_config=None,
|
| 279 |
+
qformer_config=None,
|
| 280 |
+
text_config=None,
|
| 281 |
+
num_query_tokens=32,
|
| 282 |
+
image_text_hidden_size=256,
|
| 283 |
+
image_token_index=None,
|
| 284 |
+
**kwargs,
|
| 285 |
+
):
|
| 286 |
+
super().__init__(**kwargs)
|
| 287 |
+
|
| 288 |
+
if vision_config is None:
|
| 289 |
+
vision_config = {}
|
| 290 |
+
logger.info("vision_config is None. initializing the Blip2VisionConfig with default values.")
|
| 291 |
+
|
| 292 |
+
if qformer_config is None:
|
| 293 |
+
qformer_config = {}
|
| 294 |
+
logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values.")
|
| 295 |
+
|
| 296 |
+
if text_config is None:
|
| 297 |
+
text_config = {}
|
| 298 |
+
logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")
|
| 299 |
+
|
| 300 |
+
self.vision_config = Blip2VisionConfig(**vision_config)
|
| 301 |
+
self.qformer_config = Blip2QFormerConfig(**qformer_config)
|
| 302 |
+
text_model_type = text_config["model_type"] if "model_type" in text_config else "opt"
|
| 303 |
+
self.text_config = CONFIG_MAPPING[text_model_type](**text_config)
|
| 304 |
+
|
| 305 |
+
self.num_query_tokens = num_query_tokens
|
| 306 |
+
self.image_text_hidden_size = image_text_hidden_size
|
| 307 |
+
self.image_token_index = image_token_index
|
| 308 |
+
self.qformer_config.encoder_hidden_size = self.vision_config.hidden_size
|
| 309 |
+
self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
|
| 310 |
+
self.initializer_factor = 1.0
|
| 311 |
+
self.initializer_range = 0.02
|
| 312 |
+
|
| 313 |
+
@classmethod
|
| 314 |
+
def from_vision_qformer_text_configs(
|
| 315 |
+
cls,
|
| 316 |
+
vision_config: Blip2VisionConfig,
|
| 317 |
+
qformer_config: Blip2QFormerConfig,
|
| 318 |
+
text_config: Optional[PretrainedConfig] = None,
|
| 319 |
+
**kwargs,
|
| 320 |
+
):
|
| 321 |
+
r"""
|
| 322 |
+
Instantiate a [`Blip2Config`] (or a derived class) from a BLIP-2 vision model, Q-Former and language model
|
| 323 |
+
configurations.
|
| 324 |
+
|
| 325 |
+
Args:
|
| 326 |
+
vision_config (`dict`):
|
| 327 |
+
Dictionary of configuration options used to initialize [`Blip2VisionConfig`].
|
| 328 |
+
qformer_config (`dict`):
|
| 329 |
+
Dictionary of configuration options used to initialize [`Blip2QFormerConfig`].
|
| 330 |
+
text_config (`dict`, *optional*):
|
| 331 |
+
Dictionary of configuration options used to initialize any [`PretrainedConfig`].
|
| 332 |
+
|
| 333 |
+
Returns:
|
| 334 |
+
[`Blip2Config`]: An instance of a configuration object
|
| 335 |
+
"""
|
| 336 |
+
|
| 337 |
+
return cls(
|
| 338 |
+
vision_config=vision_config.to_dict(),
|
| 339 |
+
qformer_config=qformer_config.to_dict(),
|
| 340 |
+
text_config=text_config.to_dict() if text_config is not None else None,
|
| 341 |
+
**kwargs,
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
__all__ = ["Blip2Config", "Blip2QFormerConfig", "Blip2VisionConfig"]
|
lib/python3.12/site-packages/transformers/models/blip_2/modeling_blip_2.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lib/python3.12/site-packages/transformers/models/blip_2/processing_blip_2.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Processor class for BLIP-2.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import List, Optional, Union
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import BatchFeature
|
| 22 |
+
from ...image_utils import ImageInput
|
| 23 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 24 |
+
from ...tokenization_utils_base import (
|
| 25 |
+
AddedToken,
|
| 26 |
+
BatchEncoding,
|
| 27 |
+
PreTokenizedInput,
|
| 28 |
+
TextInput,
|
| 29 |
+
)
|
| 30 |
+
from ...utils import logging
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Blip2ProcessorKwargs(ProcessingKwargs, total=False):
|
| 37 |
+
_defaults = {
|
| 38 |
+
"text_kwargs": {
|
| 39 |
+
"add_special_tokens": True,
|
| 40 |
+
"padding": False,
|
| 41 |
+
"stride": 0,
|
| 42 |
+
"return_overflowing_tokens": False,
|
| 43 |
+
"return_special_tokens_mask": False,
|
| 44 |
+
"return_offsets_mapping": False,
|
| 45 |
+
"return_token_type_ids": False,
|
| 46 |
+
"return_length": False,
|
| 47 |
+
"verbose": True,
|
| 48 |
+
},
|
| 49 |
+
"images_kwargs": {},
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class Blip2Processor(ProcessorMixin):
|
| 54 |
+
r"""
|
| 55 |
+
Constructs a BLIP-2 processor which wraps a BLIP image processor and an OPT/T5 tokenizer into a single processor.
|
| 56 |
+
|
| 57 |
+
[`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`AutoTokenizer`]. See the docstring
|
| 58 |
+
of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
image_processor (`BlipImageProcessor`):
|
| 62 |
+
An instance of [`BlipImageProcessor`]. The image processor is a required input.
|
| 63 |
+
tokenizer (`AutoTokenizer`):
|
| 64 |
+
An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input.
|
| 65 |
+
num_query_tokens (`int`, *optional*):
|
| 66 |
+
Number of tokens used by the Qformer as queries, should be same as in model's config.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
attributes = ["image_processor", "tokenizer"]
|
| 70 |
+
valid_kwargs = ["num_query_tokens"]
|
| 71 |
+
image_processor_class = ("BlipImageProcessor", "BlipImageProcessorFast")
|
| 72 |
+
tokenizer_class = "AutoTokenizer"
|
| 73 |
+
|
| 74 |
+
def __init__(self, image_processor, tokenizer, num_query_tokens=None, **kwargs):
|
| 75 |
+
tokenizer.return_token_type_ids = False
|
| 76 |
+
self.current_processor = image_processor
|
| 77 |
+
if not hasattr(tokenizer, "image_token"):
|
| 78 |
+
self.image_token = AddedToken("<image>", normalized=False, special=True)
|
| 79 |
+
tokenizer.add_tokens([self.image_token], special_tokens=True)
|
| 80 |
+
else:
|
| 81 |
+
self.image_token = tokenizer.image_token
|
| 82 |
+
self.num_query_tokens = num_query_tokens
|
| 83 |
+
|
| 84 |
+
super().__init__(image_processor, tokenizer)
|
| 85 |
+
|
| 86 |
+
def __call__(
|
| 87 |
+
self,
|
| 88 |
+
images: ImageInput = None,
|
| 89 |
+
text: Optional[Union[str, List[str], TextInput, PreTokenizedInput]] = None,
|
| 90 |
+
audio=None,
|
| 91 |
+
videos=None,
|
| 92 |
+
**kwargs: Unpack[Blip2ProcessorKwargs],
|
| 93 |
+
) -> BatchEncoding:
|
| 94 |
+
"""
|
| 95 |
+
This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
|
| 96 |
+
[`BertTokenizerFast.__call__`] to prepare text for the model.
|
| 97 |
+
|
| 98 |
+
Please refer to the docstring of the above two methods for more information.
|
| 99 |
+
Args:
|
| 100 |
+
images (`ImageInput`):
|
| 101 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 102 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 103 |
+
text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
|
| 104 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 105 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 106 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 107 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 108 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 109 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 110 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 111 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 112 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 113 |
+
"""
|
| 114 |
+
if images is None and text is None:
|
| 115 |
+
raise ValueError("You have to specify either images or text.")
|
| 116 |
+
output_kwargs = self._merge_kwargs(
|
| 117 |
+
Blip2ProcessorKwargs,
|
| 118 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 119 |
+
**kwargs,
|
| 120 |
+
)
|
| 121 |
+
# BC for explicit return_tensors
|
| 122 |
+
if "return_tensors" in output_kwargs["common_kwargs"]:
|
| 123 |
+
return_tensors = output_kwargs["common_kwargs"].pop("return_tensors", None)
|
| 124 |
+
else:
|
| 125 |
+
return_tensors = None
|
| 126 |
+
encoding = BatchFeature(tensor_type=return_tensors)
|
| 127 |
+
if text is not None:
|
| 128 |
+
if isinstance(text, str):
|
| 129 |
+
text = [text]
|
| 130 |
+
elif not isinstance(text, list) and not isinstance(text[0], str):
|
| 131 |
+
raise ValueError("Invalid input text. Please provide a string, or a list of strings")
|
| 132 |
+
|
| 133 |
+
text_encoding = {}
|
| 134 |
+
|
| 135 |
+
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
|
| 136 |
+
_text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"], return_tensors=None)
|
| 137 |
+
output_kwargs["text_kwargs"]["return_tensors"] = return_tensors
|
| 138 |
+
|
| 139 |
+
# if we know how many query tokens, expand text inside processor. We need this hacky manipulation
|
| 140 |
+
# because BLIP expects image tokens to be at the beginning even before BOS token
|
| 141 |
+
if self.num_query_tokens is not None:
|
| 142 |
+
image_tokens = self.image_token.content * self.num_query_tokens
|
| 143 |
+
image_token_encoding = self.tokenizer(
|
| 144 |
+
[image_tokens] * len(text), add_special_tokens=False, return_tensors=None
|
| 145 |
+
)
|
| 146 |
+
for k in _text_encoding:
|
| 147 |
+
text_encoding[k] = [
|
| 148 |
+
img_encoding + txt_encoding
|
| 149 |
+
for img_encoding, txt_encoding in zip(image_token_encoding[k], _text_encoding[k])
|
| 150 |
+
]
|
| 151 |
+
else:
|
| 152 |
+
text_encoding = _text_encoding
|
| 153 |
+
logger.warning_once(
|
| 154 |
+
"Expanding inputs for image tokens in BLIP-2 should be done in processing. "
|
| 155 |
+
"Please follow instruction here (https://gist.github.com/zucchini-nlp/e9f20b054fa322f84ac9311d9ab67042) to update your BLIP-2 model. "
|
| 156 |
+
"Using processors without these attributes in the config is deprecated and will throw an error in v4.50."
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# cast to desired return tensors type
|
| 160 |
+
encoding.update(BatchEncoding(text_encoding, tensor_type=return_tensors))
|
| 161 |
+
# add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
|
| 162 |
+
# else, return the text encoding.
|
| 163 |
+
|
| 164 |
+
if images is not None:
|
| 165 |
+
image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 166 |
+
encoding.update(image_encoding)
|
| 167 |
+
return encoding
|
| 168 |
+
|
| 169 |
+
# Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer
|
| 170 |
+
def batch_decode(self, *args, **kwargs):
|
| 171 |
+
"""
|
| 172 |
+
This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 173 |
+
refer to the docstring of this method for more information.
|
| 174 |
+
"""
|
| 175 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 176 |
+
|
| 177 |
+
# Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer
|
| 178 |
+
def decode(self, *args, **kwargs):
|
| 179 |
+
"""
|
| 180 |
+
This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 181 |
+
the docstring of this method for more information.
|
| 182 |
+
"""
|
| 183 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 184 |
+
|
| 185 |
+
@property
|
| 186 |
+
# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
|
| 187 |
+
def model_input_names(self):
|
| 188 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 189 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 190 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
__all__ = ["Blip2Processor"]
|
lib/python3.12/site-packages/transformers/models/cvt/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_cvt import *
|
| 22 |
+
from .modeling_cvt import *
|
| 23 |
+
from .modeling_tf_cvt import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (688 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-312.pyc
ADDED
|
Binary file (6.41 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-312.pyc
ADDED
|
Binary file (36.4 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-312.pyc
ADDED
|
Binary file (54.2 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/cvt/configuration_cvt.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""CvT model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class CvtConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`CvtModel`]. It is used to instantiate a CvT model
|
| 27 |
+
according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 28 |
+
defaults will yield a similar configuration to that of the CvT
|
| 29 |
+
[microsoft/cvt-13](https://huggingface.co/microsoft/cvt-13) architecture.
|
| 30 |
+
|
| 31 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 32 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 36 |
+
The number of input channels.
|
| 37 |
+
patch_sizes (`List[int]`, *optional*, defaults to `[7, 3, 3]`):
|
| 38 |
+
The kernel size of each encoder's patch embedding.
|
| 39 |
+
patch_stride (`List[int]`, *optional*, defaults to `[4, 2, 2]`):
|
| 40 |
+
The stride size of each encoder's patch embedding.
|
| 41 |
+
patch_padding (`List[int]`, *optional*, defaults to `[2, 1, 1]`):
|
| 42 |
+
The padding size of each encoder's patch embedding.
|
| 43 |
+
embed_dim (`List[int]`, *optional*, defaults to `[64, 192, 384]`):
|
| 44 |
+
Dimension of each of the encoder blocks.
|
| 45 |
+
num_heads (`List[int]`, *optional*, defaults to `[1, 3, 6]`):
|
| 46 |
+
Number of attention heads for each attention layer in each block of the Transformer encoder.
|
| 47 |
+
depth (`List[int]`, *optional*, defaults to `[1, 2, 10]`):
|
| 48 |
+
The number of layers in each encoder block.
|
| 49 |
+
mlp_ratios (`List[float]`, *optional*, defaults to `[4.0, 4.0, 4.0, 4.0]`):
|
| 50 |
+
Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
|
| 51 |
+
encoder blocks.
|
| 52 |
+
attention_drop_rate (`List[float]`, *optional*, defaults to `[0.0, 0.0, 0.0]`):
|
| 53 |
+
The dropout ratio for the attention probabilities.
|
| 54 |
+
drop_rate (`List[float]`, *optional*, defaults to `[0.0, 0.0, 0.0]`):
|
| 55 |
+
The dropout ratio for the patch embeddings probabilities.
|
| 56 |
+
drop_path_rate (`List[float]`, *optional*, defaults to `[0.0, 0.0, 0.1]`):
|
| 57 |
+
The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
|
| 58 |
+
qkv_bias (`List[bool]`, *optional*, defaults to `[True, True, True]`):
|
| 59 |
+
The bias bool for query, key and value in attentions
|
| 60 |
+
cls_token (`List[bool]`, *optional*, defaults to `[False, False, True]`):
|
| 61 |
+
Whether or not to add a classification token to the output of each of the last 3 stages.
|
| 62 |
+
qkv_projection_method (`List[string]`, *optional*, defaults to ["dw_bn", "dw_bn", "dw_bn"]`):
|
| 63 |
+
The projection method for query, key and value Default is depth-wise convolutions with batch norm. For
|
| 64 |
+
Linear projection use "avg".
|
| 65 |
+
kernel_qkv (`List[int]`, *optional*, defaults to `[3, 3, 3]`):
|
| 66 |
+
The kernel size for query, key and value in attention layer
|
| 67 |
+
padding_kv (`List[int]`, *optional*, defaults to `[1, 1, 1]`):
|
| 68 |
+
The padding size for key and value in attention layer
|
| 69 |
+
stride_kv (`List[int]`, *optional*, defaults to `[2, 2, 2]`):
|
| 70 |
+
The stride size for key and value in attention layer
|
| 71 |
+
padding_q (`List[int]`, *optional*, defaults to `[1, 1, 1]`):
|
| 72 |
+
The padding size for query in attention layer
|
| 73 |
+
stride_q (`List[int]`, *optional*, defaults to `[1, 1, 1]`):
|
| 74 |
+
The stride size for query in attention layer
|
| 75 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 76 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 77 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-6):
|
| 78 |
+
The epsilon used by the layer normalization layers.
|
| 79 |
+
|
| 80 |
+
Example:
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
>>> from transformers import CvtConfig, CvtModel
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a Cvt msft/cvt style configuration
|
| 86 |
+
>>> configuration = CvtConfig()
|
| 87 |
+
|
| 88 |
+
>>> # Initializing a model (with random weights) from the msft/cvt style configuration
|
| 89 |
+
>>> model = CvtModel(configuration)
|
| 90 |
+
|
| 91 |
+
>>> # Accessing the model configuration
|
| 92 |
+
>>> configuration = model.config
|
| 93 |
+
```"""
|
| 94 |
+
|
| 95 |
+
model_type = "cvt"
|
| 96 |
+
|
| 97 |
+
def __init__(
|
| 98 |
+
self,
|
| 99 |
+
num_channels=3,
|
| 100 |
+
patch_sizes=[7, 3, 3],
|
| 101 |
+
patch_stride=[4, 2, 2],
|
| 102 |
+
patch_padding=[2, 1, 1],
|
| 103 |
+
embed_dim=[64, 192, 384],
|
| 104 |
+
num_heads=[1, 3, 6],
|
| 105 |
+
depth=[1, 2, 10],
|
| 106 |
+
mlp_ratio=[4.0, 4.0, 4.0],
|
| 107 |
+
attention_drop_rate=[0.0, 0.0, 0.0],
|
| 108 |
+
drop_rate=[0.0, 0.0, 0.0],
|
| 109 |
+
drop_path_rate=[0.0, 0.0, 0.1],
|
| 110 |
+
qkv_bias=[True, True, True],
|
| 111 |
+
cls_token=[False, False, True],
|
| 112 |
+
qkv_projection_method=["dw_bn", "dw_bn", "dw_bn"],
|
| 113 |
+
kernel_qkv=[3, 3, 3],
|
| 114 |
+
padding_kv=[1, 1, 1],
|
| 115 |
+
stride_kv=[2, 2, 2],
|
| 116 |
+
padding_q=[1, 1, 1],
|
| 117 |
+
stride_q=[1, 1, 1],
|
| 118 |
+
initializer_range=0.02,
|
| 119 |
+
layer_norm_eps=1e-12,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
super().__init__(**kwargs)
|
| 123 |
+
self.num_channels = num_channels
|
| 124 |
+
self.patch_sizes = patch_sizes
|
| 125 |
+
self.patch_stride = patch_stride
|
| 126 |
+
self.patch_padding = patch_padding
|
| 127 |
+
self.embed_dim = embed_dim
|
| 128 |
+
self.num_heads = num_heads
|
| 129 |
+
self.depth = depth
|
| 130 |
+
self.mlp_ratio = mlp_ratio
|
| 131 |
+
self.attention_drop_rate = attention_drop_rate
|
| 132 |
+
self.drop_rate = drop_rate
|
| 133 |
+
self.drop_path_rate = drop_path_rate
|
| 134 |
+
self.qkv_bias = qkv_bias
|
| 135 |
+
self.cls_token = cls_token
|
| 136 |
+
self.qkv_projection_method = qkv_projection_method
|
| 137 |
+
self.kernel_qkv = kernel_qkv
|
| 138 |
+
self.padding_kv = padding_kv
|
| 139 |
+
self.stride_kv = stride_kv
|
| 140 |
+
self.padding_q = padding_q
|
| 141 |
+
self.stride_q = stride_q
|
| 142 |
+
self.initializer_range = initializer_range
|
| 143 |
+
self.layer_norm_eps = layer_norm_eps
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
__all__ = ["CvtConfig"]
|
lib/python3.12/site-packages/transformers/models/cvt/modeling_cvt.py
ADDED
|
@@ -0,0 +1,725 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch CvT model."""
|
| 16 |
+
|
| 17 |
+
import collections.abc
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 25 |
+
|
| 26 |
+
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
|
| 27 |
+
from ...modeling_outputs import ImageClassifierOutputWithNoAttention, ModelOutput
|
| 28 |
+
from ...modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer
|
| 29 |
+
from ...utils import logging
|
| 30 |
+
from .configuration_cvt import CvtConfig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
# General docstring
|
| 36 |
+
_CONFIG_FOR_DOC = "CvtConfig"
|
| 37 |
+
|
| 38 |
+
# Base docstring
|
| 39 |
+
_CHECKPOINT_FOR_DOC = "microsoft/cvt-13"
|
| 40 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 384, 14, 14]
|
| 41 |
+
|
| 42 |
+
# Image classification docstring
|
| 43 |
+
_IMAGE_CLASS_CHECKPOINT = "microsoft/cvt-13"
|
| 44 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class BaseModelOutputWithCLSToken(ModelOutput):
|
| 49 |
+
"""
|
| 50 |
+
Base class for model's outputs, with potential hidden states and attentions.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 54 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 55 |
+
cls_token_value (`torch.FloatTensor` of shape `(batch_size, 1, hidden_size)`):
|
| 56 |
+
Classification token at the output of the last layer of the model.
|
| 57 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 58 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 59 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 60 |
+
plus the initial embedding outputs.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 64 |
+
cls_token_value: Optional[torch.FloatTensor] = None
|
| 65 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 69 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 70 |
+
"""
|
| 71 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 72 |
+
|
| 73 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 74 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 75 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 76 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 77 |
+
argument.
|
| 78 |
+
"""
|
| 79 |
+
if drop_prob == 0.0 or not training:
|
| 80 |
+
return input
|
| 81 |
+
keep_prob = 1 - drop_prob
|
| 82 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 83 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 84 |
+
random_tensor.floor_() # binarize
|
| 85 |
+
output = input.div(keep_prob) * random_tensor
|
| 86 |
+
return output
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Copied from transformers.models.beit.modeling_beit.BeitDropPath
|
| 90 |
+
class CvtDropPath(nn.Module):
|
| 91 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 92 |
+
|
| 93 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 94 |
+
super().__init__()
|
| 95 |
+
self.drop_prob = drop_prob
|
| 96 |
+
|
| 97 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 98 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 99 |
+
|
| 100 |
+
def extra_repr(self) -> str:
|
| 101 |
+
return "p={}".format(self.drop_prob)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class CvtEmbeddings(nn.Module):
|
| 105 |
+
"""
|
| 106 |
+
Construct the CvT embeddings.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
def __init__(self, patch_size, num_channels, embed_dim, stride, padding, dropout_rate):
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.convolution_embeddings = CvtConvEmbeddings(
|
| 112 |
+
patch_size=patch_size, num_channels=num_channels, embed_dim=embed_dim, stride=stride, padding=padding
|
| 113 |
+
)
|
| 114 |
+
self.dropout = nn.Dropout(dropout_rate)
|
| 115 |
+
|
| 116 |
+
def forward(self, pixel_values):
|
| 117 |
+
hidden_state = self.convolution_embeddings(pixel_values)
|
| 118 |
+
hidden_state = self.dropout(hidden_state)
|
| 119 |
+
return hidden_state
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class CvtConvEmbeddings(nn.Module):
|
| 123 |
+
"""
|
| 124 |
+
Image to Conv Embedding.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
def __init__(self, patch_size, num_channels, embed_dim, stride, padding):
|
| 128 |
+
super().__init__()
|
| 129 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 130 |
+
self.patch_size = patch_size
|
| 131 |
+
self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=stride, padding=padding)
|
| 132 |
+
self.normalization = nn.LayerNorm(embed_dim)
|
| 133 |
+
|
| 134 |
+
def forward(self, pixel_values):
|
| 135 |
+
pixel_values = self.projection(pixel_values)
|
| 136 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
| 137 |
+
hidden_size = height * width
|
| 138 |
+
# rearrange "b c h w -> b (h w) c"
|
| 139 |
+
pixel_values = pixel_values.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
|
| 140 |
+
if self.normalization:
|
| 141 |
+
pixel_values = self.normalization(pixel_values)
|
| 142 |
+
# rearrange "b (h w) c" -> b c h w"
|
| 143 |
+
pixel_values = pixel_values.permute(0, 2, 1).view(batch_size, num_channels, height, width)
|
| 144 |
+
return pixel_values
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class CvtSelfAttentionConvProjection(nn.Module):
|
| 148 |
+
def __init__(self, embed_dim, kernel_size, padding, stride):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.convolution = nn.Conv2d(
|
| 151 |
+
embed_dim,
|
| 152 |
+
embed_dim,
|
| 153 |
+
kernel_size=kernel_size,
|
| 154 |
+
padding=padding,
|
| 155 |
+
stride=stride,
|
| 156 |
+
bias=False,
|
| 157 |
+
groups=embed_dim,
|
| 158 |
+
)
|
| 159 |
+
self.normalization = nn.BatchNorm2d(embed_dim)
|
| 160 |
+
|
| 161 |
+
def forward(self, hidden_state):
|
| 162 |
+
hidden_state = self.convolution(hidden_state)
|
| 163 |
+
hidden_state = self.normalization(hidden_state)
|
| 164 |
+
return hidden_state
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class CvtSelfAttentionLinearProjection(nn.Module):
|
| 168 |
+
def forward(self, hidden_state):
|
| 169 |
+
batch_size, num_channels, height, width = hidden_state.shape
|
| 170 |
+
hidden_size = height * width
|
| 171 |
+
# rearrange " b c h w -> b (h w) c"
|
| 172 |
+
hidden_state = hidden_state.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
|
| 173 |
+
return hidden_state
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class CvtSelfAttentionProjection(nn.Module):
|
| 177 |
+
def __init__(self, embed_dim, kernel_size, padding, stride, projection_method="dw_bn"):
|
| 178 |
+
super().__init__()
|
| 179 |
+
if projection_method == "dw_bn":
|
| 180 |
+
self.convolution_projection = CvtSelfAttentionConvProjection(embed_dim, kernel_size, padding, stride)
|
| 181 |
+
self.linear_projection = CvtSelfAttentionLinearProjection()
|
| 182 |
+
|
| 183 |
+
def forward(self, hidden_state):
|
| 184 |
+
hidden_state = self.convolution_projection(hidden_state)
|
| 185 |
+
hidden_state = self.linear_projection(hidden_state)
|
| 186 |
+
return hidden_state
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class CvtSelfAttention(nn.Module):
|
| 190 |
+
def __init__(
|
| 191 |
+
self,
|
| 192 |
+
num_heads,
|
| 193 |
+
embed_dim,
|
| 194 |
+
kernel_size,
|
| 195 |
+
padding_q,
|
| 196 |
+
padding_kv,
|
| 197 |
+
stride_q,
|
| 198 |
+
stride_kv,
|
| 199 |
+
qkv_projection_method,
|
| 200 |
+
qkv_bias,
|
| 201 |
+
attention_drop_rate,
|
| 202 |
+
with_cls_token=True,
|
| 203 |
+
**kwargs,
|
| 204 |
+
):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.scale = embed_dim**-0.5
|
| 207 |
+
self.with_cls_token = with_cls_token
|
| 208 |
+
self.embed_dim = embed_dim
|
| 209 |
+
self.num_heads = num_heads
|
| 210 |
+
|
| 211 |
+
self.convolution_projection_query = CvtSelfAttentionProjection(
|
| 212 |
+
embed_dim,
|
| 213 |
+
kernel_size,
|
| 214 |
+
padding_q,
|
| 215 |
+
stride_q,
|
| 216 |
+
projection_method="linear" if qkv_projection_method == "avg" else qkv_projection_method,
|
| 217 |
+
)
|
| 218 |
+
self.convolution_projection_key = CvtSelfAttentionProjection(
|
| 219 |
+
embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
|
| 220 |
+
)
|
| 221 |
+
self.convolution_projection_value = CvtSelfAttentionProjection(
|
| 222 |
+
embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
self.projection_query = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
|
| 226 |
+
self.projection_key = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
|
| 227 |
+
self.projection_value = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
|
| 228 |
+
|
| 229 |
+
self.dropout = nn.Dropout(attention_drop_rate)
|
| 230 |
+
|
| 231 |
+
def rearrange_for_multi_head_attention(self, hidden_state):
|
| 232 |
+
batch_size, hidden_size, _ = hidden_state.shape
|
| 233 |
+
head_dim = self.embed_dim // self.num_heads
|
| 234 |
+
# rearrange 'b t (h d) -> b h t d'
|
| 235 |
+
return hidden_state.view(batch_size, hidden_size, self.num_heads, head_dim).permute(0, 2, 1, 3)
|
| 236 |
+
|
| 237 |
+
def forward(self, hidden_state, height, width):
|
| 238 |
+
if self.with_cls_token:
|
| 239 |
+
cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
|
| 240 |
+
batch_size, hidden_size, num_channels = hidden_state.shape
|
| 241 |
+
# rearrange "b (h w) c -> b c h w"
|
| 242 |
+
hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
|
| 243 |
+
|
| 244 |
+
key = self.convolution_projection_key(hidden_state)
|
| 245 |
+
query = self.convolution_projection_query(hidden_state)
|
| 246 |
+
value = self.convolution_projection_value(hidden_state)
|
| 247 |
+
|
| 248 |
+
if self.with_cls_token:
|
| 249 |
+
query = torch.cat((cls_token, query), dim=1)
|
| 250 |
+
key = torch.cat((cls_token, key), dim=1)
|
| 251 |
+
value = torch.cat((cls_token, value), dim=1)
|
| 252 |
+
|
| 253 |
+
head_dim = self.embed_dim // self.num_heads
|
| 254 |
+
|
| 255 |
+
query = self.rearrange_for_multi_head_attention(self.projection_query(query))
|
| 256 |
+
key = self.rearrange_for_multi_head_attention(self.projection_key(key))
|
| 257 |
+
value = self.rearrange_for_multi_head_attention(self.projection_value(value))
|
| 258 |
+
|
| 259 |
+
attention_score = torch.einsum("bhlk,bhtk->bhlt", [query, key]) * self.scale
|
| 260 |
+
attention_probs = torch.nn.functional.softmax(attention_score, dim=-1)
|
| 261 |
+
attention_probs = self.dropout(attention_probs)
|
| 262 |
+
|
| 263 |
+
context = torch.einsum("bhlt,bhtv->bhlv", [attention_probs, value])
|
| 264 |
+
# rearrange"b h t d -> b t (h d)"
|
| 265 |
+
_, _, hidden_size, _ = context.shape
|
| 266 |
+
context = context.permute(0, 2, 1, 3).contiguous().view(batch_size, hidden_size, self.num_heads * head_dim)
|
| 267 |
+
return context
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class CvtSelfOutput(nn.Module):
|
| 271 |
+
"""
|
| 272 |
+
The residual connection is defined in CvtLayer instead of here (as is the case with other models), due to the
|
| 273 |
+
layernorm applied before each block.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
def __init__(self, embed_dim, drop_rate):
|
| 277 |
+
super().__init__()
|
| 278 |
+
self.dense = nn.Linear(embed_dim, embed_dim)
|
| 279 |
+
self.dropout = nn.Dropout(drop_rate)
|
| 280 |
+
|
| 281 |
+
def forward(self, hidden_state, input_tensor):
|
| 282 |
+
hidden_state = self.dense(hidden_state)
|
| 283 |
+
hidden_state = self.dropout(hidden_state)
|
| 284 |
+
return hidden_state
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class CvtAttention(nn.Module):
|
| 288 |
+
def __init__(
|
| 289 |
+
self,
|
| 290 |
+
num_heads,
|
| 291 |
+
embed_dim,
|
| 292 |
+
kernel_size,
|
| 293 |
+
padding_q,
|
| 294 |
+
padding_kv,
|
| 295 |
+
stride_q,
|
| 296 |
+
stride_kv,
|
| 297 |
+
qkv_projection_method,
|
| 298 |
+
qkv_bias,
|
| 299 |
+
attention_drop_rate,
|
| 300 |
+
drop_rate,
|
| 301 |
+
with_cls_token=True,
|
| 302 |
+
):
|
| 303 |
+
super().__init__()
|
| 304 |
+
self.attention = CvtSelfAttention(
|
| 305 |
+
num_heads,
|
| 306 |
+
embed_dim,
|
| 307 |
+
kernel_size,
|
| 308 |
+
padding_q,
|
| 309 |
+
padding_kv,
|
| 310 |
+
stride_q,
|
| 311 |
+
stride_kv,
|
| 312 |
+
qkv_projection_method,
|
| 313 |
+
qkv_bias,
|
| 314 |
+
attention_drop_rate,
|
| 315 |
+
with_cls_token,
|
| 316 |
+
)
|
| 317 |
+
self.output = CvtSelfOutput(embed_dim, drop_rate)
|
| 318 |
+
self.pruned_heads = set()
|
| 319 |
+
|
| 320 |
+
def prune_heads(self, heads):
|
| 321 |
+
if len(heads) == 0:
|
| 322 |
+
return
|
| 323 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 324 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Prune linear layers
|
| 328 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 329 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 330 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 331 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 332 |
+
|
| 333 |
+
# Update hyper params and store pruned heads
|
| 334 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 335 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 336 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 337 |
+
|
| 338 |
+
def forward(self, hidden_state, height, width):
|
| 339 |
+
self_output = self.attention(hidden_state, height, width)
|
| 340 |
+
attention_output = self.output(self_output, hidden_state)
|
| 341 |
+
return attention_output
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class CvtIntermediate(nn.Module):
|
| 345 |
+
def __init__(self, embed_dim, mlp_ratio):
|
| 346 |
+
super().__init__()
|
| 347 |
+
self.dense = nn.Linear(embed_dim, int(embed_dim * mlp_ratio))
|
| 348 |
+
self.activation = nn.GELU()
|
| 349 |
+
|
| 350 |
+
def forward(self, hidden_state):
|
| 351 |
+
hidden_state = self.dense(hidden_state)
|
| 352 |
+
hidden_state = self.activation(hidden_state)
|
| 353 |
+
return hidden_state
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class CvtOutput(nn.Module):
|
| 357 |
+
def __init__(self, embed_dim, mlp_ratio, drop_rate):
|
| 358 |
+
super().__init__()
|
| 359 |
+
self.dense = nn.Linear(int(embed_dim * mlp_ratio), embed_dim)
|
| 360 |
+
self.dropout = nn.Dropout(drop_rate)
|
| 361 |
+
|
| 362 |
+
def forward(self, hidden_state, input_tensor):
|
| 363 |
+
hidden_state = self.dense(hidden_state)
|
| 364 |
+
hidden_state = self.dropout(hidden_state)
|
| 365 |
+
hidden_state = hidden_state + input_tensor
|
| 366 |
+
return hidden_state
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class CvtLayer(nn.Module):
|
| 370 |
+
"""
|
| 371 |
+
CvtLayer composed by attention layers, normalization and multi-layer perceptrons (mlps).
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
def __init__(
|
| 375 |
+
self,
|
| 376 |
+
num_heads,
|
| 377 |
+
embed_dim,
|
| 378 |
+
kernel_size,
|
| 379 |
+
padding_q,
|
| 380 |
+
padding_kv,
|
| 381 |
+
stride_q,
|
| 382 |
+
stride_kv,
|
| 383 |
+
qkv_projection_method,
|
| 384 |
+
qkv_bias,
|
| 385 |
+
attention_drop_rate,
|
| 386 |
+
drop_rate,
|
| 387 |
+
mlp_ratio,
|
| 388 |
+
drop_path_rate,
|
| 389 |
+
with_cls_token=True,
|
| 390 |
+
):
|
| 391 |
+
super().__init__()
|
| 392 |
+
self.attention = CvtAttention(
|
| 393 |
+
num_heads,
|
| 394 |
+
embed_dim,
|
| 395 |
+
kernel_size,
|
| 396 |
+
padding_q,
|
| 397 |
+
padding_kv,
|
| 398 |
+
stride_q,
|
| 399 |
+
stride_kv,
|
| 400 |
+
qkv_projection_method,
|
| 401 |
+
qkv_bias,
|
| 402 |
+
attention_drop_rate,
|
| 403 |
+
drop_rate,
|
| 404 |
+
with_cls_token,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
self.intermediate = CvtIntermediate(embed_dim, mlp_ratio)
|
| 408 |
+
self.output = CvtOutput(embed_dim, mlp_ratio, drop_rate)
|
| 409 |
+
self.drop_path = CvtDropPath(drop_prob=drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
|
| 410 |
+
self.layernorm_before = nn.LayerNorm(embed_dim)
|
| 411 |
+
self.layernorm_after = nn.LayerNorm(embed_dim)
|
| 412 |
+
|
| 413 |
+
def forward(self, hidden_state, height, width):
|
| 414 |
+
self_attention_output = self.attention(
|
| 415 |
+
self.layernorm_before(hidden_state), # in Cvt, layernorm is applied before self-attention
|
| 416 |
+
height,
|
| 417 |
+
width,
|
| 418 |
+
)
|
| 419 |
+
attention_output = self_attention_output
|
| 420 |
+
attention_output = self.drop_path(attention_output)
|
| 421 |
+
|
| 422 |
+
# first residual connection
|
| 423 |
+
hidden_state = attention_output + hidden_state
|
| 424 |
+
|
| 425 |
+
# in Cvt, layernorm is also applied after self-attention
|
| 426 |
+
layer_output = self.layernorm_after(hidden_state)
|
| 427 |
+
layer_output = self.intermediate(layer_output)
|
| 428 |
+
|
| 429 |
+
# second residual connection is done here
|
| 430 |
+
layer_output = self.output(layer_output, hidden_state)
|
| 431 |
+
layer_output = self.drop_path(layer_output)
|
| 432 |
+
return layer_output
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class CvtStage(nn.Module):
|
| 436 |
+
def __init__(self, config, stage):
|
| 437 |
+
super().__init__()
|
| 438 |
+
self.config = config
|
| 439 |
+
self.stage = stage
|
| 440 |
+
if self.config.cls_token[self.stage]:
|
| 441 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, self.config.embed_dim[-1]))
|
| 442 |
+
|
| 443 |
+
self.embedding = CvtEmbeddings(
|
| 444 |
+
patch_size=config.patch_sizes[self.stage],
|
| 445 |
+
stride=config.patch_stride[self.stage],
|
| 446 |
+
num_channels=config.num_channels if self.stage == 0 else config.embed_dim[self.stage - 1],
|
| 447 |
+
embed_dim=config.embed_dim[self.stage],
|
| 448 |
+
padding=config.patch_padding[self.stage],
|
| 449 |
+
dropout_rate=config.drop_rate[self.stage],
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
drop_path_rates = [x.item() for x in torch.linspace(0, config.drop_path_rate[self.stage], config.depth[stage])]
|
| 453 |
+
|
| 454 |
+
self.layers = nn.Sequential(
|
| 455 |
+
*[
|
| 456 |
+
CvtLayer(
|
| 457 |
+
num_heads=config.num_heads[self.stage],
|
| 458 |
+
embed_dim=config.embed_dim[self.stage],
|
| 459 |
+
kernel_size=config.kernel_qkv[self.stage],
|
| 460 |
+
padding_q=config.padding_q[self.stage],
|
| 461 |
+
padding_kv=config.padding_kv[self.stage],
|
| 462 |
+
stride_kv=config.stride_kv[self.stage],
|
| 463 |
+
stride_q=config.stride_q[self.stage],
|
| 464 |
+
qkv_projection_method=config.qkv_projection_method[self.stage],
|
| 465 |
+
qkv_bias=config.qkv_bias[self.stage],
|
| 466 |
+
attention_drop_rate=config.attention_drop_rate[self.stage],
|
| 467 |
+
drop_rate=config.drop_rate[self.stage],
|
| 468 |
+
drop_path_rate=drop_path_rates[self.stage],
|
| 469 |
+
mlp_ratio=config.mlp_ratio[self.stage],
|
| 470 |
+
with_cls_token=config.cls_token[self.stage],
|
| 471 |
+
)
|
| 472 |
+
for _ in range(config.depth[self.stage])
|
| 473 |
+
]
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
def forward(self, hidden_state):
|
| 477 |
+
cls_token = None
|
| 478 |
+
hidden_state = self.embedding(hidden_state)
|
| 479 |
+
batch_size, num_channels, height, width = hidden_state.shape
|
| 480 |
+
# rearrange b c h w -> b (h w) c"
|
| 481 |
+
hidden_state = hidden_state.view(batch_size, num_channels, height * width).permute(0, 2, 1)
|
| 482 |
+
if self.config.cls_token[self.stage]:
|
| 483 |
+
cls_token = self.cls_token.expand(batch_size, -1, -1)
|
| 484 |
+
hidden_state = torch.cat((cls_token, hidden_state), dim=1)
|
| 485 |
+
|
| 486 |
+
for layer in self.layers:
|
| 487 |
+
layer_outputs = layer(hidden_state, height, width)
|
| 488 |
+
hidden_state = layer_outputs
|
| 489 |
+
|
| 490 |
+
if self.config.cls_token[self.stage]:
|
| 491 |
+
cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
|
| 492 |
+
hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
|
| 493 |
+
return hidden_state, cls_token
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
class CvtEncoder(nn.Module):
|
| 497 |
+
def __init__(self, config):
|
| 498 |
+
super().__init__()
|
| 499 |
+
self.config = config
|
| 500 |
+
self.stages = nn.ModuleList([])
|
| 501 |
+
for stage_idx in range(len(config.depth)):
|
| 502 |
+
self.stages.append(CvtStage(config, stage_idx))
|
| 503 |
+
|
| 504 |
+
def forward(self, pixel_values, output_hidden_states=False, return_dict=True):
|
| 505 |
+
all_hidden_states = () if output_hidden_states else None
|
| 506 |
+
hidden_state = pixel_values
|
| 507 |
+
|
| 508 |
+
cls_token = None
|
| 509 |
+
for _, (stage_module) in enumerate(self.stages):
|
| 510 |
+
hidden_state, cls_token = stage_module(hidden_state)
|
| 511 |
+
if output_hidden_states:
|
| 512 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 513 |
+
|
| 514 |
+
if not return_dict:
|
| 515 |
+
return tuple(v for v in [hidden_state, cls_token, all_hidden_states] if v is not None)
|
| 516 |
+
|
| 517 |
+
return BaseModelOutputWithCLSToken(
|
| 518 |
+
last_hidden_state=hidden_state,
|
| 519 |
+
cls_token_value=cls_token,
|
| 520 |
+
hidden_states=all_hidden_states,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class CvtPreTrainedModel(PreTrainedModel):
|
| 525 |
+
"""
|
| 526 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 527 |
+
models.
|
| 528 |
+
"""
|
| 529 |
+
|
| 530 |
+
config_class = CvtConfig
|
| 531 |
+
base_model_prefix = "cvt"
|
| 532 |
+
main_input_name = "pixel_values"
|
| 533 |
+
_no_split_modules = ["CvtLayer"]
|
| 534 |
+
|
| 535 |
+
def _init_weights(self, module):
|
| 536 |
+
"""Initialize the weights"""
|
| 537 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 538 |
+
module.weight.data = nn.init.trunc_normal_(module.weight.data, mean=0.0, std=self.config.initializer_range)
|
| 539 |
+
if module.bias is not None:
|
| 540 |
+
module.bias.data.zero_()
|
| 541 |
+
elif isinstance(module, nn.LayerNorm):
|
| 542 |
+
module.bias.data.zero_()
|
| 543 |
+
module.weight.data.fill_(1.0)
|
| 544 |
+
elif isinstance(module, CvtStage):
|
| 545 |
+
if self.config.cls_token[module.stage]:
|
| 546 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 547 |
+
module.cls_token.data, mean=0.0, std=self.config.initializer_range
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
CVT_START_DOCSTRING = r"""
|
| 552 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 553 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 554 |
+
behavior.
|
| 555 |
+
|
| 556 |
+
Parameters:
|
| 557 |
+
config ([`CvtConfig`]): Model configuration class with all the parameters of the model.
|
| 558 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 559 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
CVT_INPUTS_DOCSTRING = r"""
|
| 563 |
+
Args:
|
| 564 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 565 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`CvtImageProcessor.__call__`]
|
| 566 |
+
for details.
|
| 567 |
+
output_hidden_states (`bool`, *optional*):
|
| 568 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 569 |
+
more detail.
|
| 570 |
+
return_dict (`bool`, *optional*):
|
| 571 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
|
| 572 |
+
"""
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@add_start_docstrings(
|
| 576 |
+
"The bare Cvt Model transformer outputting raw hidden-states without any specific head on top.",
|
| 577 |
+
CVT_START_DOCSTRING,
|
| 578 |
+
)
|
| 579 |
+
class CvtModel(CvtPreTrainedModel):
|
| 580 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 581 |
+
super().__init__(config)
|
| 582 |
+
self.config = config
|
| 583 |
+
self.encoder = CvtEncoder(config)
|
| 584 |
+
self.post_init()
|
| 585 |
+
|
| 586 |
+
def _prune_heads(self, heads_to_prune):
|
| 587 |
+
"""
|
| 588 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 589 |
+
class PreTrainedModel
|
| 590 |
+
"""
|
| 591 |
+
for layer, heads in heads_to_prune.items():
|
| 592 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 593 |
+
|
| 594 |
+
@add_start_docstrings_to_model_forward(CVT_INPUTS_DOCSTRING)
|
| 595 |
+
@add_code_sample_docstrings(
|
| 596 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 597 |
+
output_type=BaseModelOutputWithCLSToken,
|
| 598 |
+
config_class=_CONFIG_FOR_DOC,
|
| 599 |
+
modality="vision",
|
| 600 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 601 |
+
)
|
| 602 |
+
def forward(
|
| 603 |
+
self,
|
| 604 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 605 |
+
output_hidden_states: Optional[bool] = None,
|
| 606 |
+
return_dict: Optional[bool] = None,
|
| 607 |
+
) -> Union[Tuple, BaseModelOutputWithCLSToken]:
|
| 608 |
+
output_hidden_states = (
|
| 609 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 610 |
+
)
|
| 611 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 612 |
+
|
| 613 |
+
if pixel_values is None:
|
| 614 |
+
raise ValueError("You have to specify pixel_values")
|
| 615 |
+
|
| 616 |
+
encoder_outputs = self.encoder(
|
| 617 |
+
pixel_values,
|
| 618 |
+
output_hidden_states=output_hidden_states,
|
| 619 |
+
return_dict=return_dict,
|
| 620 |
+
)
|
| 621 |
+
sequence_output = encoder_outputs[0]
|
| 622 |
+
|
| 623 |
+
if not return_dict:
|
| 624 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 625 |
+
|
| 626 |
+
return BaseModelOutputWithCLSToken(
|
| 627 |
+
last_hidden_state=sequence_output,
|
| 628 |
+
cls_token_value=encoder_outputs.cls_token_value,
|
| 629 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
@add_start_docstrings(
|
| 634 |
+
"""
|
| 635 |
+
Cvt Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
| 636 |
+
the [CLS] token) e.g. for ImageNet.
|
| 637 |
+
""",
|
| 638 |
+
CVT_START_DOCSTRING,
|
| 639 |
+
)
|
| 640 |
+
class CvtForImageClassification(CvtPreTrainedModel):
|
| 641 |
+
def __init__(self, config):
|
| 642 |
+
super().__init__(config)
|
| 643 |
+
|
| 644 |
+
self.num_labels = config.num_labels
|
| 645 |
+
self.cvt = CvtModel(config, add_pooling_layer=False)
|
| 646 |
+
self.layernorm = nn.LayerNorm(config.embed_dim[-1])
|
| 647 |
+
# Classifier head
|
| 648 |
+
self.classifier = (
|
| 649 |
+
nn.Linear(config.embed_dim[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
# Initialize weights and apply final processing
|
| 653 |
+
self.post_init()
|
| 654 |
+
|
| 655 |
+
@add_start_docstrings_to_model_forward(CVT_INPUTS_DOCSTRING)
|
| 656 |
+
@add_code_sample_docstrings(
|
| 657 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 658 |
+
output_type=ImageClassifierOutputWithNoAttention,
|
| 659 |
+
config_class=_CONFIG_FOR_DOC,
|
| 660 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 661 |
+
)
|
| 662 |
+
def forward(
|
| 663 |
+
self,
|
| 664 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 665 |
+
labels: Optional[torch.Tensor] = None,
|
| 666 |
+
output_hidden_states: Optional[bool] = None,
|
| 667 |
+
return_dict: Optional[bool] = None,
|
| 668 |
+
) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
|
| 669 |
+
r"""
|
| 670 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 671 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 672 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 673 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 674 |
+
"""
|
| 675 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 676 |
+
outputs = self.cvt(
|
| 677 |
+
pixel_values,
|
| 678 |
+
output_hidden_states=output_hidden_states,
|
| 679 |
+
return_dict=return_dict,
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
sequence_output = outputs[0]
|
| 683 |
+
cls_token = outputs[1]
|
| 684 |
+
if self.config.cls_token[-1]:
|
| 685 |
+
sequence_output = self.layernorm(cls_token)
|
| 686 |
+
else:
|
| 687 |
+
batch_size, num_channels, height, width = sequence_output.shape
|
| 688 |
+
# rearrange "b c h w -> b (h w) c"
|
| 689 |
+
sequence_output = sequence_output.view(batch_size, num_channels, height * width).permute(0, 2, 1)
|
| 690 |
+
sequence_output = self.layernorm(sequence_output)
|
| 691 |
+
|
| 692 |
+
sequence_output_mean = sequence_output.mean(dim=1)
|
| 693 |
+
logits = self.classifier(sequence_output_mean)
|
| 694 |
+
|
| 695 |
+
loss = None
|
| 696 |
+
if labels is not None:
|
| 697 |
+
if self.config.problem_type is None:
|
| 698 |
+
if self.config.num_labels == 1:
|
| 699 |
+
self.config.problem_type = "regression"
|
| 700 |
+
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 701 |
+
self.config.problem_type = "single_label_classification"
|
| 702 |
+
else:
|
| 703 |
+
self.config.problem_type = "multi_label_classification"
|
| 704 |
+
|
| 705 |
+
if self.config.problem_type == "regression":
|
| 706 |
+
loss_fct = MSELoss()
|
| 707 |
+
if self.config.num_labels == 1:
|
| 708 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 709 |
+
else:
|
| 710 |
+
loss = loss_fct(logits, labels)
|
| 711 |
+
elif self.config.problem_type == "single_label_classification":
|
| 712 |
+
loss_fct = CrossEntropyLoss()
|
| 713 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
| 714 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 715 |
+
loss_fct = BCEWithLogitsLoss()
|
| 716 |
+
loss = loss_fct(logits, labels)
|
| 717 |
+
|
| 718 |
+
if not return_dict:
|
| 719 |
+
output = (logits,) + outputs[2:]
|
| 720 |
+
return ((loss,) + output) if loss is not None else output
|
| 721 |
+
|
| 722 |
+
return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
__all__ = ["CvtForImageClassification", "CvtModel", "CvtPreTrainedModel"]
|
lib/python3.12/site-packages/transformers/models/cvt/modeling_tf_cvt.py
ADDED
|
@@ -0,0 +1,1096 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TF 2.0 Cvt model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import collections.abc
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import tensorflow as tf
|
| 24 |
+
|
| 25 |
+
from ...modeling_tf_outputs import TFImageClassifierOutputWithNoAttention
|
| 26 |
+
from ...modeling_tf_utils import (
|
| 27 |
+
TFModelInputType,
|
| 28 |
+
TFPreTrainedModel,
|
| 29 |
+
TFSequenceClassificationLoss,
|
| 30 |
+
get_initializer,
|
| 31 |
+
keras,
|
| 32 |
+
keras_serializable,
|
| 33 |
+
unpack_inputs,
|
| 34 |
+
)
|
| 35 |
+
from ...tf_utils import shape_list, stable_softmax
|
| 36 |
+
from ...utils import (
|
| 37 |
+
ModelOutput,
|
| 38 |
+
add_start_docstrings,
|
| 39 |
+
add_start_docstrings_to_model_forward,
|
| 40 |
+
logging,
|
| 41 |
+
replace_return_docstrings,
|
| 42 |
+
)
|
| 43 |
+
from .configuration_cvt import CvtConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
# General docstring
|
| 49 |
+
_CONFIG_FOR_DOC = "CvtConfig"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class TFBaseModelOutputWithCLSToken(ModelOutput):
|
| 54 |
+
"""
|
| 55 |
+
Base class for model's outputs.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 59 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 60 |
+
cls_token_value (`tf.Tensor` of shape `(batch_size, 1, hidden_size)`):
|
| 61 |
+
Classification token at the output of the last layer of the model.
|
| 62 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 63 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 64 |
+
`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
|
| 65 |
+
the initial embedding outputs.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
last_hidden_state: Optional[tf.Tensor] = None
|
| 69 |
+
cls_token_value: Optional[tf.Tensor] = None
|
| 70 |
+
hidden_states: Tuple[tf.Tensor, ...] | None = None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TFCvtDropPath(keras.layers.Layer):
|
| 74 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 75 |
+
References:
|
| 76 |
+
(1) github.com:rwightman/pytorch-image-models
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def __init__(self, drop_prob: float, **kwargs):
|
| 80 |
+
super().__init__(**kwargs)
|
| 81 |
+
self.drop_prob = drop_prob
|
| 82 |
+
|
| 83 |
+
def call(self, x: tf.Tensor, training=None):
|
| 84 |
+
if self.drop_prob == 0.0 or not training:
|
| 85 |
+
return x
|
| 86 |
+
keep_prob = 1 - self.drop_prob
|
| 87 |
+
shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
|
| 88 |
+
random_tensor = keep_prob + tf.random.uniform(shape, 0, 1, dtype=self.compute_dtype)
|
| 89 |
+
random_tensor = tf.floor(random_tensor)
|
| 90 |
+
return (x / keep_prob) * random_tensor
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class TFCvtEmbeddings(keras.layers.Layer):
|
| 94 |
+
"""Construct the Convolutional Token Embeddings."""
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
config: CvtConfig,
|
| 99 |
+
patch_size: int,
|
| 100 |
+
num_channels: int,
|
| 101 |
+
embed_dim: int,
|
| 102 |
+
stride: int,
|
| 103 |
+
padding: int,
|
| 104 |
+
dropout_rate: float,
|
| 105 |
+
**kwargs,
|
| 106 |
+
):
|
| 107 |
+
super().__init__(**kwargs)
|
| 108 |
+
self.convolution_embeddings = TFCvtConvEmbeddings(
|
| 109 |
+
config,
|
| 110 |
+
patch_size=patch_size,
|
| 111 |
+
num_channels=num_channels,
|
| 112 |
+
embed_dim=embed_dim,
|
| 113 |
+
stride=stride,
|
| 114 |
+
padding=padding,
|
| 115 |
+
name="convolution_embeddings",
|
| 116 |
+
)
|
| 117 |
+
self.dropout = keras.layers.Dropout(dropout_rate)
|
| 118 |
+
|
| 119 |
+
def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 120 |
+
hidden_state = self.convolution_embeddings(pixel_values)
|
| 121 |
+
hidden_state = self.dropout(hidden_state, training=training)
|
| 122 |
+
return hidden_state
|
| 123 |
+
|
| 124 |
+
def build(self, input_shape=None):
|
| 125 |
+
if self.built:
|
| 126 |
+
return
|
| 127 |
+
self.built = True
|
| 128 |
+
if getattr(self, "convolution_embeddings", None) is not None:
|
| 129 |
+
with tf.name_scope(self.convolution_embeddings.name):
|
| 130 |
+
self.convolution_embeddings.build(None)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class TFCvtConvEmbeddings(keras.layers.Layer):
|
| 134 |
+
"""Image to Convolution Embeddings. This convolutional operation aims to model local spatial contexts."""
|
| 135 |
+
|
| 136 |
+
def __init__(
|
| 137 |
+
self,
|
| 138 |
+
config: CvtConfig,
|
| 139 |
+
patch_size: int,
|
| 140 |
+
num_channels: int,
|
| 141 |
+
embed_dim: int,
|
| 142 |
+
stride: int,
|
| 143 |
+
padding: int,
|
| 144 |
+
**kwargs,
|
| 145 |
+
):
|
| 146 |
+
super().__init__(**kwargs)
|
| 147 |
+
self.padding = keras.layers.ZeroPadding2D(padding=padding)
|
| 148 |
+
self.patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 149 |
+
self.projection = keras.layers.Conv2D(
|
| 150 |
+
filters=embed_dim,
|
| 151 |
+
kernel_size=patch_size,
|
| 152 |
+
strides=stride,
|
| 153 |
+
padding="valid",
|
| 154 |
+
data_format="channels_last",
|
| 155 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 156 |
+
name="projection",
|
| 157 |
+
)
|
| 158 |
+
# Using the same default epsilon as PyTorch
|
| 159 |
+
self.normalization = keras.layers.LayerNormalization(epsilon=1e-5, name="normalization")
|
| 160 |
+
self.num_channels = num_channels
|
| 161 |
+
self.embed_dim = embed_dim
|
| 162 |
+
|
| 163 |
+
def call(self, pixel_values: tf.Tensor) -> tf.Tensor:
|
| 164 |
+
if isinstance(pixel_values, dict):
|
| 165 |
+
pixel_values = pixel_values["pixel_values"]
|
| 166 |
+
|
| 167 |
+
pixel_values = self.projection(self.padding(pixel_values))
|
| 168 |
+
|
| 169 |
+
# "batch_size, height, width, num_channels -> batch_size, (height*width), num_channels"
|
| 170 |
+
batch_size, height, width, num_channels = shape_list(pixel_values)
|
| 171 |
+
hidden_size = height * width
|
| 172 |
+
pixel_values = tf.reshape(pixel_values, shape=(batch_size, hidden_size, num_channels))
|
| 173 |
+
pixel_values = self.normalization(pixel_values)
|
| 174 |
+
|
| 175 |
+
# "batch_size, (height*width), num_channels -> batch_size, height, width, num_channels"
|
| 176 |
+
pixel_values = tf.reshape(pixel_values, shape=(batch_size, height, width, num_channels))
|
| 177 |
+
return pixel_values
|
| 178 |
+
|
| 179 |
+
def build(self, input_shape=None):
|
| 180 |
+
if self.built:
|
| 181 |
+
return
|
| 182 |
+
self.built = True
|
| 183 |
+
if getattr(self, "projection", None) is not None:
|
| 184 |
+
with tf.name_scope(self.projection.name):
|
| 185 |
+
self.projection.build([None, None, None, self.num_channels])
|
| 186 |
+
if getattr(self, "normalization", None) is not None:
|
| 187 |
+
with tf.name_scope(self.normalization.name):
|
| 188 |
+
self.normalization.build([None, None, self.embed_dim])
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class TFCvtSelfAttentionConvProjection(keras.layers.Layer):
|
| 192 |
+
"""Convolutional projection layer."""
|
| 193 |
+
|
| 194 |
+
def __init__(self, config: CvtConfig, embed_dim: int, kernel_size: int, stride: int, padding: int, **kwargs):
|
| 195 |
+
super().__init__(**kwargs)
|
| 196 |
+
self.padding = keras.layers.ZeroPadding2D(padding=padding)
|
| 197 |
+
self.convolution = keras.layers.Conv2D(
|
| 198 |
+
filters=embed_dim,
|
| 199 |
+
kernel_size=kernel_size,
|
| 200 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 201 |
+
padding="valid",
|
| 202 |
+
strides=stride,
|
| 203 |
+
use_bias=False,
|
| 204 |
+
name="convolution",
|
| 205 |
+
groups=embed_dim,
|
| 206 |
+
)
|
| 207 |
+
# Using the same default epsilon as PyTorch, TF uses (1 - pytorch momentum)
|
| 208 |
+
self.normalization = keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.9, name="normalization")
|
| 209 |
+
self.embed_dim = embed_dim
|
| 210 |
+
|
| 211 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 212 |
+
hidden_state = self.convolution(self.padding(hidden_state))
|
| 213 |
+
hidden_state = self.normalization(hidden_state, training=training)
|
| 214 |
+
return hidden_state
|
| 215 |
+
|
| 216 |
+
def build(self, input_shape=None):
|
| 217 |
+
if self.built:
|
| 218 |
+
return
|
| 219 |
+
self.built = True
|
| 220 |
+
if getattr(self, "convolution", None) is not None:
|
| 221 |
+
with tf.name_scope(self.convolution.name):
|
| 222 |
+
self.convolution.build([None, None, None, self.embed_dim])
|
| 223 |
+
if getattr(self, "normalization", None) is not None:
|
| 224 |
+
with tf.name_scope(self.normalization.name):
|
| 225 |
+
self.normalization.build([None, None, None, self.embed_dim])
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class TFCvtSelfAttentionLinearProjection(keras.layers.Layer):
|
| 229 |
+
"""Linear projection layer used to flatten tokens into 1D."""
|
| 230 |
+
|
| 231 |
+
def call(self, hidden_state: tf.Tensor) -> tf.Tensor:
|
| 232 |
+
# "batch_size, height, width, num_channels -> batch_size, (height*width), num_channels"
|
| 233 |
+
batch_size, height, width, num_channels = shape_list(hidden_state)
|
| 234 |
+
hidden_size = height * width
|
| 235 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, hidden_size, num_channels))
|
| 236 |
+
return hidden_state
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class TFCvtSelfAttentionProjection(keras.layers.Layer):
|
| 240 |
+
"""Convolutional Projection for Attention."""
|
| 241 |
+
|
| 242 |
+
def __init__(
|
| 243 |
+
self,
|
| 244 |
+
config: CvtConfig,
|
| 245 |
+
embed_dim: int,
|
| 246 |
+
kernel_size: int,
|
| 247 |
+
stride: int,
|
| 248 |
+
padding: int,
|
| 249 |
+
projection_method: str = "dw_bn",
|
| 250 |
+
**kwargs,
|
| 251 |
+
):
|
| 252 |
+
super().__init__(**kwargs)
|
| 253 |
+
if projection_method == "dw_bn":
|
| 254 |
+
self.convolution_projection = TFCvtSelfAttentionConvProjection(
|
| 255 |
+
config, embed_dim, kernel_size, stride, padding, name="convolution_projection"
|
| 256 |
+
)
|
| 257 |
+
self.linear_projection = TFCvtSelfAttentionLinearProjection()
|
| 258 |
+
|
| 259 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 260 |
+
hidden_state = self.convolution_projection(hidden_state, training=training)
|
| 261 |
+
hidden_state = self.linear_projection(hidden_state)
|
| 262 |
+
return hidden_state
|
| 263 |
+
|
| 264 |
+
def build(self, input_shape=None):
|
| 265 |
+
if self.built:
|
| 266 |
+
return
|
| 267 |
+
self.built = True
|
| 268 |
+
if getattr(self, "convolution_projection", None) is not None:
|
| 269 |
+
with tf.name_scope(self.convolution_projection.name):
|
| 270 |
+
self.convolution_projection.build(None)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class TFCvtSelfAttention(keras.layers.Layer):
|
| 274 |
+
"""
|
| 275 |
+
Self-attention layer. A depth-wise separable convolution operation (Convolutional Projection), is applied for
|
| 276 |
+
query, key, and value embeddings.
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
def __init__(
|
| 280 |
+
self,
|
| 281 |
+
config: CvtConfig,
|
| 282 |
+
num_heads: int,
|
| 283 |
+
embed_dim: int,
|
| 284 |
+
kernel_size: int,
|
| 285 |
+
stride_q: int,
|
| 286 |
+
stride_kv: int,
|
| 287 |
+
padding_q: int,
|
| 288 |
+
padding_kv: int,
|
| 289 |
+
qkv_projection_method: str,
|
| 290 |
+
qkv_bias: bool,
|
| 291 |
+
attention_drop_rate: float,
|
| 292 |
+
with_cls_token: bool = True,
|
| 293 |
+
**kwargs,
|
| 294 |
+
):
|
| 295 |
+
super().__init__(**kwargs)
|
| 296 |
+
self.scale = embed_dim**-0.5
|
| 297 |
+
self.with_cls_token = with_cls_token
|
| 298 |
+
self.embed_dim = embed_dim
|
| 299 |
+
self.num_heads = num_heads
|
| 300 |
+
|
| 301 |
+
self.convolution_projection_query = TFCvtSelfAttentionProjection(
|
| 302 |
+
config,
|
| 303 |
+
embed_dim,
|
| 304 |
+
kernel_size,
|
| 305 |
+
stride_q,
|
| 306 |
+
padding_q,
|
| 307 |
+
projection_method="linear" if qkv_projection_method == "avg" else qkv_projection_method,
|
| 308 |
+
name="convolution_projection_query",
|
| 309 |
+
)
|
| 310 |
+
self.convolution_projection_key = TFCvtSelfAttentionProjection(
|
| 311 |
+
config,
|
| 312 |
+
embed_dim,
|
| 313 |
+
kernel_size,
|
| 314 |
+
stride_kv,
|
| 315 |
+
padding_kv,
|
| 316 |
+
projection_method=qkv_projection_method,
|
| 317 |
+
name="convolution_projection_key",
|
| 318 |
+
)
|
| 319 |
+
self.convolution_projection_value = TFCvtSelfAttentionProjection(
|
| 320 |
+
config,
|
| 321 |
+
embed_dim,
|
| 322 |
+
kernel_size,
|
| 323 |
+
stride_kv,
|
| 324 |
+
padding_kv,
|
| 325 |
+
projection_method=qkv_projection_method,
|
| 326 |
+
name="convolution_projection_value",
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
self.projection_query = keras.layers.Dense(
|
| 330 |
+
units=embed_dim,
|
| 331 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 332 |
+
use_bias=qkv_bias,
|
| 333 |
+
bias_initializer="zeros",
|
| 334 |
+
name="projection_query",
|
| 335 |
+
)
|
| 336 |
+
self.projection_key = keras.layers.Dense(
|
| 337 |
+
units=embed_dim,
|
| 338 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 339 |
+
use_bias=qkv_bias,
|
| 340 |
+
bias_initializer="zeros",
|
| 341 |
+
name="projection_key",
|
| 342 |
+
)
|
| 343 |
+
self.projection_value = keras.layers.Dense(
|
| 344 |
+
units=embed_dim,
|
| 345 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 346 |
+
use_bias=qkv_bias,
|
| 347 |
+
bias_initializer="zeros",
|
| 348 |
+
name="projection_value",
|
| 349 |
+
)
|
| 350 |
+
self.dropout = keras.layers.Dropout(attention_drop_rate)
|
| 351 |
+
|
| 352 |
+
def rearrange_for_multi_head_attention(self, hidden_state: tf.Tensor) -> tf.Tensor:
|
| 353 |
+
batch_size, hidden_size, _ = shape_list(hidden_state)
|
| 354 |
+
head_dim = self.embed_dim // self.num_heads
|
| 355 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, hidden_size, self.num_heads, head_dim))
|
| 356 |
+
hidden_state = tf.transpose(hidden_state, perm=(0, 2, 1, 3))
|
| 357 |
+
return hidden_state
|
| 358 |
+
|
| 359 |
+
def call(self, hidden_state: tf.Tensor, height: int, width: int, training: bool = False) -> tf.Tensor:
|
| 360 |
+
if self.with_cls_token:
|
| 361 |
+
cls_token, hidden_state = tf.split(hidden_state, [1, height * width], 1)
|
| 362 |
+
|
| 363 |
+
# "batch_size, (height*width), num_channels -> batch_size, height, width, num_channels"
|
| 364 |
+
batch_size, hidden_size, num_channels = shape_list(hidden_state)
|
| 365 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, height, width, num_channels))
|
| 366 |
+
|
| 367 |
+
key = self.convolution_projection_key(hidden_state, training=training)
|
| 368 |
+
query = self.convolution_projection_query(hidden_state, training=training)
|
| 369 |
+
value = self.convolution_projection_value(hidden_state, training=training)
|
| 370 |
+
|
| 371 |
+
if self.with_cls_token:
|
| 372 |
+
query = tf.concat((cls_token, query), axis=1)
|
| 373 |
+
key = tf.concat((cls_token, key), axis=1)
|
| 374 |
+
value = tf.concat((cls_token, value), axis=1)
|
| 375 |
+
|
| 376 |
+
head_dim = self.embed_dim // self.num_heads
|
| 377 |
+
|
| 378 |
+
query = self.rearrange_for_multi_head_attention(self.projection_query(query))
|
| 379 |
+
key = self.rearrange_for_multi_head_attention(self.projection_key(key))
|
| 380 |
+
value = self.rearrange_for_multi_head_attention(self.projection_value(value))
|
| 381 |
+
|
| 382 |
+
attention_score = tf.matmul(query, key, transpose_b=True) * self.scale
|
| 383 |
+
attention_probs = stable_softmax(logits=attention_score, axis=-1)
|
| 384 |
+
attention_probs = self.dropout(attention_probs, training=training)
|
| 385 |
+
|
| 386 |
+
context = tf.matmul(attention_probs, value)
|
| 387 |
+
# "batch_size, num_heads, hidden_size, head_dim -> batch_size, hidden_size, (num_heads*head_dim)"
|
| 388 |
+
_, _, hidden_size, _ = shape_list(context)
|
| 389 |
+
context = tf.transpose(context, perm=(0, 2, 1, 3))
|
| 390 |
+
context = tf.reshape(context, (batch_size, hidden_size, self.num_heads * head_dim))
|
| 391 |
+
return context
|
| 392 |
+
|
| 393 |
+
def build(self, input_shape=None):
|
| 394 |
+
if self.built:
|
| 395 |
+
return
|
| 396 |
+
self.built = True
|
| 397 |
+
if getattr(self, "convolution_projection_query", None) is not None:
|
| 398 |
+
with tf.name_scope(self.convolution_projection_query.name):
|
| 399 |
+
self.convolution_projection_query.build(None)
|
| 400 |
+
if getattr(self, "convolution_projection_key", None) is not None:
|
| 401 |
+
with tf.name_scope(self.convolution_projection_key.name):
|
| 402 |
+
self.convolution_projection_key.build(None)
|
| 403 |
+
if getattr(self, "convolution_projection_value", None) is not None:
|
| 404 |
+
with tf.name_scope(self.convolution_projection_value.name):
|
| 405 |
+
self.convolution_projection_value.build(None)
|
| 406 |
+
if getattr(self, "projection_query", None) is not None:
|
| 407 |
+
with tf.name_scope(self.projection_query.name):
|
| 408 |
+
self.projection_query.build([None, None, self.embed_dim])
|
| 409 |
+
if getattr(self, "projection_key", None) is not None:
|
| 410 |
+
with tf.name_scope(self.projection_key.name):
|
| 411 |
+
self.projection_key.build([None, None, self.embed_dim])
|
| 412 |
+
if getattr(self, "projection_value", None) is not None:
|
| 413 |
+
with tf.name_scope(self.projection_value.name):
|
| 414 |
+
self.projection_value.build([None, None, self.embed_dim])
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class TFCvtSelfOutput(keras.layers.Layer):
|
| 418 |
+
"""Output of the Attention layer ."""
|
| 419 |
+
|
| 420 |
+
def __init__(self, config: CvtConfig, embed_dim: int, drop_rate: float, **kwargs):
|
| 421 |
+
super().__init__(**kwargs)
|
| 422 |
+
self.dense = keras.layers.Dense(
|
| 423 |
+
units=embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 424 |
+
)
|
| 425 |
+
self.dropout = keras.layers.Dropout(drop_rate)
|
| 426 |
+
self.embed_dim = embed_dim
|
| 427 |
+
|
| 428 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 429 |
+
hidden_state = self.dense(inputs=hidden_state)
|
| 430 |
+
hidden_state = self.dropout(inputs=hidden_state, training=training)
|
| 431 |
+
return hidden_state
|
| 432 |
+
|
| 433 |
+
def build(self, input_shape=None):
|
| 434 |
+
if self.built:
|
| 435 |
+
return
|
| 436 |
+
self.built = True
|
| 437 |
+
if getattr(self, "dense", None) is not None:
|
| 438 |
+
with tf.name_scope(self.dense.name):
|
| 439 |
+
self.dense.build([None, None, self.embed_dim])
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class TFCvtAttention(keras.layers.Layer):
|
| 443 |
+
"""Attention layer. First chunk of the convolutional transformer block."""
|
| 444 |
+
|
| 445 |
+
def __init__(
|
| 446 |
+
self,
|
| 447 |
+
config: CvtConfig,
|
| 448 |
+
num_heads: int,
|
| 449 |
+
embed_dim: int,
|
| 450 |
+
kernel_size: int,
|
| 451 |
+
stride_q: int,
|
| 452 |
+
stride_kv: int,
|
| 453 |
+
padding_q: int,
|
| 454 |
+
padding_kv: int,
|
| 455 |
+
qkv_projection_method: str,
|
| 456 |
+
qkv_bias: bool,
|
| 457 |
+
attention_drop_rate: float,
|
| 458 |
+
drop_rate: float,
|
| 459 |
+
with_cls_token: bool = True,
|
| 460 |
+
**kwargs,
|
| 461 |
+
):
|
| 462 |
+
super().__init__(**kwargs)
|
| 463 |
+
self.attention = TFCvtSelfAttention(
|
| 464 |
+
config,
|
| 465 |
+
num_heads,
|
| 466 |
+
embed_dim,
|
| 467 |
+
kernel_size,
|
| 468 |
+
stride_q,
|
| 469 |
+
stride_kv,
|
| 470 |
+
padding_q,
|
| 471 |
+
padding_kv,
|
| 472 |
+
qkv_projection_method,
|
| 473 |
+
qkv_bias,
|
| 474 |
+
attention_drop_rate,
|
| 475 |
+
with_cls_token,
|
| 476 |
+
name="attention",
|
| 477 |
+
)
|
| 478 |
+
self.dense_output = TFCvtSelfOutput(config, embed_dim, drop_rate, name="output")
|
| 479 |
+
|
| 480 |
+
def prune_heads(self, heads):
|
| 481 |
+
raise NotImplementedError
|
| 482 |
+
|
| 483 |
+
def call(self, hidden_state: tf.Tensor, height: int, width: int, training: bool = False):
|
| 484 |
+
self_output = self.attention(hidden_state, height, width, training=training)
|
| 485 |
+
attention_output = self.dense_output(self_output, training=training)
|
| 486 |
+
return attention_output
|
| 487 |
+
|
| 488 |
+
def build(self, input_shape=None):
|
| 489 |
+
if self.built:
|
| 490 |
+
return
|
| 491 |
+
self.built = True
|
| 492 |
+
if getattr(self, "attention", None) is not None:
|
| 493 |
+
with tf.name_scope(self.attention.name):
|
| 494 |
+
self.attention.build(None)
|
| 495 |
+
if getattr(self, "dense_output", None) is not None:
|
| 496 |
+
with tf.name_scope(self.dense_output.name):
|
| 497 |
+
self.dense_output.build(None)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
class TFCvtIntermediate(keras.layers.Layer):
|
| 501 |
+
"""Intermediate dense layer. Second chunk of the convolutional transformer block."""
|
| 502 |
+
|
| 503 |
+
def __init__(self, config: CvtConfig, embed_dim: int, mlp_ratio: int, **kwargs):
|
| 504 |
+
super().__init__(**kwargs)
|
| 505 |
+
self.dense = keras.layers.Dense(
|
| 506 |
+
units=int(embed_dim * mlp_ratio),
|
| 507 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 508 |
+
activation="gelu",
|
| 509 |
+
name="dense",
|
| 510 |
+
)
|
| 511 |
+
self.embed_dim = embed_dim
|
| 512 |
+
|
| 513 |
+
def call(self, hidden_state: tf.Tensor) -> tf.Tensor:
|
| 514 |
+
hidden_state = self.dense(hidden_state)
|
| 515 |
+
return hidden_state
|
| 516 |
+
|
| 517 |
+
def build(self, input_shape=None):
|
| 518 |
+
if self.built:
|
| 519 |
+
return
|
| 520 |
+
self.built = True
|
| 521 |
+
if getattr(self, "dense", None) is not None:
|
| 522 |
+
with tf.name_scope(self.dense.name):
|
| 523 |
+
self.dense.build([None, None, self.embed_dim])
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class TFCvtOutput(keras.layers.Layer):
|
| 527 |
+
"""
|
| 528 |
+
Output of the Convolutional Transformer Block (last chunk). It consists of a MLP and a residual connection.
|
| 529 |
+
"""
|
| 530 |
+
|
| 531 |
+
def __init__(self, config: CvtConfig, embed_dim: int, mlp_ratio: int, drop_rate: int, **kwargs):
|
| 532 |
+
super().__init__(**kwargs)
|
| 533 |
+
self.dense = keras.layers.Dense(
|
| 534 |
+
units=embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 535 |
+
)
|
| 536 |
+
self.dropout = keras.layers.Dropout(drop_rate)
|
| 537 |
+
self.embed_dim = embed_dim
|
| 538 |
+
self.mlp_ratio = mlp_ratio
|
| 539 |
+
|
| 540 |
+
def call(self, hidden_state: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 541 |
+
hidden_state = self.dense(inputs=hidden_state)
|
| 542 |
+
hidden_state = self.dropout(inputs=hidden_state, training=training)
|
| 543 |
+
hidden_state = hidden_state + input_tensor
|
| 544 |
+
return hidden_state
|
| 545 |
+
|
| 546 |
+
def build(self, input_shape=None):
|
| 547 |
+
if self.built:
|
| 548 |
+
return
|
| 549 |
+
self.built = True
|
| 550 |
+
if getattr(self, "dense", None) is not None:
|
| 551 |
+
with tf.name_scope(self.dense.name):
|
| 552 |
+
self.dense.build([None, None, int(self.embed_dim * self.mlp_ratio)])
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
class TFCvtLayer(keras.layers.Layer):
|
| 556 |
+
"""
|
| 557 |
+
Convolutional Transformer Block composed by attention layers, normalization and multi-layer perceptrons (mlps). It
|
| 558 |
+
consists of 3 chunks : an attention layer, an intermediate dense layer and an output layer. This corresponds to the
|
| 559 |
+
`Block` class in the original implementation.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
def __init__(
|
| 563 |
+
self,
|
| 564 |
+
config: CvtConfig,
|
| 565 |
+
num_heads: int,
|
| 566 |
+
embed_dim: int,
|
| 567 |
+
kernel_size: int,
|
| 568 |
+
stride_q: int,
|
| 569 |
+
stride_kv: int,
|
| 570 |
+
padding_q: int,
|
| 571 |
+
padding_kv: int,
|
| 572 |
+
qkv_projection_method: str,
|
| 573 |
+
qkv_bias: bool,
|
| 574 |
+
attention_drop_rate: float,
|
| 575 |
+
drop_rate: float,
|
| 576 |
+
mlp_ratio: float,
|
| 577 |
+
drop_path_rate: float,
|
| 578 |
+
with_cls_token: bool = True,
|
| 579 |
+
**kwargs,
|
| 580 |
+
):
|
| 581 |
+
super().__init__(**kwargs)
|
| 582 |
+
self.attention = TFCvtAttention(
|
| 583 |
+
config,
|
| 584 |
+
num_heads,
|
| 585 |
+
embed_dim,
|
| 586 |
+
kernel_size,
|
| 587 |
+
stride_q,
|
| 588 |
+
stride_kv,
|
| 589 |
+
padding_q,
|
| 590 |
+
padding_kv,
|
| 591 |
+
qkv_projection_method,
|
| 592 |
+
qkv_bias,
|
| 593 |
+
attention_drop_rate,
|
| 594 |
+
drop_rate,
|
| 595 |
+
with_cls_token,
|
| 596 |
+
name="attention",
|
| 597 |
+
)
|
| 598 |
+
self.intermediate = TFCvtIntermediate(config, embed_dim, mlp_ratio, name="intermediate")
|
| 599 |
+
self.dense_output = TFCvtOutput(config, embed_dim, mlp_ratio, drop_rate, name="output")
|
| 600 |
+
# Using `layers.Activation` instead of `tf.identity` to better control `training` behaviour.
|
| 601 |
+
self.drop_path = (
|
| 602 |
+
TFCvtDropPath(drop_path_rate, name="drop_path")
|
| 603 |
+
if drop_path_rate > 0.0
|
| 604 |
+
else keras.layers.Activation("linear", name="drop_path")
|
| 605 |
+
)
|
| 606 |
+
# Using the same default epsilon as PyTorch
|
| 607 |
+
self.layernorm_before = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_before")
|
| 608 |
+
self.layernorm_after = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_after")
|
| 609 |
+
self.embed_dim = embed_dim
|
| 610 |
+
|
| 611 |
+
def call(self, hidden_state: tf.Tensor, height: int, width: int, training: bool = False) -> tf.Tensor:
|
| 612 |
+
# in Cvt, layernorm is applied before self-attention
|
| 613 |
+
attention_output = self.attention(self.layernorm_before(hidden_state), height, width, training=training)
|
| 614 |
+
attention_output = self.drop_path(attention_output, training=training)
|
| 615 |
+
|
| 616 |
+
# first residual connection
|
| 617 |
+
hidden_state = attention_output + hidden_state
|
| 618 |
+
|
| 619 |
+
# in Cvt, layernorm is also applied after self-attention
|
| 620 |
+
layer_output = self.layernorm_after(hidden_state)
|
| 621 |
+
layer_output = self.intermediate(layer_output)
|
| 622 |
+
|
| 623 |
+
# second residual connection is done here
|
| 624 |
+
layer_output = self.dense_output(layer_output, hidden_state)
|
| 625 |
+
layer_output = self.drop_path(layer_output, training=training)
|
| 626 |
+
return layer_output
|
| 627 |
+
|
| 628 |
+
def build(self, input_shape=None):
|
| 629 |
+
if self.built:
|
| 630 |
+
return
|
| 631 |
+
self.built = True
|
| 632 |
+
if getattr(self, "attention", None) is not None:
|
| 633 |
+
with tf.name_scope(self.attention.name):
|
| 634 |
+
self.attention.build(None)
|
| 635 |
+
if getattr(self, "intermediate", None) is not None:
|
| 636 |
+
with tf.name_scope(self.intermediate.name):
|
| 637 |
+
self.intermediate.build(None)
|
| 638 |
+
if getattr(self, "dense_output", None) is not None:
|
| 639 |
+
with tf.name_scope(self.dense_output.name):
|
| 640 |
+
self.dense_output.build(None)
|
| 641 |
+
if getattr(self, "drop_path", None) is not None:
|
| 642 |
+
with tf.name_scope(self.drop_path.name):
|
| 643 |
+
self.drop_path.build(None)
|
| 644 |
+
if getattr(self, "layernorm_before", None) is not None:
|
| 645 |
+
with tf.name_scope(self.layernorm_before.name):
|
| 646 |
+
self.layernorm_before.build([None, None, self.embed_dim])
|
| 647 |
+
if getattr(self, "layernorm_after", None) is not None:
|
| 648 |
+
with tf.name_scope(self.layernorm_after.name):
|
| 649 |
+
self.layernorm_after.build([None, None, self.embed_dim])
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
class TFCvtStage(keras.layers.Layer):
|
| 653 |
+
"""
|
| 654 |
+
Cvt stage (encoder block). Each stage has 2 parts :
|
| 655 |
+
- (1) A Convolutional Token Embedding layer
|
| 656 |
+
- (2) A Convolutional Transformer Block (layer).
|
| 657 |
+
The classification token is added only in the last stage.
|
| 658 |
+
|
| 659 |
+
Args:
|
| 660 |
+
config ([`CvtConfig`]): Model configuration class.
|
| 661 |
+
stage (`int`): Stage number.
|
| 662 |
+
"""
|
| 663 |
+
|
| 664 |
+
def __init__(self, config: CvtConfig, stage: int, **kwargs):
|
| 665 |
+
super().__init__(**kwargs)
|
| 666 |
+
self.config = config
|
| 667 |
+
self.stage = stage
|
| 668 |
+
if self.config.cls_token[self.stage]:
|
| 669 |
+
self.cls_token = self.add_weight(
|
| 670 |
+
shape=(1, 1, self.config.embed_dim[-1]),
|
| 671 |
+
initializer=get_initializer(self.config.initializer_range),
|
| 672 |
+
trainable=True,
|
| 673 |
+
name="cvt.encoder.stages.2.cls_token",
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
self.embedding = TFCvtEmbeddings(
|
| 677 |
+
self.config,
|
| 678 |
+
patch_size=config.patch_sizes[self.stage],
|
| 679 |
+
num_channels=config.num_channels if self.stage == 0 else config.embed_dim[self.stage - 1],
|
| 680 |
+
stride=config.patch_stride[self.stage],
|
| 681 |
+
embed_dim=config.embed_dim[self.stage],
|
| 682 |
+
padding=config.patch_padding[self.stage],
|
| 683 |
+
dropout_rate=config.drop_rate[self.stage],
|
| 684 |
+
name="embedding",
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
drop_path_rates = tf.linspace(0.0, config.drop_path_rate[self.stage], config.depth[stage])
|
| 688 |
+
drop_path_rates = [x.numpy().item() for x in drop_path_rates]
|
| 689 |
+
self.layers = [
|
| 690 |
+
TFCvtLayer(
|
| 691 |
+
config,
|
| 692 |
+
num_heads=config.num_heads[self.stage],
|
| 693 |
+
embed_dim=config.embed_dim[self.stage],
|
| 694 |
+
kernel_size=config.kernel_qkv[self.stage],
|
| 695 |
+
stride_q=config.stride_q[self.stage],
|
| 696 |
+
stride_kv=config.stride_kv[self.stage],
|
| 697 |
+
padding_q=config.padding_q[self.stage],
|
| 698 |
+
padding_kv=config.padding_kv[self.stage],
|
| 699 |
+
qkv_projection_method=config.qkv_projection_method[self.stage],
|
| 700 |
+
qkv_bias=config.qkv_bias[self.stage],
|
| 701 |
+
attention_drop_rate=config.attention_drop_rate[self.stage],
|
| 702 |
+
drop_rate=config.drop_rate[self.stage],
|
| 703 |
+
mlp_ratio=config.mlp_ratio[self.stage],
|
| 704 |
+
drop_path_rate=drop_path_rates[self.stage],
|
| 705 |
+
with_cls_token=config.cls_token[self.stage],
|
| 706 |
+
name=f"layers.{j}",
|
| 707 |
+
)
|
| 708 |
+
for j in range(config.depth[self.stage])
|
| 709 |
+
]
|
| 710 |
+
|
| 711 |
+
def call(self, hidden_state: tf.Tensor, training: bool = False):
|
| 712 |
+
cls_token = None
|
| 713 |
+
hidden_state = self.embedding(hidden_state, training)
|
| 714 |
+
|
| 715 |
+
# "batch_size, height, width, num_channels -> batch_size, (height*width), num_channels"
|
| 716 |
+
batch_size, height, width, num_channels = shape_list(hidden_state)
|
| 717 |
+
hidden_size = height * width
|
| 718 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, hidden_size, num_channels))
|
| 719 |
+
|
| 720 |
+
if self.config.cls_token[self.stage]:
|
| 721 |
+
cls_token = tf.repeat(self.cls_token, repeats=batch_size, axis=0)
|
| 722 |
+
hidden_state = tf.concat((cls_token, hidden_state), axis=1)
|
| 723 |
+
|
| 724 |
+
for layer in self.layers:
|
| 725 |
+
layer_outputs = layer(hidden_state, height, width, training=training)
|
| 726 |
+
hidden_state = layer_outputs
|
| 727 |
+
|
| 728 |
+
if self.config.cls_token[self.stage]:
|
| 729 |
+
cls_token, hidden_state = tf.split(hidden_state, [1, height * width], 1)
|
| 730 |
+
|
| 731 |
+
# "batch_size, (height*width), num_channels -> batch_size, height, width, num_channels"
|
| 732 |
+
hidden_state = tf.reshape(hidden_state, shape=(batch_size, height, width, num_channels))
|
| 733 |
+
return hidden_state, cls_token
|
| 734 |
+
|
| 735 |
+
def build(self, input_shape=None):
|
| 736 |
+
if self.built:
|
| 737 |
+
return
|
| 738 |
+
self.built = True
|
| 739 |
+
if getattr(self, "embedding", None) is not None:
|
| 740 |
+
with tf.name_scope(self.embedding.name):
|
| 741 |
+
self.embedding.build(None)
|
| 742 |
+
if getattr(self, "layers", None) is not None:
|
| 743 |
+
for layer in self.layers:
|
| 744 |
+
with tf.name_scope(layer.name):
|
| 745 |
+
layer.build(None)
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class TFCvtEncoder(keras.layers.Layer):
|
| 749 |
+
"""
|
| 750 |
+
Convolutional Vision Transformer encoder. CVT has 3 stages of encoder blocks with their respective number of layers
|
| 751 |
+
(depth) being 1, 2 and 10.
|
| 752 |
+
|
| 753 |
+
Args:
|
| 754 |
+
config ([`CvtConfig`]): Model configuration class.
|
| 755 |
+
"""
|
| 756 |
+
|
| 757 |
+
config_class = CvtConfig
|
| 758 |
+
|
| 759 |
+
def __init__(self, config: CvtConfig, **kwargs):
|
| 760 |
+
super().__init__(**kwargs)
|
| 761 |
+
self.config = config
|
| 762 |
+
self.stages = [
|
| 763 |
+
TFCvtStage(config, stage_idx, name=f"stages.{stage_idx}") for stage_idx in range(len(config.depth))
|
| 764 |
+
]
|
| 765 |
+
|
| 766 |
+
def call(
|
| 767 |
+
self,
|
| 768 |
+
pixel_values: TFModelInputType,
|
| 769 |
+
output_hidden_states: Optional[bool] = False,
|
| 770 |
+
return_dict: Optional[bool] = True,
|
| 771 |
+
training: Optional[bool] = False,
|
| 772 |
+
) -> Union[TFBaseModelOutputWithCLSToken, Tuple[tf.Tensor]]:
|
| 773 |
+
all_hidden_states = () if output_hidden_states else None
|
| 774 |
+
hidden_state = pixel_values
|
| 775 |
+
# When running on CPU, `keras.layers.Conv2D` doesn't support (batch_size, num_channels, height, width)
|
| 776 |
+
# as input format. So change the input format to (batch_size, height, width, num_channels).
|
| 777 |
+
hidden_state = tf.transpose(hidden_state, perm=(0, 2, 3, 1))
|
| 778 |
+
|
| 779 |
+
cls_token = None
|
| 780 |
+
for _, (stage_module) in enumerate(self.stages):
|
| 781 |
+
hidden_state, cls_token = stage_module(hidden_state, training=training)
|
| 782 |
+
if output_hidden_states:
|
| 783 |
+
all_hidden_states = all_hidden_states + (hidden_state,)
|
| 784 |
+
|
| 785 |
+
# Change back to (batch_size, num_channels, height, width) format to have uniformity in the modules
|
| 786 |
+
hidden_state = tf.transpose(hidden_state, perm=(0, 3, 1, 2))
|
| 787 |
+
if output_hidden_states:
|
| 788 |
+
all_hidden_states = tuple([tf.transpose(hs, perm=(0, 3, 1, 2)) for hs in all_hidden_states])
|
| 789 |
+
|
| 790 |
+
if not return_dict:
|
| 791 |
+
return tuple(v for v in [hidden_state, cls_token, all_hidden_states] if v is not None)
|
| 792 |
+
|
| 793 |
+
return TFBaseModelOutputWithCLSToken(
|
| 794 |
+
last_hidden_state=hidden_state,
|
| 795 |
+
cls_token_value=cls_token,
|
| 796 |
+
hidden_states=all_hidden_states,
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
def build(self, input_shape=None):
|
| 800 |
+
if self.built:
|
| 801 |
+
return
|
| 802 |
+
self.built = True
|
| 803 |
+
if getattr(self, "stages", None) is not None:
|
| 804 |
+
for layer in self.stages:
|
| 805 |
+
with tf.name_scope(layer.name):
|
| 806 |
+
layer.build(None)
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
@keras_serializable
|
| 810 |
+
class TFCvtMainLayer(keras.layers.Layer):
|
| 811 |
+
"""Construct the Cvt model."""
|
| 812 |
+
|
| 813 |
+
config_class = CvtConfig
|
| 814 |
+
|
| 815 |
+
def __init__(self, config: CvtConfig, **kwargs):
|
| 816 |
+
super().__init__(**kwargs)
|
| 817 |
+
self.config = config
|
| 818 |
+
self.encoder = TFCvtEncoder(config, name="encoder")
|
| 819 |
+
|
| 820 |
+
@unpack_inputs
|
| 821 |
+
def call(
|
| 822 |
+
self,
|
| 823 |
+
pixel_values: TFModelInputType | None = None,
|
| 824 |
+
output_hidden_states: Optional[bool] = None,
|
| 825 |
+
return_dict: Optional[bool] = None,
|
| 826 |
+
training: Optional[bool] = False,
|
| 827 |
+
) -> Union[TFBaseModelOutputWithCLSToken, Tuple[tf.Tensor]]:
|
| 828 |
+
if pixel_values is None:
|
| 829 |
+
raise ValueError("You have to specify pixel_values")
|
| 830 |
+
|
| 831 |
+
encoder_outputs = self.encoder(
|
| 832 |
+
pixel_values,
|
| 833 |
+
output_hidden_states=output_hidden_states,
|
| 834 |
+
return_dict=return_dict,
|
| 835 |
+
training=training,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
sequence_output = encoder_outputs[0]
|
| 839 |
+
|
| 840 |
+
if not return_dict:
|
| 841 |
+
return (sequence_output,) + encoder_outputs[1:]
|
| 842 |
+
|
| 843 |
+
return TFBaseModelOutputWithCLSToken(
|
| 844 |
+
last_hidden_state=sequence_output,
|
| 845 |
+
cls_token_value=encoder_outputs.cls_token_value,
|
| 846 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
def build(self, input_shape=None):
|
| 850 |
+
if self.built:
|
| 851 |
+
return
|
| 852 |
+
self.built = True
|
| 853 |
+
if getattr(self, "encoder", None) is not None:
|
| 854 |
+
with tf.name_scope(self.encoder.name):
|
| 855 |
+
self.encoder.build(None)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
class TFCvtPreTrainedModel(TFPreTrainedModel):
|
| 859 |
+
"""
|
| 860 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 861 |
+
models.
|
| 862 |
+
"""
|
| 863 |
+
|
| 864 |
+
config_class = CvtConfig
|
| 865 |
+
base_model_prefix = "cvt"
|
| 866 |
+
main_input_name = "pixel_values"
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
TFCVT_START_DOCSTRING = r"""
|
| 870 |
+
|
| 871 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 872 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 873 |
+
etc.)
|
| 874 |
+
|
| 875 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 876 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 877 |
+
behavior.
|
| 878 |
+
|
| 879 |
+
<Tip>
|
| 880 |
+
|
| 881 |
+
TF 2.0 models accepts two formats as inputs:
|
| 882 |
+
|
| 883 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 884 |
+
- having all inputs as a list, tuple or dict in the first positional arguments.
|
| 885 |
+
|
| 886 |
+
This second option is useful when using [`keras.Model.fit`] method which currently requires having all the
|
| 887 |
+
tensors in the first argument of the model call function: `model(inputs)`.
|
| 888 |
+
|
| 889 |
+
</Tip>
|
| 890 |
+
|
| 891 |
+
Args:
|
| 892 |
+
config ([`CvtConfig`]): Model configuration class with all the parameters of the model.
|
| 893 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 894 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 895 |
+
"""
|
| 896 |
+
|
| 897 |
+
TFCVT_INPUTS_DOCSTRING = r"""
|
| 898 |
+
Args:
|
| 899 |
+
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)`):
|
| 900 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`CvtImageProcessor.__call__`]
|
| 901 |
+
for details.
|
| 902 |
+
|
| 903 |
+
output_hidden_states (`bool`, *optional*):
|
| 904 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 905 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 906 |
+
used instead.
|
| 907 |
+
return_dict (`bool`, *optional*):
|
| 908 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 909 |
+
eager mode, in graph mode the value will always be set to True.
|
| 910 |
+
training (`bool`, *optional*, defaults to `False``):
|
| 911 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 912 |
+
behaviors between training and evaluation).
|
| 913 |
+
"""
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
@add_start_docstrings(
|
| 917 |
+
"The bare Cvt Model transformer outputting raw hidden-states without any specific head on top.",
|
| 918 |
+
TFCVT_START_DOCSTRING,
|
| 919 |
+
)
|
| 920 |
+
class TFCvtModel(TFCvtPreTrainedModel):
|
| 921 |
+
def __init__(self, config: CvtConfig, *inputs, **kwargs):
|
| 922 |
+
super().__init__(config, *inputs, **kwargs)
|
| 923 |
+
|
| 924 |
+
self.cvt = TFCvtMainLayer(config, name="cvt")
|
| 925 |
+
|
| 926 |
+
@unpack_inputs
|
| 927 |
+
@add_start_docstrings_to_model_forward(TFCVT_INPUTS_DOCSTRING)
|
| 928 |
+
@replace_return_docstrings(output_type=TFBaseModelOutputWithCLSToken, config_class=_CONFIG_FOR_DOC)
|
| 929 |
+
def call(
|
| 930 |
+
self,
|
| 931 |
+
pixel_values: tf.Tensor | None = None,
|
| 932 |
+
output_hidden_states: Optional[bool] = None,
|
| 933 |
+
return_dict: Optional[bool] = None,
|
| 934 |
+
training: Optional[bool] = False,
|
| 935 |
+
) -> Union[TFBaseModelOutputWithCLSToken, Tuple[tf.Tensor]]:
|
| 936 |
+
r"""
|
| 937 |
+
Returns:
|
| 938 |
+
|
| 939 |
+
Examples:
|
| 940 |
+
|
| 941 |
+
```python
|
| 942 |
+
>>> from transformers import AutoImageProcessor, TFCvtModel
|
| 943 |
+
>>> from PIL import Image
|
| 944 |
+
>>> import requests
|
| 945 |
+
|
| 946 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 947 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 948 |
+
|
| 949 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/cvt-13")
|
| 950 |
+
>>> model = TFCvtModel.from_pretrained("microsoft/cvt-13")
|
| 951 |
+
|
| 952 |
+
>>> inputs = image_processor(images=image, return_tensors="tf")
|
| 953 |
+
>>> outputs = model(**inputs)
|
| 954 |
+
>>> last_hidden_states = outputs.last_hidden_state
|
| 955 |
+
```"""
|
| 956 |
+
|
| 957 |
+
if pixel_values is None:
|
| 958 |
+
raise ValueError("You have to specify pixel_values")
|
| 959 |
+
|
| 960 |
+
outputs = self.cvt(
|
| 961 |
+
pixel_values=pixel_values,
|
| 962 |
+
output_hidden_states=output_hidden_states,
|
| 963 |
+
return_dict=return_dict,
|
| 964 |
+
training=training,
|
| 965 |
+
)
|
| 966 |
+
|
| 967 |
+
if not return_dict:
|
| 968 |
+
return (outputs[0],) + outputs[1:]
|
| 969 |
+
|
| 970 |
+
return TFBaseModelOutputWithCLSToken(
|
| 971 |
+
last_hidden_state=outputs.last_hidden_state,
|
| 972 |
+
cls_token_value=outputs.cls_token_value,
|
| 973 |
+
hidden_states=outputs.hidden_states,
|
| 974 |
+
)
|
| 975 |
+
|
| 976 |
+
def build(self, input_shape=None):
|
| 977 |
+
if self.built:
|
| 978 |
+
return
|
| 979 |
+
self.built = True
|
| 980 |
+
if getattr(self, "cvt", None) is not None:
|
| 981 |
+
with tf.name_scope(self.cvt.name):
|
| 982 |
+
self.cvt.build(None)
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
@add_start_docstrings(
|
| 986 |
+
"""
|
| 987 |
+
Cvt Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
| 988 |
+
the [CLS] token) e.g. for ImageNet.
|
| 989 |
+
""",
|
| 990 |
+
TFCVT_START_DOCSTRING,
|
| 991 |
+
)
|
| 992 |
+
class TFCvtForImageClassification(TFCvtPreTrainedModel, TFSequenceClassificationLoss):
|
| 993 |
+
def __init__(self, config: CvtConfig, *inputs, **kwargs):
|
| 994 |
+
super().__init__(config, *inputs, **kwargs)
|
| 995 |
+
|
| 996 |
+
self.num_labels = config.num_labels
|
| 997 |
+
self.cvt = TFCvtMainLayer(config, name="cvt")
|
| 998 |
+
# Using same default epsilon as in the original implementation.
|
| 999 |
+
self.layernorm = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm")
|
| 1000 |
+
|
| 1001 |
+
# Classifier head
|
| 1002 |
+
self.classifier = keras.layers.Dense(
|
| 1003 |
+
units=config.num_labels,
|
| 1004 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1005 |
+
use_bias=True,
|
| 1006 |
+
bias_initializer="zeros",
|
| 1007 |
+
name="classifier",
|
| 1008 |
+
)
|
| 1009 |
+
self.config = config
|
| 1010 |
+
|
| 1011 |
+
@unpack_inputs
|
| 1012 |
+
@add_start_docstrings_to_model_forward(TFCVT_INPUTS_DOCSTRING)
|
| 1013 |
+
@replace_return_docstrings(output_type=TFImageClassifierOutputWithNoAttention, config_class=_CONFIG_FOR_DOC)
|
| 1014 |
+
def call(
|
| 1015 |
+
self,
|
| 1016 |
+
pixel_values: tf.Tensor | None = None,
|
| 1017 |
+
labels: tf.Tensor | None = None,
|
| 1018 |
+
output_hidden_states: Optional[bool] = None,
|
| 1019 |
+
return_dict: Optional[bool] = None,
|
| 1020 |
+
training: Optional[bool] = False,
|
| 1021 |
+
) -> Union[TFImageClassifierOutputWithNoAttention, Tuple[tf.Tensor]]:
|
| 1022 |
+
r"""
|
| 1023 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 1024 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 1025 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1026 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1027 |
+
|
| 1028 |
+
Returns:
|
| 1029 |
+
|
| 1030 |
+
Examples:
|
| 1031 |
+
|
| 1032 |
+
```python
|
| 1033 |
+
>>> from transformers import AutoImageProcessor, TFCvtForImageClassification
|
| 1034 |
+
>>> import tensorflow as tf
|
| 1035 |
+
>>> from PIL import Image
|
| 1036 |
+
>>> import requests
|
| 1037 |
+
|
| 1038 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1039 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1040 |
+
|
| 1041 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/cvt-13")
|
| 1042 |
+
>>> model = TFCvtForImageClassification.from_pretrained("microsoft/cvt-13")
|
| 1043 |
+
|
| 1044 |
+
>>> inputs = image_processor(images=image, return_tensors="tf")
|
| 1045 |
+
>>> outputs = model(**inputs)
|
| 1046 |
+
>>> logits = outputs.logits
|
| 1047 |
+
>>> # model predicts one of the 1000 ImageNet classes
|
| 1048 |
+
>>> predicted_class_idx = tf.math.argmax(logits, axis=-1)[0]
|
| 1049 |
+
>>> print("Predicted class:", model.config.id2label[int(predicted_class_idx)])
|
| 1050 |
+
```"""
|
| 1051 |
+
|
| 1052 |
+
outputs = self.cvt(
|
| 1053 |
+
pixel_values,
|
| 1054 |
+
output_hidden_states=output_hidden_states,
|
| 1055 |
+
return_dict=return_dict,
|
| 1056 |
+
training=training,
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
sequence_output = outputs[0]
|
| 1060 |
+
cls_token = outputs[1]
|
| 1061 |
+
if self.config.cls_token[-1]:
|
| 1062 |
+
sequence_output = self.layernorm(cls_token)
|
| 1063 |
+
else:
|
| 1064 |
+
# rearrange "batch_size, num_channels, height, width -> batch_size, (height*width), num_channels"
|
| 1065 |
+
batch_size, num_channels, height, width = shape_list(sequence_output)
|
| 1066 |
+
sequence_output = tf.reshape(sequence_output, shape=(batch_size, num_channels, height * width))
|
| 1067 |
+
sequence_output = tf.transpose(sequence_output, perm=(0, 2, 1))
|
| 1068 |
+
sequence_output = self.layernorm(sequence_output)
|
| 1069 |
+
|
| 1070 |
+
sequence_output_mean = tf.reduce_mean(sequence_output, axis=1)
|
| 1071 |
+
logits = self.classifier(sequence_output_mean)
|
| 1072 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1073 |
+
|
| 1074 |
+
if not return_dict:
|
| 1075 |
+
output = (logits,) + outputs[2:]
|
| 1076 |
+
return ((loss,) + output) if loss is not None else output
|
| 1077 |
+
|
| 1078 |
+
return TFImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
|
| 1079 |
+
|
| 1080 |
+
def build(self, input_shape=None):
|
| 1081 |
+
if self.built:
|
| 1082 |
+
return
|
| 1083 |
+
self.built = True
|
| 1084 |
+
if getattr(self, "cvt", None) is not None:
|
| 1085 |
+
with tf.name_scope(self.cvt.name):
|
| 1086 |
+
self.cvt.build(None)
|
| 1087 |
+
if getattr(self, "layernorm", None) is not None:
|
| 1088 |
+
with tf.name_scope(self.layernorm.name):
|
| 1089 |
+
self.layernorm.build([None, None, self.config.embed_dim[-1]])
|
| 1090 |
+
if getattr(self, "classifier", None) is not None:
|
| 1091 |
+
if hasattr(self.classifier, "name"):
|
| 1092 |
+
with tf.name_scope(self.classifier.name):
|
| 1093 |
+
self.classifier.build([None, None, self.config.embed_dim[-1]])
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
__all__ = ["TFCvtForImageClassification", "TFCvtModel", "TFCvtPreTrainedModel"]
|
lib/python3.12/site-packages/transformers/models/donut/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_donut_swin import *
|
| 22 |
+
from .feature_extraction_donut import *
|
| 23 |
+
from .image_processing_donut import *
|
| 24 |
+
from .modeling_donut_swin import *
|
| 25 |
+
from .processing_donut import *
|
| 26 |
+
else:
|
| 27 |
+
import sys
|
| 28 |
+
|
| 29 |
+
_file = globals()["__file__"]
|
| 30 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
lib/python3.12/site-packages/transformers/models/donut/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (781 Bytes). View file
|
|
|
lib/python3.12/site-packages/transformers/models/donut/__pycache__/configuration_donut_swin.cpython-312.pyc
ADDED
|
Binary file (5.38 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/donut/__pycache__/feature_extraction_donut.cpython-312.pyc
ADDED
|
Binary file (1.21 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut.cpython-312.pyc
ADDED
|
Binary file (21 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/donut/__pycache__/modeling_donut_swin.cpython-312.pyc
ADDED
|
Binary file (53.9 kB). View file
|
|
|
lib/python3.12/site-packages/transformers/models/donut/__pycache__/processing_donut.cpython-312.pyc
ADDED
|
Binary file (9.53 kB). View file
|
|
|