Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__init__.py +32 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/__init__.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_original_tf2_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_original_tf_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_pytorch_checkpoint_to_original_tf.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/modeling_flax_bert.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/modeling_tf_bert.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/configuration_bert.py +154 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py +246 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py +62 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py +112 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py +188 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py +2009 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/modeling_flax_bert.py +1727 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/modeling_tf_bert.py +2126 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert.py +507 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert_fast.py +175 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert_tf.py +257 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__init__.py +30 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/__init__.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/configuration_blip.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/convert_blip_original_pytorch_to_hf.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/image_processing_blip.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_blip.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/processing_blip.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/configuration_blip.py +329 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/convert_blip_original_pytorch_to_hf.py +191 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip.py +297 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_blip.py +1603 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_blip_text.py +958 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip.py +1709 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip_text.py +1122 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/blip/processing_blip.py +139 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__init__.py +27 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/__init__.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/configuration_hiera.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/convert_hiera_to_hf.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/modeling_hiera.cpython-310.pyc +0 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/configuration_hiera.py +194 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/convert_hiera_to_hf.py +369 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/modeling_hiera.py +1573 -0
- vlmpy310/lib/python3.10/site-packages/transformers/models/mixtral/__init__.py +66 -0
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 import *
|
| 22 |
+
from .modeling_bert import *
|
| 23 |
+
from .modeling_flax_bert import *
|
| 24 |
+
from .modeling_tf_bert import *
|
| 25 |
+
from .tokenization_bert import *
|
| 26 |
+
from .tokenization_bert_fast import *
|
| 27 |
+
from .tokenization_bert_tf import *
|
| 28 |
+
else:
|
| 29 |
+
import sys
|
| 30 |
+
|
| 31 |
+
_file = globals()["__file__"]
|
| 32 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (687 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_original_tf2_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (5.59 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_original_tf_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (1.41 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_pytorch_checkpoint_to_original_tf.cpython-310.pyc
ADDED
|
Binary file (3.72 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.cpython-310.pyc
ADDED
|
Binary file (4.84 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-310.pyc
ADDED
|
Binary file (57.5 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/modeling_flax_bert.cpython-310.pyc
ADDED
|
Binary file (42.3 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/modeling_tf_bert.cpython-310.pyc
ADDED
|
Binary file (61.2 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-310.pyc
ADDED
|
Binary file (17.2 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-310.pyc
ADDED
|
Binary file (6.77 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-310.pyc
ADDED
|
Binary file (9.29 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/configuration_bert.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""BERT model configuration"""
|
| 17 |
+
|
| 18 |
+
from collections import OrderedDict
|
| 19 |
+
from typing import Mapping
|
| 20 |
+
|
| 21 |
+
from ...configuration_utils import PretrainedConfig
|
| 22 |
+
from ...onnx import OnnxConfig
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BertConfig(PretrainedConfig):
|
| 30 |
+
r"""
|
| 31 |
+
This is the configuration class to store the configuration of a [`BertModel`] or a [`TFBertModel`]. It is used to
|
| 32 |
+
instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
|
| 33 |
+
configuration with the defaults will yield a similar configuration to that of the BERT
|
| 34 |
+
[google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) architecture.
|
| 35 |
+
|
| 36 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 37 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
| 42 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
| 43 |
+
`inputs_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
| 44 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 45 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 46 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 47 |
+
Number of hidden layers in the Transformer encoder.
|
| 48 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 50 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 51 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
| 52 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
| 53 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 54 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
| 55 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 56 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 57 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
| 58 |
+
The dropout ratio for the attention probabilities.
|
| 59 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 60 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 61 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 62 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
| 63 |
+
The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
| 64 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 65 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 66 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 67 |
+
The epsilon used by the layer normalization layers.
|
| 68 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
| 69 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
| 70 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
| 71 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
| 72 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
| 73 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
| 74 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
| 75 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
| 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 |
+
classifier_dropout (`float`, *optional*):
|
| 80 |
+
The dropout ratio for the classification head.
|
| 81 |
+
|
| 82 |
+
Examples:
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
>>> from transformers import BertConfig, BertModel
|
| 86 |
+
|
| 87 |
+
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
|
| 88 |
+
>>> configuration = BertConfig()
|
| 89 |
+
|
| 90 |
+
>>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
|
| 91 |
+
>>> model = BertModel(configuration)
|
| 92 |
+
|
| 93 |
+
>>> # Accessing the model configuration
|
| 94 |
+
>>> configuration = model.config
|
| 95 |
+
```"""
|
| 96 |
+
|
| 97 |
+
model_type = "bert"
|
| 98 |
+
|
| 99 |
+
def __init__(
|
| 100 |
+
self,
|
| 101 |
+
vocab_size=30522,
|
| 102 |
+
hidden_size=768,
|
| 103 |
+
num_hidden_layers=12,
|
| 104 |
+
num_attention_heads=12,
|
| 105 |
+
intermediate_size=3072,
|
| 106 |
+
hidden_act="gelu",
|
| 107 |
+
hidden_dropout_prob=0.1,
|
| 108 |
+
attention_probs_dropout_prob=0.1,
|
| 109 |
+
max_position_embeddings=512,
|
| 110 |
+
type_vocab_size=2,
|
| 111 |
+
initializer_range=0.02,
|
| 112 |
+
layer_norm_eps=1e-12,
|
| 113 |
+
pad_token_id=0,
|
| 114 |
+
position_embedding_type="absolute",
|
| 115 |
+
use_cache=True,
|
| 116 |
+
classifier_dropout=None,
|
| 117 |
+
**kwargs,
|
| 118 |
+
):
|
| 119 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
| 120 |
+
|
| 121 |
+
self.vocab_size = vocab_size
|
| 122 |
+
self.hidden_size = hidden_size
|
| 123 |
+
self.num_hidden_layers = num_hidden_layers
|
| 124 |
+
self.num_attention_heads = num_attention_heads
|
| 125 |
+
self.hidden_act = hidden_act
|
| 126 |
+
self.intermediate_size = intermediate_size
|
| 127 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 128 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 129 |
+
self.max_position_embeddings = max_position_embeddings
|
| 130 |
+
self.type_vocab_size = type_vocab_size
|
| 131 |
+
self.initializer_range = initializer_range
|
| 132 |
+
self.layer_norm_eps = layer_norm_eps
|
| 133 |
+
self.position_embedding_type = position_embedding_type
|
| 134 |
+
self.use_cache = use_cache
|
| 135 |
+
self.classifier_dropout = classifier_dropout
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class BertOnnxConfig(OnnxConfig):
|
| 139 |
+
@property
|
| 140 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
| 141 |
+
if self.task == "multiple-choice":
|
| 142 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
| 143 |
+
else:
|
| 144 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
| 145 |
+
return OrderedDict(
|
| 146 |
+
[
|
| 147 |
+
("input_ids", dynamic_axis),
|
| 148 |
+
("attention_mask", dynamic_axis),
|
| 149 |
+
("token_type_ids", dynamic_axis),
|
| 150 |
+
]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
__all__ = ["BertConfig", "BertOnnxConfig"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This script can be used to convert a head-less TF2.x Bert model to PyTorch, as published on the official (now
|
| 17 |
+
deprecated) GitHub: https://github.com/tensorflow/models/tree/v2.3.0/official/nlp/bert
|
| 18 |
+
|
| 19 |
+
TF2.x uses different variable names from the original BERT (TF 1.4) implementation. The script re-maps the TF2.x Bert
|
| 20 |
+
weight names to the original names, so the model can be imported with Huggingface/transformer.
|
| 21 |
+
|
| 22 |
+
You may adapt this script to include classification/MLM/NSP/etc. heads.
|
| 23 |
+
|
| 24 |
+
Note: This script is only working with an older version of the TensorFlow models repository (<= v2.3.0).
|
| 25 |
+
Models trained with never versions are not compatible with this script.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import os
|
| 30 |
+
import re
|
| 31 |
+
|
| 32 |
+
import tensorflow as tf
|
| 33 |
+
import torch
|
| 34 |
+
|
| 35 |
+
from transformers import BertConfig, BertModel
|
| 36 |
+
from transformers.utils import logging
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logging.set_verbosity_info()
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_tf2_weights_in_bert(model, tf_checkpoint_path, config):
|
| 44 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 45 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 46 |
+
# Load weights from TF model
|
| 47 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 48 |
+
names = []
|
| 49 |
+
arrays = []
|
| 50 |
+
layer_depth = []
|
| 51 |
+
for full_name, shape in init_vars:
|
| 52 |
+
# logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 53 |
+
name = full_name.split("/")
|
| 54 |
+
if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]:
|
| 55 |
+
logger.info(f"Skipping non-model layer {full_name}")
|
| 56 |
+
continue
|
| 57 |
+
if "optimizer" in full_name:
|
| 58 |
+
logger.info(f"Skipping optimization layer {full_name}")
|
| 59 |
+
continue
|
| 60 |
+
if name[0] == "model":
|
| 61 |
+
# ignore initial 'model'
|
| 62 |
+
name = name[1:]
|
| 63 |
+
# figure out how many levels deep the name is
|
| 64 |
+
depth = 0
|
| 65 |
+
for _name in name:
|
| 66 |
+
if _name.startswith("layer_with_weights"):
|
| 67 |
+
depth += 1
|
| 68 |
+
else:
|
| 69 |
+
break
|
| 70 |
+
layer_depth.append(depth)
|
| 71 |
+
# read data
|
| 72 |
+
array = tf.train.load_variable(tf_path, full_name)
|
| 73 |
+
names.append("/".join(name))
|
| 74 |
+
arrays.append(array)
|
| 75 |
+
logger.info(f"Read a total of {len(arrays):,} layers")
|
| 76 |
+
|
| 77 |
+
# Sanity check
|
| 78 |
+
if len(set(layer_depth)) != 1:
|
| 79 |
+
raise ValueError(f"Found layer names with different depths (layer depth {list(set(layer_depth))})")
|
| 80 |
+
layer_depth = list(set(layer_depth))[0]
|
| 81 |
+
if layer_depth != 1:
|
| 82 |
+
raise ValueError(
|
| 83 |
+
"The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP"
|
| 84 |
+
" heads."
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# convert layers
|
| 88 |
+
logger.info("Converting weights...")
|
| 89 |
+
for full_name, array in zip(names, arrays):
|
| 90 |
+
name = full_name.split("/")
|
| 91 |
+
pointer = model
|
| 92 |
+
trace = []
|
| 93 |
+
for i, m_name in enumerate(name):
|
| 94 |
+
if m_name == ".ATTRIBUTES":
|
| 95 |
+
# variable names end with .ATTRIBUTES/VARIABLE_VALUE
|
| 96 |
+
break
|
| 97 |
+
if m_name.startswith("layer_with_weights"):
|
| 98 |
+
layer_num = int(m_name.split("-")[-1])
|
| 99 |
+
if layer_num <= 2:
|
| 100 |
+
# embedding layers
|
| 101 |
+
# layer_num 0: word_embeddings
|
| 102 |
+
# layer_num 1: position_embeddings
|
| 103 |
+
# layer_num 2: token_type_embeddings
|
| 104 |
+
continue
|
| 105 |
+
elif layer_num == 3:
|
| 106 |
+
# embedding LayerNorm
|
| 107 |
+
trace.extend(["embeddings", "LayerNorm"])
|
| 108 |
+
pointer = getattr(pointer, "embeddings")
|
| 109 |
+
pointer = getattr(pointer, "LayerNorm")
|
| 110 |
+
elif layer_num > 3 and layer_num < config.num_hidden_layers + 4:
|
| 111 |
+
# encoder layers
|
| 112 |
+
trace.extend(["encoder", "layer", str(layer_num - 4)])
|
| 113 |
+
pointer = getattr(pointer, "encoder")
|
| 114 |
+
pointer = getattr(pointer, "layer")
|
| 115 |
+
pointer = pointer[layer_num - 4]
|
| 116 |
+
elif layer_num == config.num_hidden_layers + 4:
|
| 117 |
+
# pooler layer
|
| 118 |
+
trace.extend(["pooler", "dense"])
|
| 119 |
+
pointer = getattr(pointer, "pooler")
|
| 120 |
+
pointer = getattr(pointer, "dense")
|
| 121 |
+
elif m_name == "embeddings":
|
| 122 |
+
trace.append("embeddings")
|
| 123 |
+
pointer = getattr(pointer, "embeddings")
|
| 124 |
+
if layer_num == 0:
|
| 125 |
+
trace.append("word_embeddings")
|
| 126 |
+
pointer = getattr(pointer, "word_embeddings")
|
| 127 |
+
elif layer_num == 1:
|
| 128 |
+
trace.append("position_embeddings")
|
| 129 |
+
pointer = getattr(pointer, "position_embeddings")
|
| 130 |
+
elif layer_num == 2:
|
| 131 |
+
trace.append("token_type_embeddings")
|
| 132 |
+
pointer = getattr(pointer, "token_type_embeddings")
|
| 133 |
+
else:
|
| 134 |
+
raise ValueError(f"Unknown embedding layer with name {full_name}")
|
| 135 |
+
trace.append("weight")
|
| 136 |
+
pointer = getattr(pointer, "weight")
|
| 137 |
+
elif m_name == "_attention_layer":
|
| 138 |
+
# self-attention layer
|
| 139 |
+
trace.extend(["attention", "self"])
|
| 140 |
+
pointer = getattr(pointer, "attention")
|
| 141 |
+
pointer = getattr(pointer, "self")
|
| 142 |
+
elif m_name == "_attention_layer_norm":
|
| 143 |
+
# output attention norm
|
| 144 |
+
trace.extend(["attention", "output", "LayerNorm"])
|
| 145 |
+
pointer = getattr(pointer, "attention")
|
| 146 |
+
pointer = getattr(pointer, "output")
|
| 147 |
+
pointer = getattr(pointer, "LayerNorm")
|
| 148 |
+
elif m_name == "_attention_output_dense":
|
| 149 |
+
# output attention dense
|
| 150 |
+
trace.extend(["attention", "output", "dense"])
|
| 151 |
+
pointer = getattr(pointer, "attention")
|
| 152 |
+
pointer = getattr(pointer, "output")
|
| 153 |
+
pointer = getattr(pointer, "dense")
|
| 154 |
+
elif m_name == "_output_dense":
|
| 155 |
+
# output dense
|
| 156 |
+
trace.extend(["output", "dense"])
|
| 157 |
+
pointer = getattr(pointer, "output")
|
| 158 |
+
pointer = getattr(pointer, "dense")
|
| 159 |
+
elif m_name == "_output_layer_norm":
|
| 160 |
+
# output dense
|
| 161 |
+
trace.extend(["output", "LayerNorm"])
|
| 162 |
+
pointer = getattr(pointer, "output")
|
| 163 |
+
pointer = getattr(pointer, "LayerNorm")
|
| 164 |
+
elif m_name == "_key_dense":
|
| 165 |
+
# attention key
|
| 166 |
+
trace.append("key")
|
| 167 |
+
pointer = getattr(pointer, "key")
|
| 168 |
+
elif m_name == "_query_dense":
|
| 169 |
+
# attention query
|
| 170 |
+
trace.append("query")
|
| 171 |
+
pointer = getattr(pointer, "query")
|
| 172 |
+
elif m_name == "_value_dense":
|
| 173 |
+
# attention value
|
| 174 |
+
trace.append("value")
|
| 175 |
+
pointer = getattr(pointer, "value")
|
| 176 |
+
elif m_name == "_intermediate_dense":
|
| 177 |
+
# attention intermediate dense
|
| 178 |
+
trace.extend(["intermediate", "dense"])
|
| 179 |
+
pointer = getattr(pointer, "intermediate")
|
| 180 |
+
pointer = getattr(pointer, "dense")
|
| 181 |
+
elif m_name == "_output_layer_norm":
|
| 182 |
+
# output layer norm
|
| 183 |
+
trace.append("output")
|
| 184 |
+
pointer = getattr(pointer, "output")
|
| 185 |
+
# weights & biases
|
| 186 |
+
elif m_name in ["bias", "beta"]:
|
| 187 |
+
trace.append("bias")
|
| 188 |
+
pointer = getattr(pointer, "bias")
|
| 189 |
+
elif m_name in ["kernel", "gamma"]:
|
| 190 |
+
trace.append("weight")
|
| 191 |
+
pointer = getattr(pointer, "weight")
|
| 192 |
+
else:
|
| 193 |
+
logger.warning(f"Ignored {m_name}")
|
| 194 |
+
# for certain layers reshape is necessary
|
| 195 |
+
trace = ".".join(trace)
|
| 196 |
+
if re.match(r"(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)", trace) or re.match(
|
| 197 |
+
r"(\S+)\.attention\.output\.dense\.weight", trace
|
| 198 |
+
):
|
| 199 |
+
array = array.reshape(pointer.data.shape)
|
| 200 |
+
if "kernel" in full_name:
|
| 201 |
+
array = array.transpose()
|
| 202 |
+
if pointer.shape == array.shape:
|
| 203 |
+
pointer.data = torch.from_numpy(array)
|
| 204 |
+
else:
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f"Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:"
|
| 207 |
+
f" {array.shape}"
|
| 208 |
+
)
|
| 209 |
+
logger.info(f"Successfully set variable {full_name} to PyTorch layer {trace}")
|
| 210 |
+
return model
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def convert_tf2_checkpoint_to_pytorch(tf_checkpoint_path, config_path, pytorch_dump_path):
|
| 214 |
+
# Instantiate model
|
| 215 |
+
logger.info(f"Loading model based on config from {config_path}...")
|
| 216 |
+
config = BertConfig.from_json_file(config_path)
|
| 217 |
+
model = BertModel(config)
|
| 218 |
+
|
| 219 |
+
# Load weights from checkpoint
|
| 220 |
+
logger.info(f"Loading weights from checkpoint {tf_checkpoint_path}...")
|
| 221 |
+
load_tf2_weights_in_bert(model, tf_checkpoint_path, config)
|
| 222 |
+
|
| 223 |
+
# Save pytorch-model
|
| 224 |
+
logger.info(f"Saving PyTorch model to {pytorch_dump_path}...")
|
| 225 |
+
torch.save(model.state_dict(), pytorch_dump_path)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
parser = argparse.ArgumentParser()
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow 2.x checkpoint path."
|
| 232 |
+
)
|
| 233 |
+
parser.add_argument(
|
| 234 |
+
"--bert_config_file",
|
| 235 |
+
type=str,
|
| 236 |
+
required=True,
|
| 237 |
+
help="The config json file corresponding to the BERT model. This specifies the model architecture.",
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--pytorch_dump_path",
|
| 241 |
+
type=str,
|
| 242 |
+
required=True,
|
| 243 |
+
help="Path to the output PyTorch model (must include filename).",
|
| 244 |
+
)
|
| 245 |
+
args = parser.parse_args()
|
| 246 |
+
convert_tf2_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Convert BERT checkpoint."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
|
| 22 |
+
from transformers.utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logging.set_verbosity_info()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_path):
|
| 29 |
+
# Initialise PyTorch model
|
| 30 |
+
config = BertConfig.from_json_file(bert_config_file)
|
| 31 |
+
print(f"Building PyTorch model from configuration: {config}")
|
| 32 |
+
model = BertForPreTraining(config)
|
| 33 |
+
|
| 34 |
+
# Load weights from tf checkpoint
|
| 35 |
+
load_tf_weights_in_bert(model, config, tf_checkpoint_path)
|
| 36 |
+
|
| 37 |
+
# Save pytorch-model
|
| 38 |
+
print(f"Save PyTorch model to {pytorch_dump_path}")
|
| 39 |
+
torch.save(model.state_dict(), pytorch_dump_path)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
parser = argparse.ArgumentParser()
|
| 44 |
+
# Required parameters
|
| 45 |
+
parser.add_argument(
|
| 46 |
+
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
|
| 47 |
+
)
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--bert_config_file",
|
| 50 |
+
default=None,
|
| 51 |
+
type=str,
|
| 52 |
+
required=True,
|
| 53 |
+
help=(
|
| 54 |
+
"The config json file corresponding to the pre-trained BERT model. \n"
|
| 55 |
+
"This specifies the model architecture."
|
| 56 |
+
),
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
|
| 60 |
+
)
|
| 61 |
+
args = parser.parse_args()
|
| 62 |
+
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""Convert Huggingface Pytorch checkpoint to Tensorflow checkpoint."""
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
from transformers import BertModel
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def convert_pytorch_checkpoint_to_tf(model: BertModel, ckpt_dir: str, model_name: str):
|
| 29 |
+
"""
|
| 30 |
+
Args:
|
| 31 |
+
model: BertModel Pytorch model instance to be converted
|
| 32 |
+
ckpt_dir: Tensorflow model directory
|
| 33 |
+
model_name: model name
|
| 34 |
+
|
| 35 |
+
Currently supported HF models:
|
| 36 |
+
|
| 37 |
+
- Y BertModel
|
| 38 |
+
- N BertForMaskedLM
|
| 39 |
+
- N BertForPreTraining
|
| 40 |
+
- N BertForMultipleChoice
|
| 41 |
+
- N BertForNextSentencePrediction
|
| 42 |
+
- N BertForSequenceClassification
|
| 43 |
+
- N BertForQuestionAnswering
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
tensors_to_transpose = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value")
|
| 47 |
+
|
| 48 |
+
var_map = (
|
| 49 |
+
("layer.", "layer_"),
|
| 50 |
+
("word_embeddings.weight", "word_embeddings"),
|
| 51 |
+
("position_embeddings.weight", "position_embeddings"),
|
| 52 |
+
("token_type_embeddings.weight", "token_type_embeddings"),
|
| 53 |
+
(".", "/"),
|
| 54 |
+
("LayerNorm/weight", "LayerNorm/gamma"),
|
| 55 |
+
("LayerNorm/bias", "LayerNorm/beta"),
|
| 56 |
+
("weight", "kernel"),
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if not os.path.isdir(ckpt_dir):
|
| 60 |
+
os.makedirs(ckpt_dir)
|
| 61 |
+
|
| 62 |
+
state_dict = model.state_dict()
|
| 63 |
+
|
| 64 |
+
def to_tf_var_name(name: str):
|
| 65 |
+
for patt, repl in iter(var_map):
|
| 66 |
+
name = name.replace(patt, repl)
|
| 67 |
+
return f"bert/{name}"
|
| 68 |
+
|
| 69 |
+
def create_tf_var(tensor: np.ndarray, name: str, session: tf.Session):
|
| 70 |
+
tf_dtype = tf.dtypes.as_dtype(tensor.dtype)
|
| 71 |
+
tf_var = tf.get_variable(dtype=tf_dtype, shape=tensor.shape, name=name, initializer=tf.zeros_initializer())
|
| 72 |
+
session.run(tf.variables_initializer([tf_var]))
|
| 73 |
+
session.run(tf_var)
|
| 74 |
+
return tf_var
|
| 75 |
+
|
| 76 |
+
tf.reset_default_graph()
|
| 77 |
+
with tf.Session() as session:
|
| 78 |
+
for var_name in state_dict:
|
| 79 |
+
tf_name = to_tf_var_name(var_name)
|
| 80 |
+
torch_tensor = state_dict[var_name].numpy()
|
| 81 |
+
if any(x in var_name for x in tensors_to_transpose):
|
| 82 |
+
torch_tensor = torch_tensor.T
|
| 83 |
+
tf_var = create_tf_var(tensor=torch_tensor, name=tf_name, session=session)
|
| 84 |
+
tf_var.assign(tf.cast(torch_tensor, tf_var.dtype))
|
| 85 |
+
tf_weight = session.run(tf_var)
|
| 86 |
+
print(f"Successfully created {tf_name}: {np.allclose(tf_weight, torch_tensor)}")
|
| 87 |
+
|
| 88 |
+
saver = tf.train.Saver(tf.trainable_variables())
|
| 89 |
+
saver.save(session, os.path.join(ckpt_dir, model_name.replace("-", "_") + ".ckpt"))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def main(raw_args=None):
|
| 93 |
+
parser = argparse.ArgumentParser()
|
| 94 |
+
parser.add_argument("--model_name", type=str, required=True, help="model name e.g. google-bert/bert-base-uncased")
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--cache_dir", type=str, default=None, required=False, help="Directory containing pytorch model"
|
| 97 |
+
)
|
| 98 |
+
parser.add_argument("--pytorch_model_path", type=str, required=True, help="/path/to/<pytorch-model-name>.bin")
|
| 99 |
+
parser.add_argument("--tf_cache_dir", type=str, required=True, help="Directory in which to save tensorflow model")
|
| 100 |
+
args = parser.parse_args(raw_args)
|
| 101 |
+
|
| 102 |
+
model = BertModel.from_pretrained(
|
| 103 |
+
pretrained_model_name_or_path=args.model_name,
|
| 104 |
+
state_dict=torch.load(args.pytorch_model_path),
|
| 105 |
+
cache_dir=args.cache_dir,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
convert_pytorch_checkpoint_to_tf(model=model, ckpt_dir=args.tf_cache_dir, model_name=args.model_name)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
main()
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This script converts a lm-head checkpoint from the "Token Dropping" implementation into a PyTorch-compatible BERT
|
| 17 |
+
model. The official implementation of "Token Dropping" can be found in the TensorFlow Models repository:
|
| 18 |
+
|
| 19 |
+
https://github.com/tensorflow/models/tree/master/official/projects/token_dropping
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
|
| 24 |
+
import tensorflow as tf
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
from transformers import BertConfig, BertForMaskedLM
|
| 28 |
+
from transformers.models.bert.modeling_bert import (
|
| 29 |
+
BertIntermediate,
|
| 30 |
+
BertLayer,
|
| 31 |
+
BertOutput,
|
| 32 |
+
BertPooler,
|
| 33 |
+
BertSelfAttention,
|
| 34 |
+
BertSelfOutput,
|
| 35 |
+
)
|
| 36 |
+
from transformers.utils import logging
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
logging.set_verbosity_info()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def convert_checkpoint_to_pytorch(tf_checkpoint_path: str, config_path: str, pytorch_dump_path: str):
|
| 43 |
+
def get_masked_lm_array(name: str):
|
| 44 |
+
full_name = f"masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE"
|
| 45 |
+
array = tf.train.load_variable(tf_checkpoint_path, full_name)
|
| 46 |
+
|
| 47 |
+
if "kernel" in name:
|
| 48 |
+
array = array.transpose()
|
| 49 |
+
|
| 50 |
+
return torch.from_numpy(array)
|
| 51 |
+
|
| 52 |
+
def get_encoder_array(name: str):
|
| 53 |
+
full_name = f"encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE"
|
| 54 |
+
array = tf.train.load_variable(tf_checkpoint_path, full_name)
|
| 55 |
+
|
| 56 |
+
if "kernel" in name:
|
| 57 |
+
array = array.transpose()
|
| 58 |
+
|
| 59 |
+
return torch.from_numpy(array)
|
| 60 |
+
|
| 61 |
+
def get_encoder_layer_array(layer_index: int, name: str):
|
| 62 |
+
full_name = f"encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE"
|
| 63 |
+
array = tf.train.load_variable(tf_checkpoint_path, full_name)
|
| 64 |
+
|
| 65 |
+
if "kernel" in name:
|
| 66 |
+
array = array.transpose()
|
| 67 |
+
|
| 68 |
+
return torch.from_numpy(array)
|
| 69 |
+
|
| 70 |
+
def get_encoder_attention_layer_array(layer_index: int, name: str, orginal_shape):
|
| 71 |
+
full_name = f"encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE"
|
| 72 |
+
array = tf.train.load_variable(tf_checkpoint_path, full_name)
|
| 73 |
+
array = array.reshape(orginal_shape)
|
| 74 |
+
|
| 75 |
+
if "kernel" in name:
|
| 76 |
+
array = array.transpose()
|
| 77 |
+
|
| 78 |
+
return torch.from_numpy(array)
|
| 79 |
+
|
| 80 |
+
print(f"Loading model based on config from {config_path}...")
|
| 81 |
+
config = BertConfig.from_json_file(config_path)
|
| 82 |
+
model = BertForMaskedLM(config)
|
| 83 |
+
|
| 84 |
+
# Layers
|
| 85 |
+
for layer_index in range(0, config.num_hidden_layers):
|
| 86 |
+
layer: BertLayer = model.bert.encoder.layer[layer_index]
|
| 87 |
+
|
| 88 |
+
# Self-attention
|
| 89 |
+
self_attn: BertSelfAttention = layer.attention.self
|
| 90 |
+
|
| 91 |
+
self_attn.query.weight.data = get_encoder_attention_layer_array(
|
| 92 |
+
layer_index, "_query_dense/kernel", self_attn.query.weight.data.shape
|
| 93 |
+
)
|
| 94 |
+
self_attn.query.bias.data = get_encoder_attention_layer_array(
|
| 95 |
+
layer_index, "_query_dense/bias", self_attn.query.bias.data.shape
|
| 96 |
+
)
|
| 97 |
+
self_attn.key.weight.data = get_encoder_attention_layer_array(
|
| 98 |
+
layer_index, "_key_dense/kernel", self_attn.key.weight.data.shape
|
| 99 |
+
)
|
| 100 |
+
self_attn.key.bias.data = get_encoder_attention_layer_array(
|
| 101 |
+
layer_index, "_key_dense/bias", self_attn.key.bias.data.shape
|
| 102 |
+
)
|
| 103 |
+
self_attn.value.weight.data = get_encoder_attention_layer_array(
|
| 104 |
+
layer_index, "_value_dense/kernel", self_attn.value.weight.data.shape
|
| 105 |
+
)
|
| 106 |
+
self_attn.value.bias.data = get_encoder_attention_layer_array(
|
| 107 |
+
layer_index, "_value_dense/bias", self_attn.value.bias.data.shape
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Self-attention Output
|
| 111 |
+
self_output: BertSelfOutput = layer.attention.output
|
| 112 |
+
|
| 113 |
+
self_output.dense.weight.data = get_encoder_attention_layer_array(
|
| 114 |
+
layer_index, "_output_dense/kernel", self_output.dense.weight.data.shape
|
| 115 |
+
)
|
| 116 |
+
self_output.dense.bias.data = get_encoder_attention_layer_array(
|
| 117 |
+
layer_index, "_output_dense/bias", self_output.dense.bias.data.shape
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
self_output.LayerNorm.weight.data = get_encoder_layer_array(layer_index, "_attention_layer_norm/gamma")
|
| 121 |
+
self_output.LayerNorm.bias.data = get_encoder_layer_array(layer_index, "_attention_layer_norm/beta")
|
| 122 |
+
|
| 123 |
+
# Intermediate
|
| 124 |
+
intermediate: BertIntermediate = layer.intermediate
|
| 125 |
+
|
| 126 |
+
intermediate.dense.weight.data = get_encoder_layer_array(layer_index, "_intermediate_dense/kernel")
|
| 127 |
+
intermediate.dense.bias.data = get_encoder_layer_array(layer_index, "_intermediate_dense/bias")
|
| 128 |
+
|
| 129 |
+
# Output
|
| 130 |
+
bert_output: BertOutput = layer.output
|
| 131 |
+
|
| 132 |
+
bert_output.dense.weight.data = get_encoder_layer_array(layer_index, "_output_dense/kernel")
|
| 133 |
+
bert_output.dense.bias.data = get_encoder_layer_array(layer_index, "_output_dense/bias")
|
| 134 |
+
|
| 135 |
+
bert_output.LayerNorm.weight.data = get_encoder_layer_array(layer_index, "_output_layer_norm/gamma")
|
| 136 |
+
bert_output.LayerNorm.bias.data = get_encoder_layer_array(layer_index, "_output_layer_norm/beta")
|
| 137 |
+
|
| 138 |
+
# Embeddings
|
| 139 |
+
model.bert.embeddings.position_embeddings.weight.data = get_encoder_array("_position_embedding_layer/embeddings")
|
| 140 |
+
model.bert.embeddings.token_type_embeddings.weight.data = get_encoder_array("_type_embedding_layer/embeddings")
|
| 141 |
+
model.bert.embeddings.LayerNorm.weight.data = get_encoder_array("_embedding_norm_layer/gamma")
|
| 142 |
+
model.bert.embeddings.LayerNorm.bias.data = get_encoder_array("_embedding_norm_layer/beta")
|
| 143 |
+
|
| 144 |
+
# LM Head
|
| 145 |
+
lm_head = model.cls.predictions.transform
|
| 146 |
+
|
| 147 |
+
lm_head.dense.weight.data = get_masked_lm_array("dense/kernel")
|
| 148 |
+
lm_head.dense.bias.data = get_masked_lm_array("dense/bias")
|
| 149 |
+
|
| 150 |
+
lm_head.LayerNorm.weight.data = get_masked_lm_array("layer_norm/gamma")
|
| 151 |
+
lm_head.LayerNorm.bias.data = get_masked_lm_array("layer_norm/beta")
|
| 152 |
+
|
| 153 |
+
model.bert.embeddings.word_embeddings.weight.data = get_masked_lm_array("embedding_table")
|
| 154 |
+
|
| 155 |
+
# Pooling
|
| 156 |
+
model.bert.pooler = BertPooler(config=config)
|
| 157 |
+
model.bert.pooler.dense.weight.data: BertPooler = get_encoder_array("_pooler_layer/kernel")
|
| 158 |
+
model.bert.pooler.dense.bias.data: BertPooler = get_encoder_array("_pooler_layer/bias")
|
| 159 |
+
|
| 160 |
+
# Export final model
|
| 161 |
+
model.save_pretrained(pytorch_dump_path)
|
| 162 |
+
|
| 163 |
+
# Integration test - should load without any errors ;)
|
| 164 |
+
new_model = BertForMaskedLM.from_pretrained(pytorch_dump_path)
|
| 165 |
+
print(new_model.eval())
|
| 166 |
+
|
| 167 |
+
print("Model conversion was done sucessfully!")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
parser = argparse.ArgumentParser()
|
| 172 |
+
parser.add_argument(
|
| 173 |
+
"--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path."
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--bert_config_file",
|
| 177 |
+
type=str,
|
| 178 |
+
required=True,
|
| 179 |
+
help="The config json file corresponding to the BERT model. This specifies the model architecture.",
|
| 180 |
+
)
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--pytorch_dump_path",
|
| 183 |
+
type=str,
|
| 184 |
+
required=True,
|
| 185 |
+
help="Path to the output PyTorch model.",
|
| 186 |
+
)
|
| 187 |
+
args = parser.parse_args()
|
| 188 |
+
convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py
ADDED
|
@@ -0,0 +1,2009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""PyTorch BERT model."""
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
import warnings
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
from typing import List, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.utils.checkpoint
|
| 26 |
+
from packaging import version
|
| 27 |
+
from torch import nn
|
| 28 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 29 |
+
|
| 30 |
+
from ...activations import ACT2FN
|
| 31 |
+
from ...generation import GenerationMixin
|
| 32 |
+
from ...modeling_attn_mask_utils import (
|
| 33 |
+
_prepare_4d_attention_mask_for_sdpa,
|
| 34 |
+
_prepare_4d_causal_attention_mask_for_sdpa,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_outputs import (
|
| 37 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 38 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 39 |
+
CausalLMOutputWithCrossAttentions,
|
| 40 |
+
MaskedLMOutput,
|
| 41 |
+
MultipleChoiceModelOutput,
|
| 42 |
+
NextSentencePredictorOutput,
|
| 43 |
+
QuestionAnsweringModelOutput,
|
| 44 |
+
SequenceClassifierOutput,
|
| 45 |
+
TokenClassifierOutput,
|
| 46 |
+
)
|
| 47 |
+
from ...modeling_utils import PreTrainedModel
|
| 48 |
+
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
| 49 |
+
from ...utils import (
|
| 50 |
+
ModelOutput,
|
| 51 |
+
add_code_sample_docstrings,
|
| 52 |
+
add_start_docstrings,
|
| 53 |
+
add_start_docstrings_to_model_forward,
|
| 54 |
+
get_torch_version,
|
| 55 |
+
logging,
|
| 56 |
+
replace_return_docstrings,
|
| 57 |
+
)
|
| 58 |
+
from .configuration_bert import BertConfig
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
logger = logging.get_logger(__name__)
|
| 62 |
+
|
| 63 |
+
_CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
|
| 64 |
+
_CONFIG_FOR_DOC = "BertConfig"
|
| 65 |
+
|
| 66 |
+
# TokenClassification docstring
|
| 67 |
+
_CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
|
| 68 |
+
_TOKEN_CLASS_EXPECTED_OUTPUT = (
|
| 69 |
+
"['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
|
| 70 |
+
)
|
| 71 |
+
_TOKEN_CLASS_EXPECTED_LOSS = 0.01
|
| 72 |
+
|
| 73 |
+
# QuestionAnswering docstring
|
| 74 |
+
_CHECKPOINT_FOR_QA = "deepset/bert-base-cased-squad2"
|
| 75 |
+
_QA_EXPECTED_OUTPUT = "'a nice puppet'"
|
| 76 |
+
_QA_EXPECTED_LOSS = 7.41
|
| 77 |
+
_QA_TARGET_START_INDEX = 14
|
| 78 |
+
_QA_TARGET_END_INDEX = 15
|
| 79 |
+
|
| 80 |
+
# SequenceClassification docstring
|
| 81 |
+
_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "textattack/bert-base-uncased-yelp-polarity"
|
| 82 |
+
_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
|
| 83 |
+
_SEQ_CLASS_EXPECTED_LOSS = 0.01
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
|
| 87 |
+
"""Load tf checkpoints in a pytorch model."""
|
| 88 |
+
try:
|
| 89 |
+
import re
|
| 90 |
+
|
| 91 |
+
import numpy as np
|
| 92 |
+
import tensorflow as tf
|
| 93 |
+
except ImportError:
|
| 94 |
+
logger.error(
|
| 95 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
| 96 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
| 97 |
+
)
|
| 98 |
+
raise
|
| 99 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
| 100 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
| 101 |
+
# Load weights from TF model
|
| 102 |
+
init_vars = tf.train.list_variables(tf_path)
|
| 103 |
+
names = []
|
| 104 |
+
arrays = []
|
| 105 |
+
for name, shape in init_vars:
|
| 106 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
| 107 |
+
array = tf.train.load_variable(tf_path, name)
|
| 108 |
+
names.append(name)
|
| 109 |
+
arrays.append(array)
|
| 110 |
+
|
| 111 |
+
for name, array in zip(names, arrays):
|
| 112 |
+
name = name.split("/")
|
| 113 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
| 114 |
+
# which are not required for using pretrained model
|
| 115 |
+
if any(
|
| 116 |
+
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
|
| 117 |
+
for n in name
|
| 118 |
+
):
|
| 119 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 120 |
+
continue
|
| 121 |
+
pointer = model
|
| 122 |
+
for m_name in name:
|
| 123 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
| 124 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
| 125 |
+
else:
|
| 126 |
+
scope_names = [m_name]
|
| 127 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
| 128 |
+
pointer = getattr(pointer, "weight")
|
| 129 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
| 130 |
+
pointer = getattr(pointer, "bias")
|
| 131 |
+
elif scope_names[0] == "output_weights":
|
| 132 |
+
pointer = getattr(pointer, "weight")
|
| 133 |
+
elif scope_names[0] == "squad":
|
| 134 |
+
pointer = getattr(pointer, "classifier")
|
| 135 |
+
else:
|
| 136 |
+
try:
|
| 137 |
+
pointer = getattr(pointer, scope_names[0])
|
| 138 |
+
except AttributeError:
|
| 139 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
| 140 |
+
continue
|
| 141 |
+
if len(scope_names) >= 2:
|
| 142 |
+
num = int(scope_names[1])
|
| 143 |
+
pointer = pointer[num]
|
| 144 |
+
if m_name[-11:] == "_embeddings":
|
| 145 |
+
pointer = getattr(pointer, "weight")
|
| 146 |
+
elif m_name == "kernel":
|
| 147 |
+
array = np.transpose(array)
|
| 148 |
+
try:
|
| 149 |
+
if pointer.shape != array.shape:
|
| 150 |
+
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
|
| 151 |
+
except ValueError as e:
|
| 152 |
+
e.args += (pointer.shape, array.shape)
|
| 153 |
+
raise
|
| 154 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
| 155 |
+
pointer.data = torch.from_numpy(array)
|
| 156 |
+
return model
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class BertEmbeddings(nn.Module):
|
| 160 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 161 |
+
|
| 162 |
+
def __init__(self, config):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 165 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 166 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 167 |
+
|
| 168 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 169 |
+
# any TensorFlow checkpoint file
|
| 170 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 171 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 172 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 173 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 174 |
+
self.register_buffer(
|
| 175 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 176 |
+
)
|
| 177 |
+
self.register_buffer(
|
| 178 |
+
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def forward(
|
| 182 |
+
self,
|
| 183 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 184 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 185 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 186 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 187 |
+
past_key_values_length: int = 0,
|
| 188 |
+
) -> torch.Tensor:
|
| 189 |
+
if input_ids is not None:
|
| 190 |
+
input_shape = input_ids.size()
|
| 191 |
+
else:
|
| 192 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 193 |
+
|
| 194 |
+
seq_length = input_shape[1]
|
| 195 |
+
|
| 196 |
+
if position_ids is None:
|
| 197 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 198 |
+
|
| 199 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 200 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 201 |
+
# issue #5664
|
| 202 |
+
if token_type_ids is None:
|
| 203 |
+
if hasattr(self, "token_type_ids"):
|
| 204 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 205 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 206 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 207 |
+
else:
|
| 208 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 209 |
+
|
| 210 |
+
if inputs_embeds is None:
|
| 211 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 212 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 213 |
+
|
| 214 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 215 |
+
if self.position_embedding_type == "absolute":
|
| 216 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 217 |
+
embeddings += position_embeddings
|
| 218 |
+
embeddings = self.LayerNorm(embeddings)
|
| 219 |
+
embeddings = self.dropout(embeddings)
|
| 220 |
+
return embeddings
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class BertSelfAttention(nn.Module):
|
| 224 |
+
def __init__(self, config, position_embedding_type=None):
|
| 225 |
+
super().__init__()
|
| 226 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 227 |
+
raise ValueError(
|
| 228 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
| 229 |
+
f"heads ({config.num_attention_heads})"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
self.num_attention_heads = config.num_attention_heads
|
| 233 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 234 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 235 |
+
|
| 236 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 237 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 238 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 239 |
+
|
| 240 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 241 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
| 242 |
+
config, "position_embedding_type", "absolute"
|
| 243 |
+
)
|
| 244 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 245 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 246 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 247 |
+
|
| 248 |
+
self.is_decoder = config.is_decoder
|
| 249 |
+
|
| 250 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 251 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 252 |
+
x = x.view(new_x_shape)
|
| 253 |
+
return x.permute(0, 2, 1, 3)
|
| 254 |
+
|
| 255 |
+
def forward(
|
| 256 |
+
self,
|
| 257 |
+
hidden_states: torch.Tensor,
|
| 258 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 259 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 260 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 261 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 262 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 263 |
+
output_attentions: Optional[bool] = False,
|
| 264 |
+
) -> Tuple[torch.Tensor]:
|
| 265 |
+
mixed_query_layer = self.query(hidden_states)
|
| 266 |
+
|
| 267 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 268 |
+
# and values come from an encoder; the attention mask needs to be
|
| 269 |
+
# such that the encoder's padding tokens are not attended to.
|
| 270 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 271 |
+
|
| 272 |
+
if is_cross_attention and past_key_value is not None:
|
| 273 |
+
# reuse k,v, cross_attentions
|
| 274 |
+
key_layer = past_key_value[0]
|
| 275 |
+
value_layer = past_key_value[1]
|
| 276 |
+
attention_mask = encoder_attention_mask
|
| 277 |
+
elif is_cross_attention:
|
| 278 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 279 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 280 |
+
attention_mask = encoder_attention_mask
|
| 281 |
+
elif past_key_value is not None:
|
| 282 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 283 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 284 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 285 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 286 |
+
else:
|
| 287 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 288 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 289 |
+
|
| 290 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 291 |
+
|
| 292 |
+
use_cache = past_key_value is not None
|
| 293 |
+
if self.is_decoder:
|
| 294 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 295 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 296 |
+
# key/value_states (first "if" case)
|
| 297 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 298 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 299 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 300 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 301 |
+
past_key_value = (key_layer, value_layer)
|
| 302 |
+
|
| 303 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 304 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 305 |
+
|
| 306 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 307 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
| 308 |
+
if use_cache:
|
| 309 |
+
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
|
| 310 |
+
-1, 1
|
| 311 |
+
)
|
| 312 |
+
else:
|
| 313 |
+
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 314 |
+
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 315 |
+
distance = position_ids_l - position_ids_r
|
| 316 |
+
|
| 317 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 318 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 319 |
+
|
| 320 |
+
if self.position_embedding_type == "relative_key":
|
| 321 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 322 |
+
attention_scores = attention_scores + relative_position_scores
|
| 323 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 324 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 325 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 326 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 327 |
+
|
| 328 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 329 |
+
if attention_mask is not None:
|
| 330 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
| 331 |
+
attention_scores = attention_scores + attention_mask
|
| 332 |
+
|
| 333 |
+
# Normalize the attention scores to probabilities.
|
| 334 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 335 |
+
|
| 336 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 337 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 338 |
+
attention_probs = self.dropout(attention_probs)
|
| 339 |
+
|
| 340 |
+
# Mask heads if we want to
|
| 341 |
+
if head_mask is not None:
|
| 342 |
+
attention_probs = attention_probs * head_mask
|
| 343 |
+
|
| 344 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 345 |
+
|
| 346 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 347 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 348 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 349 |
+
|
| 350 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 351 |
+
|
| 352 |
+
if self.is_decoder:
|
| 353 |
+
outputs = outputs + (past_key_value,)
|
| 354 |
+
return outputs
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class BertSdpaSelfAttention(BertSelfAttention):
|
| 358 |
+
def __init__(self, config, position_embedding_type=None):
|
| 359 |
+
super().__init__(config, position_embedding_type=position_embedding_type)
|
| 360 |
+
self.dropout_prob = config.attention_probs_dropout_prob
|
| 361 |
+
self.require_contiguous_qkv = version.parse(get_torch_version()) < version.parse("2.2.0")
|
| 362 |
+
|
| 363 |
+
# Adapted from BertSelfAttention
|
| 364 |
+
def forward(
|
| 365 |
+
self,
|
| 366 |
+
hidden_states: torch.Tensor,
|
| 367 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 368 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 369 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 370 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 371 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 372 |
+
output_attentions: Optional[bool] = False,
|
| 373 |
+
) -> Tuple[torch.Tensor]:
|
| 374 |
+
if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
|
| 375 |
+
# TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once implemented.
|
| 376 |
+
logger.warning_once(
|
| 377 |
+
"BertSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
|
| 378 |
+
"non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
|
| 379 |
+
"the manual attention implementation, but specifying the manual implementation will be required from "
|
| 380 |
+
"Transformers version v5.0.0 onwards. This warning can be removed using the argument "
|
| 381 |
+
'`attn_implementation="eager"` when loading the model.'
|
| 382 |
+
)
|
| 383 |
+
return super().forward(
|
| 384 |
+
hidden_states,
|
| 385 |
+
attention_mask,
|
| 386 |
+
head_mask,
|
| 387 |
+
encoder_hidden_states,
|
| 388 |
+
encoder_attention_mask,
|
| 389 |
+
past_key_value,
|
| 390 |
+
output_attentions,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 394 |
+
|
| 395 |
+
query_layer = self.transpose_for_scores(self.query(hidden_states))
|
| 396 |
+
|
| 397 |
+
# If this is instantiated as a cross-attention module, the keys and values come from an encoder; the attention
|
| 398 |
+
# mask needs to be such that the encoder's padding tokens are not attended to.
|
| 399 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 400 |
+
|
| 401 |
+
current_states = encoder_hidden_states if is_cross_attention else hidden_states
|
| 402 |
+
attention_mask = encoder_attention_mask if is_cross_attention else attention_mask
|
| 403 |
+
|
| 404 |
+
# Check `seq_length` of `past_key_value` == `len(current_states)` to support prefix tuning
|
| 405 |
+
if is_cross_attention and past_key_value and past_key_value[0].shape[2] == current_states.shape[1]:
|
| 406 |
+
key_layer, value_layer = past_key_value
|
| 407 |
+
else:
|
| 408 |
+
key_layer = self.transpose_for_scores(self.key(current_states))
|
| 409 |
+
value_layer = self.transpose_for_scores(self.value(current_states))
|
| 410 |
+
if past_key_value is not None and not is_cross_attention:
|
| 411 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 412 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 413 |
+
|
| 414 |
+
if self.is_decoder:
|
| 415 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 416 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 417 |
+
# key/value_states (first "if" case)
|
| 418 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 419 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 420 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 421 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 422 |
+
past_key_value = (key_layer, value_layer)
|
| 423 |
+
|
| 424 |
+
# SDPA with memory-efficient backend is broken in torch==2.1.2 when using non-contiguous inputs and a custom
|
| 425 |
+
# attn_mask, so we need to call `.contiguous()` here. This was fixed in torch==2.2.0.
|
| 426 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577
|
| 427 |
+
if self.require_contiguous_qkv and query_layer.device.type == "cuda" and attention_mask is not None:
|
| 428 |
+
query_layer = query_layer.contiguous()
|
| 429 |
+
key_layer = key_layer.contiguous()
|
| 430 |
+
value_layer = value_layer.contiguous()
|
| 431 |
+
|
| 432 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 433 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 434 |
+
# The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create
|
| 435 |
+
# a causal mask in case tgt_len == 1.
|
| 436 |
+
is_causal = (
|
| 437 |
+
True if self.is_decoder and not is_cross_attention and attention_mask is None and tgt_len > 1 else False
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 441 |
+
query_layer,
|
| 442 |
+
key_layer,
|
| 443 |
+
value_layer,
|
| 444 |
+
attn_mask=attention_mask,
|
| 445 |
+
dropout_p=self.dropout_prob if self.training else 0.0,
|
| 446 |
+
is_causal=is_causal,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
attn_output = attn_output.transpose(1, 2)
|
| 450 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.all_head_size)
|
| 451 |
+
|
| 452 |
+
outputs = (attn_output,)
|
| 453 |
+
if self.is_decoder:
|
| 454 |
+
outputs = outputs + (past_key_value,)
|
| 455 |
+
return outputs
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class BertSelfOutput(nn.Module):
|
| 459 |
+
def __init__(self, config):
|
| 460 |
+
super().__init__()
|
| 461 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 462 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 463 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 464 |
+
|
| 465 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 466 |
+
hidden_states = self.dense(hidden_states)
|
| 467 |
+
hidden_states = self.dropout(hidden_states)
|
| 468 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 469 |
+
return hidden_states
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
BERT_SELF_ATTENTION_CLASSES = {
|
| 473 |
+
"eager": BertSelfAttention,
|
| 474 |
+
"sdpa": BertSdpaSelfAttention,
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class BertAttention(nn.Module):
|
| 479 |
+
def __init__(self, config, position_embedding_type=None):
|
| 480 |
+
super().__init__()
|
| 481 |
+
self.self = BERT_SELF_ATTENTION_CLASSES[config._attn_implementation](
|
| 482 |
+
config, position_embedding_type=position_embedding_type
|
| 483 |
+
)
|
| 484 |
+
self.output = BertSelfOutput(config)
|
| 485 |
+
self.pruned_heads = set()
|
| 486 |
+
|
| 487 |
+
def prune_heads(self, heads):
|
| 488 |
+
if len(heads) == 0:
|
| 489 |
+
return
|
| 490 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 491 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
# Prune linear layers
|
| 495 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 496 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 497 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 498 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 499 |
+
|
| 500 |
+
# Update hyper params and store pruned heads
|
| 501 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 502 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 503 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 504 |
+
|
| 505 |
+
def forward(
|
| 506 |
+
self,
|
| 507 |
+
hidden_states: torch.Tensor,
|
| 508 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 509 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 510 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 511 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 512 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 513 |
+
output_attentions: Optional[bool] = False,
|
| 514 |
+
) -> Tuple[torch.Tensor]:
|
| 515 |
+
self_outputs = self.self(
|
| 516 |
+
hidden_states,
|
| 517 |
+
attention_mask,
|
| 518 |
+
head_mask,
|
| 519 |
+
encoder_hidden_states,
|
| 520 |
+
encoder_attention_mask,
|
| 521 |
+
past_key_value,
|
| 522 |
+
output_attentions,
|
| 523 |
+
)
|
| 524 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 525 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 526 |
+
return outputs
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
class BertIntermediate(nn.Module):
|
| 530 |
+
def __init__(self, config):
|
| 531 |
+
super().__init__()
|
| 532 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 533 |
+
if isinstance(config.hidden_act, str):
|
| 534 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 535 |
+
else:
|
| 536 |
+
self.intermediate_act_fn = config.hidden_act
|
| 537 |
+
|
| 538 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 539 |
+
hidden_states = self.dense(hidden_states)
|
| 540 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 541 |
+
return hidden_states
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
class BertOutput(nn.Module):
|
| 545 |
+
def __init__(self, config):
|
| 546 |
+
super().__init__()
|
| 547 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 548 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 549 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 550 |
+
|
| 551 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 552 |
+
hidden_states = self.dense(hidden_states)
|
| 553 |
+
hidden_states = self.dropout(hidden_states)
|
| 554 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 555 |
+
return hidden_states
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
class BertLayer(nn.Module):
|
| 559 |
+
def __init__(self, config):
|
| 560 |
+
super().__init__()
|
| 561 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 562 |
+
self.seq_len_dim = 1
|
| 563 |
+
self.attention = BertAttention(config)
|
| 564 |
+
self.is_decoder = config.is_decoder
|
| 565 |
+
self.add_cross_attention = config.add_cross_attention
|
| 566 |
+
if self.add_cross_attention:
|
| 567 |
+
if not self.is_decoder:
|
| 568 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 569 |
+
self.crossattention = BertAttention(config, position_embedding_type="absolute")
|
| 570 |
+
self.intermediate = BertIntermediate(config)
|
| 571 |
+
self.output = BertOutput(config)
|
| 572 |
+
|
| 573 |
+
def forward(
|
| 574 |
+
self,
|
| 575 |
+
hidden_states: torch.Tensor,
|
| 576 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 577 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 578 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 579 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 580 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 581 |
+
output_attentions: Optional[bool] = False,
|
| 582 |
+
) -> Tuple[torch.Tensor]:
|
| 583 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 584 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 585 |
+
self_attention_outputs = self.attention(
|
| 586 |
+
hidden_states,
|
| 587 |
+
attention_mask,
|
| 588 |
+
head_mask,
|
| 589 |
+
output_attentions=output_attentions,
|
| 590 |
+
past_key_value=self_attn_past_key_value,
|
| 591 |
+
)
|
| 592 |
+
attention_output = self_attention_outputs[0]
|
| 593 |
+
|
| 594 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 595 |
+
if self.is_decoder:
|
| 596 |
+
outputs = self_attention_outputs[1:-1]
|
| 597 |
+
present_key_value = self_attention_outputs[-1]
|
| 598 |
+
else:
|
| 599 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 600 |
+
|
| 601 |
+
cross_attn_present_key_value = None
|
| 602 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 603 |
+
if not hasattr(self, "crossattention"):
|
| 604 |
+
raise ValueError(
|
| 605 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 606 |
+
" by setting `config.add_cross_attention=True`"
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 610 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 611 |
+
cross_attention_outputs = self.crossattention(
|
| 612 |
+
attention_output,
|
| 613 |
+
attention_mask,
|
| 614 |
+
head_mask,
|
| 615 |
+
encoder_hidden_states,
|
| 616 |
+
encoder_attention_mask,
|
| 617 |
+
cross_attn_past_key_value,
|
| 618 |
+
output_attentions,
|
| 619 |
+
)
|
| 620 |
+
attention_output = cross_attention_outputs[0]
|
| 621 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 622 |
+
|
| 623 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 624 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 625 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 626 |
+
|
| 627 |
+
layer_output = apply_chunking_to_forward(
|
| 628 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 629 |
+
)
|
| 630 |
+
outputs = (layer_output,) + outputs
|
| 631 |
+
|
| 632 |
+
# if decoder, return the attn key/values as the last output
|
| 633 |
+
if self.is_decoder:
|
| 634 |
+
outputs = outputs + (present_key_value,)
|
| 635 |
+
|
| 636 |
+
return outputs
|
| 637 |
+
|
| 638 |
+
def feed_forward_chunk(self, attention_output):
|
| 639 |
+
intermediate_output = self.intermediate(attention_output)
|
| 640 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 641 |
+
return layer_output
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
class BertEncoder(nn.Module):
|
| 645 |
+
def __init__(self, config):
|
| 646 |
+
super().__init__()
|
| 647 |
+
self.config = config
|
| 648 |
+
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
|
| 649 |
+
self.gradient_checkpointing = False
|
| 650 |
+
|
| 651 |
+
def forward(
|
| 652 |
+
self,
|
| 653 |
+
hidden_states: torch.Tensor,
|
| 654 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 655 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 656 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 657 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 658 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 659 |
+
use_cache: Optional[bool] = None,
|
| 660 |
+
output_attentions: Optional[bool] = False,
|
| 661 |
+
output_hidden_states: Optional[bool] = False,
|
| 662 |
+
return_dict: Optional[bool] = True,
|
| 663 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 664 |
+
all_hidden_states = () if output_hidden_states else None
|
| 665 |
+
all_self_attentions = () if output_attentions else None
|
| 666 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 667 |
+
|
| 668 |
+
if self.gradient_checkpointing and self.training:
|
| 669 |
+
if use_cache:
|
| 670 |
+
logger.warning_once(
|
| 671 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 672 |
+
)
|
| 673 |
+
use_cache = False
|
| 674 |
+
|
| 675 |
+
next_decoder_cache = () if use_cache else None
|
| 676 |
+
for i, layer_module in enumerate(self.layer):
|
| 677 |
+
if output_hidden_states:
|
| 678 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 679 |
+
|
| 680 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 681 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 682 |
+
|
| 683 |
+
if self.gradient_checkpointing and self.training:
|
| 684 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 685 |
+
layer_module.__call__,
|
| 686 |
+
hidden_states,
|
| 687 |
+
attention_mask,
|
| 688 |
+
layer_head_mask,
|
| 689 |
+
encoder_hidden_states,
|
| 690 |
+
encoder_attention_mask,
|
| 691 |
+
past_key_value,
|
| 692 |
+
output_attentions,
|
| 693 |
+
)
|
| 694 |
+
else:
|
| 695 |
+
layer_outputs = layer_module(
|
| 696 |
+
hidden_states,
|
| 697 |
+
attention_mask,
|
| 698 |
+
layer_head_mask,
|
| 699 |
+
encoder_hidden_states,
|
| 700 |
+
encoder_attention_mask,
|
| 701 |
+
past_key_value,
|
| 702 |
+
output_attentions,
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
hidden_states = layer_outputs[0]
|
| 706 |
+
if use_cache:
|
| 707 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 708 |
+
if output_attentions:
|
| 709 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 710 |
+
if self.config.add_cross_attention:
|
| 711 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 712 |
+
|
| 713 |
+
if output_hidden_states:
|
| 714 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 715 |
+
|
| 716 |
+
if not return_dict:
|
| 717 |
+
return tuple(
|
| 718 |
+
v
|
| 719 |
+
for v in [
|
| 720 |
+
hidden_states,
|
| 721 |
+
next_decoder_cache,
|
| 722 |
+
all_hidden_states,
|
| 723 |
+
all_self_attentions,
|
| 724 |
+
all_cross_attentions,
|
| 725 |
+
]
|
| 726 |
+
if v is not None
|
| 727 |
+
)
|
| 728 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 729 |
+
last_hidden_state=hidden_states,
|
| 730 |
+
past_key_values=next_decoder_cache,
|
| 731 |
+
hidden_states=all_hidden_states,
|
| 732 |
+
attentions=all_self_attentions,
|
| 733 |
+
cross_attentions=all_cross_attentions,
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
class BertPooler(nn.Module):
|
| 738 |
+
def __init__(self, config):
|
| 739 |
+
super().__init__()
|
| 740 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 741 |
+
self.activation = nn.Tanh()
|
| 742 |
+
|
| 743 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 744 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 745 |
+
# to the first token.
|
| 746 |
+
first_token_tensor = hidden_states[:, 0]
|
| 747 |
+
pooled_output = self.dense(first_token_tensor)
|
| 748 |
+
pooled_output = self.activation(pooled_output)
|
| 749 |
+
return pooled_output
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
class BertPredictionHeadTransform(nn.Module):
|
| 753 |
+
def __init__(self, config):
|
| 754 |
+
super().__init__()
|
| 755 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 756 |
+
if isinstance(config.hidden_act, str):
|
| 757 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 758 |
+
else:
|
| 759 |
+
self.transform_act_fn = config.hidden_act
|
| 760 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 761 |
+
|
| 762 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 763 |
+
hidden_states = self.dense(hidden_states)
|
| 764 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 765 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 766 |
+
return hidden_states
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
class BertLMPredictionHead(nn.Module):
|
| 770 |
+
def __init__(self, config):
|
| 771 |
+
super().__init__()
|
| 772 |
+
self.transform = BertPredictionHeadTransform(config)
|
| 773 |
+
|
| 774 |
+
# The output weights are the same as the input embeddings, but there is
|
| 775 |
+
# an output-only bias for each token.
|
| 776 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 777 |
+
|
| 778 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 779 |
+
|
| 780 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
| 781 |
+
self.decoder.bias = self.bias
|
| 782 |
+
|
| 783 |
+
def _tie_weights(self):
|
| 784 |
+
self.decoder.bias = self.bias
|
| 785 |
+
|
| 786 |
+
def forward(self, hidden_states):
|
| 787 |
+
hidden_states = self.transform(hidden_states)
|
| 788 |
+
hidden_states = self.decoder(hidden_states)
|
| 789 |
+
return hidden_states
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
class BertOnlyMLMHead(nn.Module):
|
| 793 |
+
def __init__(self, config):
|
| 794 |
+
super().__init__()
|
| 795 |
+
self.predictions = BertLMPredictionHead(config)
|
| 796 |
+
|
| 797 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
| 798 |
+
prediction_scores = self.predictions(sequence_output)
|
| 799 |
+
return prediction_scores
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
class BertOnlyNSPHead(nn.Module):
|
| 803 |
+
def __init__(self, config):
|
| 804 |
+
super().__init__()
|
| 805 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 806 |
+
|
| 807 |
+
def forward(self, pooled_output):
|
| 808 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 809 |
+
return seq_relationship_score
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
class BertPreTrainingHeads(nn.Module):
|
| 813 |
+
def __init__(self, config):
|
| 814 |
+
super().__init__()
|
| 815 |
+
self.predictions = BertLMPredictionHead(config)
|
| 816 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
| 817 |
+
|
| 818 |
+
def forward(self, sequence_output, pooled_output):
|
| 819 |
+
prediction_scores = self.predictions(sequence_output)
|
| 820 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 821 |
+
return prediction_scores, seq_relationship_score
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
class BertPreTrainedModel(PreTrainedModel):
|
| 825 |
+
"""
|
| 826 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 827 |
+
models.
|
| 828 |
+
"""
|
| 829 |
+
|
| 830 |
+
config_class = BertConfig
|
| 831 |
+
load_tf_weights = load_tf_weights_in_bert
|
| 832 |
+
base_model_prefix = "bert"
|
| 833 |
+
supports_gradient_checkpointing = True
|
| 834 |
+
_supports_sdpa = True
|
| 835 |
+
|
| 836 |
+
def _init_weights(self, module):
|
| 837 |
+
"""Initialize the weights"""
|
| 838 |
+
if isinstance(module, nn.Linear):
|
| 839 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 840 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 841 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 842 |
+
if module.bias is not None:
|
| 843 |
+
module.bias.data.zero_()
|
| 844 |
+
elif isinstance(module, nn.Embedding):
|
| 845 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 846 |
+
if module.padding_idx is not None:
|
| 847 |
+
module.weight.data[module.padding_idx].zero_()
|
| 848 |
+
elif isinstance(module, nn.LayerNorm):
|
| 849 |
+
module.bias.data.zero_()
|
| 850 |
+
module.weight.data.fill_(1.0)
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
@dataclass
|
| 854 |
+
class BertForPreTrainingOutput(ModelOutput):
|
| 855 |
+
"""
|
| 856 |
+
Output type of [`BertForPreTraining`].
|
| 857 |
+
|
| 858 |
+
Args:
|
| 859 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 860 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
| 861 |
+
(classification) loss.
|
| 862 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 863 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 864 |
+
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
|
| 865 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 866 |
+
before SoftMax).
|
| 867 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 868 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 869 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
| 870 |
+
|
| 871 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 872 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 873 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 874 |
+
sequence_length)`.
|
| 875 |
+
|
| 876 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 877 |
+
heads.
|
| 878 |
+
"""
|
| 879 |
+
|
| 880 |
+
loss: Optional[torch.FloatTensor] = None
|
| 881 |
+
prediction_logits: torch.FloatTensor = None
|
| 882 |
+
seq_relationship_logits: torch.FloatTensor = None
|
| 883 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 884 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
BERT_START_DOCSTRING = r"""
|
| 888 |
+
|
| 889 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 890 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 891 |
+
etc.)
|
| 892 |
+
|
| 893 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 894 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 895 |
+
and behavior.
|
| 896 |
+
|
| 897 |
+
Parameters:
|
| 898 |
+
config ([`BertConfig`]): Model configuration class with all the parameters of the model.
|
| 899 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 900 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 901 |
+
"""
|
| 902 |
+
|
| 903 |
+
BERT_INPUTS_DOCSTRING = r"""
|
| 904 |
+
Args:
|
| 905 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
| 906 |
+
Indices of input sequence tokens in the vocabulary.
|
| 907 |
+
|
| 908 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 909 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 910 |
+
|
| 911 |
+
[What are input IDs?](../glossary#input-ids)
|
| 912 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`or `(batch_size, sequence_length, target_length)`, *optional*):
|
| 913 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 914 |
+
|
| 915 |
+
- 1 for tokens that are **not masked**,
|
| 916 |
+
- 0 for tokens that are **masked**.
|
| 917 |
+
|
| 918 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 919 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 920 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 921 |
+
1]`:
|
| 922 |
+
|
| 923 |
+
- 0 corresponds to a *sentence A* token,
|
| 924 |
+
- 1 corresponds to a *sentence B* token.
|
| 925 |
+
|
| 926 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 927 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
| 928 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 929 |
+
config.max_position_embeddings - 1]`.
|
| 930 |
+
|
| 931 |
+
[What are position IDs?](../glossary#position-ids)
|
| 932 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 933 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 934 |
+
|
| 935 |
+
- 1 indicates the head is **not masked**,
|
| 936 |
+
- 0 indicates the head is **masked**.
|
| 937 |
+
|
| 938 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
| 939 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 940 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 941 |
+
model's internal embedding lookup matrix.
|
| 942 |
+
output_attentions (`bool`, *optional*):
|
| 943 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 944 |
+
tensors for more detail.
|
| 945 |
+
output_hidden_states (`bool`, *optional*):
|
| 946 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 947 |
+
more detail.
|
| 948 |
+
return_dict (`bool`, *optional*):
|
| 949 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 950 |
+
"""
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
@add_start_docstrings(
|
| 954 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 955 |
+
BERT_START_DOCSTRING,
|
| 956 |
+
)
|
| 957 |
+
class BertModel(BertPreTrainedModel):
|
| 958 |
+
"""
|
| 959 |
+
|
| 960 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 961 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 962 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 963 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
| 964 |
+
|
| 965 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
| 966 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
| 967 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
| 968 |
+
"""
|
| 969 |
+
|
| 970 |
+
_no_split_modules = ["BertEmbeddings", "BertLayer"]
|
| 971 |
+
|
| 972 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 973 |
+
super().__init__(config)
|
| 974 |
+
self.config = config
|
| 975 |
+
|
| 976 |
+
self.embeddings = BertEmbeddings(config)
|
| 977 |
+
self.encoder = BertEncoder(config)
|
| 978 |
+
|
| 979 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
| 980 |
+
|
| 981 |
+
self.attn_implementation = config._attn_implementation
|
| 982 |
+
self.position_embedding_type = config.position_embedding_type
|
| 983 |
+
|
| 984 |
+
# Initialize weights and apply final processing
|
| 985 |
+
self.post_init()
|
| 986 |
+
|
| 987 |
+
def get_input_embeddings(self):
|
| 988 |
+
return self.embeddings.word_embeddings
|
| 989 |
+
|
| 990 |
+
def set_input_embeddings(self, value):
|
| 991 |
+
self.embeddings.word_embeddings = value
|
| 992 |
+
|
| 993 |
+
def _prune_heads(self, heads_to_prune):
|
| 994 |
+
"""
|
| 995 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 996 |
+
class PreTrainedModel
|
| 997 |
+
"""
|
| 998 |
+
for layer, heads in heads_to_prune.items():
|
| 999 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 1000 |
+
|
| 1001 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1002 |
+
@add_code_sample_docstrings(
|
| 1003 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1004 |
+
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
|
| 1005 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1006 |
+
)
|
| 1007 |
+
def forward(
|
| 1008 |
+
self,
|
| 1009 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1010 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1011 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1012 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1013 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1014 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1015 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1016 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1017 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1018 |
+
use_cache: Optional[bool] = None,
|
| 1019 |
+
output_attentions: Optional[bool] = None,
|
| 1020 |
+
output_hidden_states: Optional[bool] = None,
|
| 1021 |
+
return_dict: Optional[bool] = None,
|
| 1022 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 1023 |
+
r"""
|
| 1024 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1025 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1026 |
+
the model is configured as a decoder.
|
| 1027 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, target_length)`, *optional*):
|
| 1028 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1029 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1030 |
+
|
| 1031 |
+
- 1 for tokens that are **not masked**,
|
| 1032 |
+
- 0 for tokens that are **masked**.
|
| 1033 |
+
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)`):
|
| 1034 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1035 |
+
|
| 1036 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1037 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1038 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1039 |
+
use_cache (`bool`, *optional*):
|
| 1040 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1041 |
+
`past_key_values`).
|
| 1042 |
+
"""
|
| 1043 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1044 |
+
output_hidden_states = (
|
| 1045 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1046 |
+
)
|
| 1047 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1048 |
+
|
| 1049 |
+
if self.config.is_decoder:
|
| 1050 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1051 |
+
else:
|
| 1052 |
+
use_cache = False
|
| 1053 |
+
|
| 1054 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1055 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1056 |
+
elif input_ids is not None:
|
| 1057 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 1058 |
+
input_shape = input_ids.size()
|
| 1059 |
+
elif inputs_embeds is not None:
|
| 1060 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1061 |
+
else:
|
| 1062 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1063 |
+
|
| 1064 |
+
batch_size, seq_length = input_shape
|
| 1065 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 1066 |
+
|
| 1067 |
+
# past_key_values_length
|
| 1068 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1069 |
+
|
| 1070 |
+
if token_type_ids is None:
|
| 1071 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
| 1072 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
| 1073 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
| 1074 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 1075 |
+
else:
|
| 1076 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
| 1077 |
+
|
| 1078 |
+
embedding_output = self.embeddings(
|
| 1079 |
+
input_ids=input_ids,
|
| 1080 |
+
position_ids=position_ids,
|
| 1081 |
+
token_type_ids=token_type_ids,
|
| 1082 |
+
inputs_embeds=inputs_embeds,
|
| 1083 |
+
past_key_values_length=past_key_values_length,
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
if attention_mask is None:
|
| 1087 |
+
attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
|
| 1088 |
+
|
| 1089 |
+
use_sdpa_attention_masks = (
|
| 1090 |
+
self.attn_implementation == "sdpa"
|
| 1091 |
+
and self.position_embedding_type == "absolute"
|
| 1092 |
+
and head_mask is None
|
| 1093 |
+
and not output_attentions
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
# Expand the attention mask
|
| 1097 |
+
if use_sdpa_attention_masks and attention_mask.dim() == 2:
|
| 1098 |
+
# Expand the attention mask for SDPA.
|
| 1099 |
+
# [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
|
| 1100 |
+
if self.config.is_decoder:
|
| 1101 |
+
extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
| 1102 |
+
attention_mask,
|
| 1103 |
+
input_shape,
|
| 1104 |
+
embedding_output,
|
| 1105 |
+
past_key_values_length,
|
| 1106 |
+
)
|
| 1107 |
+
else:
|
| 1108 |
+
extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
|
| 1109 |
+
attention_mask, embedding_output.dtype, tgt_len=seq_length
|
| 1110 |
+
)
|
| 1111 |
+
else:
|
| 1112 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 1113 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 1114 |
+
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
|
| 1115 |
+
|
| 1116 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 1117 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 1118 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
| 1119 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 1120 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 1121 |
+
if encoder_attention_mask is None:
|
| 1122 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 1123 |
+
|
| 1124 |
+
if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
|
| 1125 |
+
# Expand the attention mask for SDPA.
|
| 1126 |
+
# [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
|
| 1127 |
+
encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
|
| 1128 |
+
encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
|
| 1129 |
+
)
|
| 1130 |
+
else:
|
| 1131 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 1132 |
+
else:
|
| 1133 |
+
encoder_extended_attention_mask = None
|
| 1134 |
+
|
| 1135 |
+
# Prepare head mask if needed
|
| 1136 |
+
# 1.0 in head_mask indicate we keep the head
|
| 1137 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 1138 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 1139 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 1140 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 1141 |
+
|
| 1142 |
+
encoder_outputs = self.encoder(
|
| 1143 |
+
embedding_output,
|
| 1144 |
+
attention_mask=extended_attention_mask,
|
| 1145 |
+
head_mask=head_mask,
|
| 1146 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1147 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 1148 |
+
past_key_values=past_key_values,
|
| 1149 |
+
use_cache=use_cache,
|
| 1150 |
+
output_attentions=output_attentions,
|
| 1151 |
+
output_hidden_states=output_hidden_states,
|
| 1152 |
+
return_dict=return_dict,
|
| 1153 |
+
)
|
| 1154 |
+
sequence_output = encoder_outputs[0]
|
| 1155 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 1156 |
+
|
| 1157 |
+
if not return_dict:
|
| 1158 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 1159 |
+
|
| 1160 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 1161 |
+
last_hidden_state=sequence_output,
|
| 1162 |
+
pooler_output=pooled_output,
|
| 1163 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 1164 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1165 |
+
attentions=encoder_outputs.attentions,
|
| 1166 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
@add_start_docstrings(
|
| 1171 |
+
"""
|
| 1172 |
+
Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
|
| 1173 |
+
sentence prediction (classification)` head.
|
| 1174 |
+
""",
|
| 1175 |
+
BERT_START_DOCSTRING,
|
| 1176 |
+
)
|
| 1177 |
+
class BertForPreTraining(BertPreTrainedModel):
|
| 1178 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 1179 |
+
|
| 1180 |
+
def __init__(self, config):
|
| 1181 |
+
super().__init__(config)
|
| 1182 |
+
|
| 1183 |
+
self.bert = BertModel(config)
|
| 1184 |
+
self.cls = BertPreTrainingHeads(config)
|
| 1185 |
+
|
| 1186 |
+
# Initialize weights and apply final processing
|
| 1187 |
+
self.post_init()
|
| 1188 |
+
|
| 1189 |
+
def get_output_embeddings(self):
|
| 1190 |
+
return self.cls.predictions.decoder
|
| 1191 |
+
|
| 1192 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1193 |
+
self.cls.predictions.decoder = new_embeddings
|
| 1194 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 1195 |
+
|
| 1196 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1197 |
+
@replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 1198 |
+
def forward(
|
| 1199 |
+
self,
|
| 1200 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1201 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1202 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1203 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1204 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1205 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1206 |
+
labels: Optional[torch.Tensor] = None,
|
| 1207 |
+
next_sentence_label: Optional[torch.Tensor] = None,
|
| 1208 |
+
output_attentions: Optional[bool] = None,
|
| 1209 |
+
output_hidden_states: Optional[bool] = None,
|
| 1210 |
+
return_dict: Optional[bool] = None,
|
| 1211 |
+
) -> Union[Tuple[torch.Tensor], BertForPreTrainingOutput]:
|
| 1212 |
+
r"""
|
| 1213 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1214 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1215 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
|
| 1216 |
+
the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1217 |
+
next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1218 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
|
| 1219 |
+
pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
|
| 1220 |
+
|
| 1221 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
| 1222 |
+
- 1 indicates sequence B is a random sequence.
|
| 1223 |
+
kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
|
| 1224 |
+
Used to hide legacy arguments that have been deprecated.
|
| 1225 |
+
|
| 1226 |
+
Returns:
|
| 1227 |
+
|
| 1228 |
+
Example:
|
| 1229 |
+
|
| 1230 |
+
```python
|
| 1231 |
+
>>> from transformers import AutoTokenizer, BertForPreTraining
|
| 1232 |
+
>>> import torch
|
| 1233 |
+
|
| 1234 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 1235 |
+
>>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
|
| 1236 |
+
|
| 1237 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
| 1238 |
+
>>> outputs = model(**inputs)
|
| 1239 |
+
|
| 1240 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 1241 |
+
>>> seq_relationship_logits = outputs.seq_relationship_logits
|
| 1242 |
+
```
|
| 1243 |
+
"""
|
| 1244 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1245 |
+
|
| 1246 |
+
outputs = self.bert(
|
| 1247 |
+
input_ids,
|
| 1248 |
+
attention_mask=attention_mask,
|
| 1249 |
+
token_type_ids=token_type_ids,
|
| 1250 |
+
position_ids=position_ids,
|
| 1251 |
+
head_mask=head_mask,
|
| 1252 |
+
inputs_embeds=inputs_embeds,
|
| 1253 |
+
output_attentions=output_attentions,
|
| 1254 |
+
output_hidden_states=output_hidden_states,
|
| 1255 |
+
return_dict=return_dict,
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
sequence_output, pooled_output = outputs[:2]
|
| 1259 |
+
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
|
| 1260 |
+
|
| 1261 |
+
total_loss = None
|
| 1262 |
+
if labels is not None and next_sentence_label is not None:
|
| 1263 |
+
loss_fct = CrossEntropyLoss()
|
| 1264 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1265 |
+
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
|
| 1266 |
+
total_loss = masked_lm_loss + next_sentence_loss
|
| 1267 |
+
|
| 1268 |
+
if not return_dict:
|
| 1269 |
+
output = (prediction_scores, seq_relationship_score) + outputs[2:]
|
| 1270 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1271 |
+
|
| 1272 |
+
return BertForPreTrainingOutput(
|
| 1273 |
+
loss=total_loss,
|
| 1274 |
+
prediction_logits=prediction_scores,
|
| 1275 |
+
seq_relationship_logits=seq_relationship_score,
|
| 1276 |
+
hidden_states=outputs.hidden_states,
|
| 1277 |
+
attentions=outputs.attentions,
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
|
| 1281 |
+
@add_start_docstrings(
|
| 1282 |
+
"""Bert Model with a `language modeling` head on top for CLM fine-tuning.""", BERT_START_DOCSTRING
|
| 1283 |
+
)
|
| 1284 |
+
class BertLMHeadModel(BertPreTrainedModel, GenerationMixin):
|
| 1285 |
+
_tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 1286 |
+
|
| 1287 |
+
def __init__(self, config):
|
| 1288 |
+
super().__init__(config)
|
| 1289 |
+
|
| 1290 |
+
if not config.is_decoder:
|
| 1291 |
+
logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
| 1292 |
+
|
| 1293 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 1294 |
+
self.cls = BertOnlyMLMHead(config)
|
| 1295 |
+
|
| 1296 |
+
# Initialize weights and apply final processing
|
| 1297 |
+
self.post_init()
|
| 1298 |
+
|
| 1299 |
+
def get_output_embeddings(self):
|
| 1300 |
+
return self.cls.predictions.decoder
|
| 1301 |
+
|
| 1302 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1303 |
+
self.cls.predictions.decoder = new_embeddings
|
| 1304 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 1305 |
+
|
| 1306 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1307 |
+
@add_code_sample_docstrings(
|
| 1308 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1309 |
+
output_type=CausalLMOutputWithCrossAttentions,
|
| 1310 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1311 |
+
)
|
| 1312 |
+
def forward(
|
| 1313 |
+
self,
|
| 1314 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1315 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1316 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1317 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1318 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1319 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1320 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1321 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1322 |
+
labels: Optional[torch.Tensor] = None,
|
| 1323 |
+
past_key_values: Optional[List[torch.Tensor]] = None,
|
| 1324 |
+
use_cache: Optional[bool] = None,
|
| 1325 |
+
output_attentions: Optional[bool] = None,
|
| 1326 |
+
output_hidden_states: Optional[bool] = None,
|
| 1327 |
+
return_dict: Optional[bool] = None,
|
| 1328 |
+
**loss_kwargs,
|
| 1329 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
| 1330 |
+
r"""
|
| 1331 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1332 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1333 |
+
the model is configured as a decoder.
|
| 1334 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1335 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1336 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1337 |
+
|
| 1338 |
+
- 1 for tokens that are **not masked**,
|
| 1339 |
+
- 0 for tokens that are **masked**.
|
| 1340 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1341 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 1342 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 1343 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
|
| 1344 |
+
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)`):
|
| 1345 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1346 |
+
|
| 1347 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1348 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1349 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1350 |
+
use_cache (`bool`, *optional*):
|
| 1351 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1352 |
+
`past_key_values`).
|
| 1353 |
+
"""
|
| 1354 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1355 |
+
if labels is not None:
|
| 1356 |
+
use_cache = False
|
| 1357 |
+
|
| 1358 |
+
outputs = self.bert(
|
| 1359 |
+
input_ids,
|
| 1360 |
+
attention_mask=attention_mask,
|
| 1361 |
+
token_type_ids=token_type_ids,
|
| 1362 |
+
position_ids=position_ids,
|
| 1363 |
+
head_mask=head_mask,
|
| 1364 |
+
inputs_embeds=inputs_embeds,
|
| 1365 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1366 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1367 |
+
past_key_values=past_key_values,
|
| 1368 |
+
use_cache=use_cache,
|
| 1369 |
+
output_attentions=output_attentions,
|
| 1370 |
+
output_hidden_states=output_hidden_states,
|
| 1371 |
+
return_dict=return_dict,
|
| 1372 |
+
)
|
| 1373 |
+
|
| 1374 |
+
sequence_output = outputs[0]
|
| 1375 |
+
prediction_scores = self.cls(sequence_output)
|
| 1376 |
+
|
| 1377 |
+
lm_loss = None
|
| 1378 |
+
if labels is not None:
|
| 1379 |
+
lm_loss = self.loss_function(prediction_scores, labels, self.config.vocab_size, **loss_kwargs)
|
| 1380 |
+
|
| 1381 |
+
if not return_dict:
|
| 1382 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1383 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
| 1384 |
+
|
| 1385 |
+
return CausalLMOutputWithCrossAttentions(
|
| 1386 |
+
loss=lm_loss,
|
| 1387 |
+
logits=prediction_scores,
|
| 1388 |
+
past_key_values=outputs.past_key_values,
|
| 1389 |
+
hidden_states=outputs.hidden_states,
|
| 1390 |
+
attentions=outputs.attentions,
|
| 1391 |
+
cross_attentions=outputs.cross_attentions,
|
| 1392 |
+
)
|
| 1393 |
+
|
| 1394 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 1395 |
+
reordered_past = ()
|
| 1396 |
+
for layer_past in past_key_values:
|
| 1397 |
+
reordered_past += (
|
| 1398 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 1399 |
+
)
|
| 1400 |
+
return reordered_past
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
@add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
|
| 1404 |
+
class BertForMaskedLM(BertPreTrainedModel):
|
| 1405 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 1406 |
+
|
| 1407 |
+
def __init__(self, config):
|
| 1408 |
+
super().__init__(config)
|
| 1409 |
+
|
| 1410 |
+
if config.is_decoder:
|
| 1411 |
+
logger.warning(
|
| 1412 |
+
"If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
|
| 1413 |
+
"bi-directional self-attention."
|
| 1414 |
+
)
|
| 1415 |
+
|
| 1416 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 1417 |
+
self.cls = BertOnlyMLMHead(config)
|
| 1418 |
+
|
| 1419 |
+
# Initialize weights and apply final processing
|
| 1420 |
+
self.post_init()
|
| 1421 |
+
|
| 1422 |
+
def get_output_embeddings(self):
|
| 1423 |
+
return self.cls.predictions.decoder
|
| 1424 |
+
|
| 1425 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1426 |
+
self.cls.predictions.decoder = new_embeddings
|
| 1427 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 1428 |
+
|
| 1429 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1430 |
+
@add_code_sample_docstrings(
|
| 1431 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1432 |
+
output_type=MaskedLMOutput,
|
| 1433 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1434 |
+
expected_output="'paris'",
|
| 1435 |
+
expected_loss=0.88,
|
| 1436 |
+
)
|
| 1437 |
+
def forward(
|
| 1438 |
+
self,
|
| 1439 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1440 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1441 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1442 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1443 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1444 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1445 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 1446 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 1447 |
+
labels: Optional[torch.Tensor] = None,
|
| 1448 |
+
output_attentions: Optional[bool] = None,
|
| 1449 |
+
output_hidden_states: Optional[bool] = None,
|
| 1450 |
+
return_dict: Optional[bool] = None,
|
| 1451 |
+
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
|
| 1452 |
+
r"""
|
| 1453 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1454 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1455 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1456 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1457 |
+
"""
|
| 1458 |
+
|
| 1459 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1460 |
+
|
| 1461 |
+
outputs = self.bert(
|
| 1462 |
+
input_ids,
|
| 1463 |
+
attention_mask=attention_mask,
|
| 1464 |
+
token_type_ids=token_type_ids,
|
| 1465 |
+
position_ids=position_ids,
|
| 1466 |
+
head_mask=head_mask,
|
| 1467 |
+
inputs_embeds=inputs_embeds,
|
| 1468 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1469 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1470 |
+
output_attentions=output_attentions,
|
| 1471 |
+
output_hidden_states=output_hidden_states,
|
| 1472 |
+
return_dict=return_dict,
|
| 1473 |
+
)
|
| 1474 |
+
|
| 1475 |
+
sequence_output = outputs[0]
|
| 1476 |
+
prediction_scores = self.cls(sequence_output)
|
| 1477 |
+
|
| 1478 |
+
masked_lm_loss = None
|
| 1479 |
+
if labels is not None:
|
| 1480 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
| 1481 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1482 |
+
|
| 1483 |
+
if not return_dict:
|
| 1484 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1485 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1486 |
+
|
| 1487 |
+
return MaskedLMOutput(
|
| 1488 |
+
loss=masked_lm_loss,
|
| 1489 |
+
logits=prediction_scores,
|
| 1490 |
+
hidden_states=outputs.hidden_states,
|
| 1491 |
+
attentions=outputs.attentions,
|
| 1492 |
+
)
|
| 1493 |
+
|
| 1494 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
|
| 1495 |
+
input_shape = input_ids.shape
|
| 1496 |
+
effective_batch_size = input_shape[0]
|
| 1497 |
+
|
| 1498 |
+
# add a dummy token
|
| 1499 |
+
if self.config.pad_token_id is None:
|
| 1500 |
+
raise ValueError("The PAD token should be defined for generation")
|
| 1501 |
+
|
| 1502 |
+
attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
|
| 1503 |
+
dummy_token = torch.full(
|
| 1504 |
+
(effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
|
| 1505 |
+
)
|
| 1506 |
+
input_ids = torch.cat([input_ids, dummy_token], dim=1)
|
| 1507 |
+
|
| 1508 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 1509 |
+
|
| 1510 |
+
|
| 1511 |
+
@add_start_docstrings(
|
| 1512 |
+
"""Bert Model with a `next sentence prediction (classification)` head on top.""",
|
| 1513 |
+
BERT_START_DOCSTRING,
|
| 1514 |
+
)
|
| 1515 |
+
class BertForNextSentencePrediction(BertPreTrainedModel):
|
| 1516 |
+
def __init__(self, config):
|
| 1517 |
+
super().__init__(config)
|
| 1518 |
+
|
| 1519 |
+
self.bert = BertModel(config)
|
| 1520 |
+
self.cls = BertOnlyNSPHead(config)
|
| 1521 |
+
|
| 1522 |
+
# Initialize weights and apply final processing
|
| 1523 |
+
self.post_init()
|
| 1524 |
+
|
| 1525 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1526 |
+
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
|
| 1527 |
+
def forward(
|
| 1528 |
+
self,
|
| 1529 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1530 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1531 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1532 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1533 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1534 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1535 |
+
labels: Optional[torch.Tensor] = None,
|
| 1536 |
+
output_attentions: Optional[bool] = None,
|
| 1537 |
+
output_hidden_states: Optional[bool] = None,
|
| 1538 |
+
return_dict: Optional[bool] = None,
|
| 1539 |
+
**kwargs,
|
| 1540 |
+
) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
|
| 1541 |
+
r"""
|
| 1542 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1543 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
| 1544 |
+
(see `input_ids` docstring). Indices should be in `[0, 1]`:
|
| 1545 |
+
|
| 1546 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
| 1547 |
+
- 1 indicates sequence B is a random sequence.
|
| 1548 |
+
|
| 1549 |
+
Returns:
|
| 1550 |
+
|
| 1551 |
+
Example:
|
| 1552 |
+
|
| 1553 |
+
```python
|
| 1554 |
+
>>> from transformers import AutoTokenizer, BertForNextSentencePrediction
|
| 1555 |
+
>>> import torch
|
| 1556 |
+
|
| 1557 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 1558 |
+
>>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
|
| 1559 |
+
|
| 1560 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 1561 |
+
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
|
| 1562 |
+
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
|
| 1563 |
+
|
| 1564 |
+
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
|
| 1565 |
+
>>> logits = outputs.logits
|
| 1566 |
+
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
|
| 1567 |
+
```
|
| 1568 |
+
"""
|
| 1569 |
+
|
| 1570 |
+
if "next_sentence_label" in kwargs:
|
| 1571 |
+
warnings.warn(
|
| 1572 |
+
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
|
| 1573 |
+
" `labels` instead.",
|
| 1574 |
+
FutureWarning,
|
| 1575 |
+
)
|
| 1576 |
+
labels = kwargs.pop("next_sentence_label")
|
| 1577 |
+
|
| 1578 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1579 |
+
|
| 1580 |
+
outputs = self.bert(
|
| 1581 |
+
input_ids,
|
| 1582 |
+
attention_mask=attention_mask,
|
| 1583 |
+
token_type_ids=token_type_ids,
|
| 1584 |
+
position_ids=position_ids,
|
| 1585 |
+
head_mask=head_mask,
|
| 1586 |
+
inputs_embeds=inputs_embeds,
|
| 1587 |
+
output_attentions=output_attentions,
|
| 1588 |
+
output_hidden_states=output_hidden_states,
|
| 1589 |
+
return_dict=return_dict,
|
| 1590 |
+
)
|
| 1591 |
+
|
| 1592 |
+
pooled_output = outputs[1]
|
| 1593 |
+
|
| 1594 |
+
seq_relationship_scores = self.cls(pooled_output)
|
| 1595 |
+
|
| 1596 |
+
next_sentence_loss = None
|
| 1597 |
+
if labels is not None:
|
| 1598 |
+
loss_fct = CrossEntropyLoss()
|
| 1599 |
+
next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
|
| 1600 |
+
|
| 1601 |
+
if not return_dict:
|
| 1602 |
+
output = (seq_relationship_scores,) + outputs[2:]
|
| 1603 |
+
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
|
| 1604 |
+
|
| 1605 |
+
return NextSentencePredictorOutput(
|
| 1606 |
+
loss=next_sentence_loss,
|
| 1607 |
+
logits=seq_relationship_scores,
|
| 1608 |
+
hidden_states=outputs.hidden_states,
|
| 1609 |
+
attentions=outputs.attentions,
|
| 1610 |
+
)
|
| 1611 |
+
|
| 1612 |
+
|
| 1613 |
+
@add_start_docstrings(
|
| 1614 |
+
"""
|
| 1615 |
+
Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1616 |
+
output) e.g. for GLUE tasks.
|
| 1617 |
+
""",
|
| 1618 |
+
BERT_START_DOCSTRING,
|
| 1619 |
+
)
|
| 1620 |
+
class BertForSequenceClassification(BertPreTrainedModel):
|
| 1621 |
+
def __init__(self, config):
|
| 1622 |
+
super().__init__(config)
|
| 1623 |
+
self.num_labels = config.num_labels
|
| 1624 |
+
self.config = config
|
| 1625 |
+
|
| 1626 |
+
self.bert = BertModel(config)
|
| 1627 |
+
classifier_dropout = (
|
| 1628 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1629 |
+
)
|
| 1630 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1631 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1632 |
+
|
| 1633 |
+
# Initialize weights and apply final processing
|
| 1634 |
+
self.post_init()
|
| 1635 |
+
|
| 1636 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1637 |
+
@add_code_sample_docstrings(
|
| 1638 |
+
checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
|
| 1639 |
+
output_type=SequenceClassifierOutput,
|
| 1640 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1641 |
+
expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
|
| 1642 |
+
expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
|
| 1643 |
+
)
|
| 1644 |
+
def forward(
|
| 1645 |
+
self,
|
| 1646 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1647 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1648 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1649 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1650 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1651 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1652 |
+
labels: Optional[torch.Tensor] = None,
|
| 1653 |
+
output_attentions: Optional[bool] = None,
|
| 1654 |
+
output_hidden_states: Optional[bool] = None,
|
| 1655 |
+
return_dict: Optional[bool] = None,
|
| 1656 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
|
| 1657 |
+
r"""
|
| 1658 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1659 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1660 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1661 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1662 |
+
"""
|
| 1663 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1664 |
+
|
| 1665 |
+
outputs = self.bert(
|
| 1666 |
+
input_ids,
|
| 1667 |
+
attention_mask=attention_mask,
|
| 1668 |
+
token_type_ids=token_type_ids,
|
| 1669 |
+
position_ids=position_ids,
|
| 1670 |
+
head_mask=head_mask,
|
| 1671 |
+
inputs_embeds=inputs_embeds,
|
| 1672 |
+
output_attentions=output_attentions,
|
| 1673 |
+
output_hidden_states=output_hidden_states,
|
| 1674 |
+
return_dict=return_dict,
|
| 1675 |
+
)
|
| 1676 |
+
|
| 1677 |
+
pooled_output = outputs[1]
|
| 1678 |
+
|
| 1679 |
+
pooled_output = self.dropout(pooled_output)
|
| 1680 |
+
logits = self.classifier(pooled_output)
|
| 1681 |
+
|
| 1682 |
+
loss = None
|
| 1683 |
+
if labels is not None:
|
| 1684 |
+
if self.config.problem_type is None:
|
| 1685 |
+
if self.num_labels == 1:
|
| 1686 |
+
self.config.problem_type = "regression"
|
| 1687 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1688 |
+
self.config.problem_type = "single_label_classification"
|
| 1689 |
+
else:
|
| 1690 |
+
self.config.problem_type = "multi_label_classification"
|
| 1691 |
+
|
| 1692 |
+
if self.config.problem_type == "regression":
|
| 1693 |
+
loss_fct = MSELoss()
|
| 1694 |
+
if self.num_labels == 1:
|
| 1695 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1696 |
+
else:
|
| 1697 |
+
loss = loss_fct(logits, labels)
|
| 1698 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1699 |
+
loss_fct = CrossEntropyLoss()
|
| 1700 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1701 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1702 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1703 |
+
loss = loss_fct(logits, labels)
|
| 1704 |
+
if not return_dict:
|
| 1705 |
+
output = (logits,) + outputs[2:]
|
| 1706 |
+
return ((loss,) + output) if loss is not None else output
|
| 1707 |
+
|
| 1708 |
+
return SequenceClassifierOutput(
|
| 1709 |
+
loss=loss,
|
| 1710 |
+
logits=logits,
|
| 1711 |
+
hidden_states=outputs.hidden_states,
|
| 1712 |
+
attentions=outputs.attentions,
|
| 1713 |
+
)
|
| 1714 |
+
|
| 1715 |
+
|
| 1716 |
+
@add_start_docstrings(
|
| 1717 |
+
"""
|
| 1718 |
+
Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1719 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1720 |
+
""",
|
| 1721 |
+
BERT_START_DOCSTRING,
|
| 1722 |
+
)
|
| 1723 |
+
class BertForMultipleChoice(BertPreTrainedModel):
|
| 1724 |
+
def __init__(self, config):
|
| 1725 |
+
super().__init__(config)
|
| 1726 |
+
|
| 1727 |
+
self.bert = BertModel(config)
|
| 1728 |
+
classifier_dropout = (
|
| 1729 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1730 |
+
)
|
| 1731 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1732 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1733 |
+
|
| 1734 |
+
# Initialize weights and apply final processing
|
| 1735 |
+
self.post_init()
|
| 1736 |
+
|
| 1737 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 1738 |
+
@add_code_sample_docstrings(
|
| 1739 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1740 |
+
output_type=MultipleChoiceModelOutput,
|
| 1741 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1742 |
+
)
|
| 1743 |
+
def forward(
|
| 1744 |
+
self,
|
| 1745 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1746 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1747 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1748 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1749 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1750 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1751 |
+
labels: Optional[torch.Tensor] = None,
|
| 1752 |
+
output_attentions: Optional[bool] = None,
|
| 1753 |
+
output_hidden_states: Optional[bool] = None,
|
| 1754 |
+
return_dict: Optional[bool] = None,
|
| 1755 |
+
) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
|
| 1756 |
+
r"""
|
| 1757 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1758 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
| 1759 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
| 1760 |
+
`input_ids` above)
|
| 1761 |
+
"""
|
| 1762 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1763 |
+
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
| 1764 |
+
|
| 1765 |
+
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
| 1766 |
+
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 1767 |
+
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
|
| 1768 |
+
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
|
| 1769 |
+
inputs_embeds = (
|
| 1770 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
| 1771 |
+
if inputs_embeds is not None
|
| 1772 |
+
else None
|
| 1773 |
+
)
|
| 1774 |
+
|
| 1775 |
+
outputs = self.bert(
|
| 1776 |
+
input_ids,
|
| 1777 |
+
attention_mask=attention_mask,
|
| 1778 |
+
token_type_ids=token_type_ids,
|
| 1779 |
+
position_ids=position_ids,
|
| 1780 |
+
head_mask=head_mask,
|
| 1781 |
+
inputs_embeds=inputs_embeds,
|
| 1782 |
+
output_attentions=output_attentions,
|
| 1783 |
+
output_hidden_states=output_hidden_states,
|
| 1784 |
+
return_dict=return_dict,
|
| 1785 |
+
)
|
| 1786 |
+
|
| 1787 |
+
pooled_output = outputs[1]
|
| 1788 |
+
|
| 1789 |
+
pooled_output = self.dropout(pooled_output)
|
| 1790 |
+
logits = self.classifier(pooled_output)
|
| 1791 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 1792 |
+
|
| 1793 |
+
loss = None
|
| 1794 |
+
if labels is not None:
|
| 1795 |
+
loss_fct = CrossEntropyLoss()
|
| 1796 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 1797 |
+
|
| 1798 |
+
if not return_dict:
|
| 1799 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1800 |
+
return ((loss,) + output) if loss is not None else output
|
| 1801 |
+
|
| 1802 |
+
return MultipleChoiceModelOutput(
|
| 1803 |
+
loss=loss,
|
| 1804 |
+
logits=reshaped_logits,
|
| 1805 |
+
hidden_states=outputs.hidden_states,
|
| 1806 |
+
attentions=outputs.attentions,
|
| 1807 |
+
)
|
| 1808 |
+
|
| 1809 |
+
|
| 1810 |
+
@add_start_docstrings(
|
| 1811 |
+
"""
|
| 1812 |
+
Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1813 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1814 |
+
""",
|
| 1815 |
+
BERT_START_DOCSTRING,
|
| 1816 |
+
)
|
| 1817 |
+
class BertForTokenClassification(BertPreTrainedModel):
|
| 1818 |
+
def __init__(self, config):
|
| 1819 |
+
super().__init__(config)
|
| 1820 |
+
self.num_labels = config.num_labels
|
| 1821 |
+
|
| 1822 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 1823 |
+
classifier_dropout = (
|
| 1824 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1825 |
+
)
|
| 1826 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1827 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1828 |
+
|
| 1829 |
+
# Initialize weights and apply final processing
|
| 1830 |
+
self.post_init()
|
| 1831 |
+
|
| 1832 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1833 |
+
@add_code_sample_docstrings(
|
| 1834 |
+
checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
|
| 1835 |
+
output_type=TokenClassifierOutput,
|
| 1836 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1837 |
+
expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
|
| 1838 |
+
expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
|
| 1839 |
+
)
|
| 1840 |
+
def forward(
|
| 1841 |
+
self,
|
| 1842 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1843 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1844 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1845 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1846 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1847 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1848 |
+
labels: Optional[torch.Tensor] = None,
|
| 1849 |
+
output_attentions: Optional[bool] = None,
|
| 1850 |
+
output_hidden_states: Optional[bool] = None,
|
| 1851 |
+
return_dict: Optional[bool] = None,
|
| 1852 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
| 1853 |
+
r"""
|
| 1854 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1855 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1856 |
+
"""
|
| 1857 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1858 |
+
|
| 1859 |
+
outputs = self.bert(
|
| 1860 |
+
input_ids,
|
| 1861 |
+
attention_mask=attention_mask,
|
| 1862 |
+
token_type_ids=token_type_ids,
|
| 1863 |
+
position_ids=position_ids,
|
| 1864 |
+
head_mask=head_mask,
|
| 1865 |
+
inputs_embeds=inputs_embeds,
|
| 1866 |
+
output_attentions=output_attentions,
|
| 1867 |
+
output_hidden_states=output_hidden_states,
|
| 1868 |
+
return_dict=return_dict,
|
| 1869 |
+
)
|
| 1870 |
+
|
| 1871 |
+
sequence_output = outputs[0]
|
| 1872 |
+
|
| 1873 |
+
sequence_output = self.dropout(sequence_output)
|
| 1874 |
+
logits = self.classifier(sequence_output)
|
| 1875 |
+
|
| 1876 |
+
loss = None
|
| 1877 |
+
if labels is not None:
|
| 1878 |
+
loss_fct = CrossEntropyLoss()
|
| 1879 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1880 |
+
|
| 1881 |
+
if not return_dict:
|
| 1882 |
+
output = (logits,) + outputs[2:]
|
| 1883 |
+
return ((loss,) + output) if loss is not None else output
|
| 1884 |
+
|
| 1885 |
+
return TokenClassifierOutput(
|
| 1886 |
+
loss=loss,
|
| 1887 |
+
logits=logits,
|
| 1888 |
+
hidden_states=outputs.hidden_states,
|
| 1889 |
+
attentions=outputs.attentions,
|
| 1890 |
+
)
|
| 1891 |
+
|
| 1892 |
+
|
| 1893 |
+
@add_start_docstrings(
|
| 1894 |
+
"""
|
| 1895 |
+
Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1896 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1897 |
+
""",
|
| 1898 |
+
BERT_START_DOCSTRING,
|
| 1899 |
+
)
|
| 1900 |
+
class BertForQuestionAnswering(BertPreTrainedModel):
|
| 1901 |
+
def __init__(self, config):
|
| 1902 |
+
super().__init__(config)
|
| 1903 |
+
self.num_labels = config.num_labels
|
| 1904 |
+
|
| 1905 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 1906 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1907 |
+
|
| 1908 |
+
# Initialize weights and apply final processing
|
| 1909 |
+
self.post_init()
|
| 1910 |
+
|
| 1911 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1912 |
+
@add_code_sample_docstrings(
|
| 1913 |
+
checkpoint=_CHECKPOINT_FOR_QA,
|
| 1914 |
+
output_type=QuestionAnsweringModelOutput,
|
| 1915 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1916 |
+
qa_target_start_index=_QA_TARGET_START_INDEX,
|
| 1917 |
+
qa_target_end_index=_QA_TARGET_END_INDEX,
|
| 1918 |
+
expected_output=_QA_EXPECTED_OUTPUT,
|
| 1919 |
+
expected_loss=_QA_EXPECTED_LOSS,
|
| 1920 |
+
)
|
| 1921 |
+
def forward(
|
| 1922 |
+
self,
|
| 1923 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1924 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1925 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 1926 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1927 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1928 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 1929 |
+
start_positions: Optional[torch.Tensor] = None,
|
| 1930 |
+
end_positions: Optional[torch.Tensor] = None,
|
| 1931 |
+
output_attentions: Optional[bool] = None,
|
| 1932 |
+
output_hidden_states: Optional[bool] = None,
|
| 1933 |
+
return_dict: Optional[bool] = None,
|
| 1934 |
+
) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
|
| 1935 |
+
r"""
|
| 1936 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1937 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1938 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1939 |
+
are not taken into account for computing the loss.
|
| 1940 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1941 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1942 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1943 |
+
are not taken into account for computing the loss.
|
| 1944 |
+
"""
|
| 1945 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1946 |
+
|
| 1947 |
+
outputs = self.bert(
|
| 1948 |
+
input_ids,
|
| 1949 |
+
attention_mask=attention_mask,
|
| 1950 |
+
token_type_ids=token_type_ids,
|
| 1951 |
+
position_ids=position_ids,
|
| 1952 |
+
head_mask=head_mask,
|
| 1953 |
+
inputs_embeds=inputs_embeds,
|
| 1954 |
+
output_attentions=output_attentions,
|
| 1955 |
+
output_hidden_states=output_hidden_states,
|
| 1956 |
+
return_dict=return_dict,
|
| 1957 |
+
)
|
| 1958 |
+
|
| 1959 |
+
sequence_output = outputs[0]
|
| 1960 |
+
|
| 1961 |
+
logits = self.qa_outputs(sequence_output)
|
| 1962 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1963 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1964 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1965 |
+
|
| 1966 |
+
total_loss = None
|
| 1967 |
+
if start_positions is not None and end_positions is not None:
|
| 1968 |
+
# If we are on multi-GPU, split add a dimension
|
| 1969 |
+
if len(start_positions.size()) > 1:
|
| 1970 |
+
start_positions = start_positions.squeeze(-1)
|
| 1971 |
+
if len(end_positions.size()) > 1:
|
| 1972 |
+
end_positions = end_positions.squeeze(-1)
|
| 1973 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1974 |
+
ignored_index = start_logits.size(1)
|
| 1975 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1976 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1977 |
+
|
| 1978 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1979 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1980 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1981 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1982 |
+
|
| 1983 |
+
if not return_dict:
|
| 1984 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 1985 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1986 |
+
|
| 1987 |
+
return QuestionAnsweringModelOutput(
|
| 1988 |
+
loss=total_loss,
|
| 1989 |
+
start_logits=start_logits,
|
| 1990 |
+
end_logits=end_logits,
|
| 1991 |
+
hidden_states=outputs.hidden_states,
|
| 1992 |
+
attentions=outputs.attentions,
|
| 1993 |
+
)
|
| 1994 |
+
|
| 1995 |
+
|
| 1996 |
+
__all__ = [
|
| 1997 |
+
"BertForMaskedLM",
|
| 1998 |
+
"BertForMultipleChoice",
|
| 1999 |
+
"BertForNextSentencePrediction",
|
| 2000 |
+
"BertForPreTraining",
|
| 2001 |
+
"BertForQuestionAnswering",
|
| 2002 |
+
"BertForSequenceClassification",
|
| 2003 |
+
"BertForTokenClassification",
|
| 2004 |
+
"BertLayer",
|
| 2005 |
+
"BertLMHeadModel",
|
| 2006 |
+
"BertModel",
|
| 2007 |
+
"BertPreTrainedModel",
|
| 2008 |
+
"load_tf_weights_in_bert",
|
| 2009 |
+
]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/modeling_flax_bert.py
ADDED
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The Google Flax Team Authors and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from typing import Callable, Optional, Tuple
|
| 17 |
+
|
| 18 |
+
import flax
|
| 19 |
+
import flax.linen as nn
|
| 20 |
+
import jax
|
| 21 |
+
import jax.numpy as jnp
|
| 22 |
+
import numpy as np
|
| 23 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 24 |
+
from flax.linen import combine_masks, make_causal_mask
|
| 25 |
+
from flax.linen import partitioning as nn_partitioning
|
| 26 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 27 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 28 |
+
from jax import lax
|
| 29 |
+
|
| 30 |
+
from ...modeling_flax_outputs import (
|
| 31 |
+
FlaxBaseModelOutputWithPastAndCrossAttentions,
|
| 32 |
+
FlaxBaseModelOutputWithPooling,
|
| 33 |
+
FlaxBaseModelOutputWithPoolingAndCrossAttentions,
|
| 34 |
+
FlaxCausalLMOutputWithCrossAttentions,
|
| 35 |
+
FlaxMaskedLMOutput,
|
| 36 |
+
FlaxMultipleChoiceModelOutput,
|
| 37 |
+
FlaxNextSentencePredictorOutput,
|
| 38 |
+
FlaxQuestionAnsweringModelOutput,
|
| 39 |
+
FlaxSequenceClassifierOutput,
|
| 40 |
+
FlaxTokenClassifierOutput,
|
| 41 |
+
)
|
| 42 |
+
from ...modeling_flax_utils import (
|
| 43 |
+
ACT2FN,
|
| 44 |
+
FlaxPreTrainedModel,
|
| 45 |
+
append_call_sample_docstring,
|
| 46 |
+
append_replace_return_docstrings,
|
| 47 |
+
overwrite_call_docstring,
|
| 48 |
+
)
|
| 49 |
+
from ...utils import ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 50 |
+
from .configuration_bert import BertConfig
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
_CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
|
| 56 |
+
_CONFIG_FOR_DOC = "BertConfig"
|
| 57 |
+
|
| 58 |
+
remat = nn_partitioning.remat
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@flax.struct.dataclass
|
| 62 |
+
class FlaxBertForPreTrainingOutput(ModelOutput):
|
| 63 |
+
"""
|
| 64 |
+
Output type of [`BertForPreTraining`].
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
prediction_logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 68 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 69 |
+
seq_relationship_logits (`jnp.ndarray` of shape `(batch_size, 2)`):
|
| 70 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 71 |
+
before SoftMax).
|
| 72 |
+
hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 73 |
+
Tuple of `jnp.ndarray` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 74 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 75 |
+
|
| 76 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 77 |
+
attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 78 |
+
Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 79 |
+
sequence_length)`.
|
| 80 |
+
|
| 81 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 82 |
+
heads.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
prediction_logits: jnp.ndarray = None
|
| 86 |
+
seq_relationship_logits: jnp.ndarray = None
|
| 87 |
+
hidden_states: Optional[Tuple[jnp.ndarray]] = None
|
| 88 |
+
attentions: Optional[Tuple[jnp.ndarray]] = None
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
BERT_START_DOCSTRING = r"""
|
| 92 |
+
|
| 93 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 94 |
+
library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
|
| 95 |
+
|
| 96 |
+
This model is also a
|
| 97 |
+
[flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
|
| 98 |
+
a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
|
| 99 |
+
behavior.
|
| 100 |
+
|
| 101 |
+
Finally, this model supports inherent JAX features such as:
|
| 102 |
+
|
| 103 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 104 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 105 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 106 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 107 |
+
|
| 108 |
+
Parameters:
|
| 109 |
+
config ([`BertConfig`]): Model configuration class with all the parameters of the model.
|
| 110 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 111 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 112 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 113 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 114 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 115 |
+
|
| 116 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 117 |
+
specified all the computation will be performed with the given `dtype`.
|
| 118 |
+
|
| 119 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 120 |
+
parameters.**
|
| 121 |
+
|
| 122 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 123 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 124 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 125 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 126 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 127 |
+
|
| 128 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 129 |
+
specified all the computation will be performed with the given `dtype`.
|
| 130 |
+
|
| 131 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 132 |
+
parameters.**
|
| 133 |
+
|
| 134 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 135 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
BERT_INPUTS_DOCSTRING = r"""
|
| 140 |
+
Args:
|
| 141 |
+
input_ids (`numpy.ndarray` of shape `({0})`):
|
| 142 |
+
Indices of input sequence tokens in the vocabulary.
|
| 143 |
+
|
| 144 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 145 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 146 |
+
|
| 147 |
+
[What are input IDs?](../glossary#input-ids)
|
| 148 |
+
attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 149 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 150 |
+
|
| 151 |
+
- 1 for tokens that are **not masked**,
|
| 152 |
+
- 0 for tokens that are **masked**.
|
| 153 |
+
|
| 154 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 155 |
+
token_type_ids (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 156 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 157 |
+
1]`:
|
| 158 |
+
|
| 159 |
+
- 0 corresponds to a *sentence A* token,
|
| 160 |
+
- 1 corresponds to a *sentence B* token.
|
| 161 |
+
|
| 162 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 163 |
+
position_ids (`numpy.ndarray` of shape `({0})`, *optional*):
|
| 164 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 165 |
+
config.max_position_embeddings - 1]`.
|
| 166 |
+
head_mask (`numpy.ndarray` of shape `({0})`, `optional):
|
| 167 |
+
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
|
| 168 |
+
|
| 169 |
+
- 1 indicates the head is **not masked**,
|
| 170 |
+
- 0 indicates the head is **masked**.
|
| 171 |
+
|
| 172 |
+
return_dict (`bool`, *optional*):
|
| 173 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 174 |
+
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class FlaxBertEmbeddings(nn.Module):
|
| 179 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 180 |
+
|
| 181 |
+
config: BertConfig
|
| 182 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 183 |
+
|
| 184 |
+
def setup(self):
|
| 185 |
+
self.word_embeddings = nn.Embed(
|
| 186 |
+
self.config.vocab_size,
|
| 187 |
+
self.config.hidden_size,
|
| 188 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 189 |
+
dtype=self.dtype,
|
| 190 |
+
)
|
| 191 |
+
self.position_embeddings = nn.Embed(
|
| 192 |
+
self.config.max_position_embeddings,
|
| 193 |
+
self.config.hidden_size,
|
| 194 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 195 |
+
dtype=self.dtype,
|
| 196 |
+
)
|
| 197 |
+
self.token_type_embeddings = nn.Embed(
|
| 198 |
+
self.config.type_vocab_size,
|
| 199 |
+
self.config.hidden_size,
|
| 200 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 201 |
+
dtype=self.dtype,
|
| 202 |
+
)
|
| 203 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 204 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 205 |
+
|
| 206 |
+
def __call__(self, input_ids, token_type_ids, position_ids, attention_mask, deterministic: bool = True):
|
| 207 |
+
# Embed
|
| 208 |
+
inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
|
| 209 |
+
position_embeds = self.position_embeddings(position_ids.astype("i4"))
|
| 210 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
|
| 211 |
+
|
| 212 |
+
# Sum all embeddings
|
| 213 |
+
hidden_states = inputs_embeds + token_type_embeddings + position_embeds
|
| 214 |
+
|
| 215 |
+
# Layer Norm
|
| 216 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 217 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 218 |
+
return hidden_states
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class FlaxBertSelfAttention(nn.Module):
|
| 222 |
+
config: BertConfig
|
| 223 |
+
causal: bool = False
|
| 224 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 225 |
+
|
| 226 |
+
def setup(self):
|
| 227 |
+
self.head_dim = self.config.hidden_size // self.config.num_attention_heads
|
| 228 |
+
if self.config.hidden_size % self.config.num_attention_heads != 0:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
"`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads` "
|
| 231 |
+
" : {self.config.num_attention_heads}"
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
self.query = nn.Dense(
|
| 235 |
+
self.config.hidden_size,
|
| 236 |
+
dtype=self.dtype,
|
| 237 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 238 |
+
)
|
| 239 |
+
self.key = nn.Dense(
|
| 240 |
+
self.config.hidden_size,
|
| 241 |
+
dtype=self.dtype,
|
| 242 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 243 |
+
)
|
| 244 |
+
self.value = nn.Dense(
|
| 245 |
+
self.config.hidden_size,
|
| 246 |
+
dtype=self.dtype,
|
| 247 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if self.causal:
|
| 251 |
+
self.causal_mask = make_causal_mask(
|
| 252 |
+
jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
def _split_heads(self, hidden_states):
|
| 256 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.config.num_attention_heads, self.head_dim))
|
| 257 |
+
|
| 258 |
+
def _merge_heads(self, hidden_states):
|
| 259 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.config.hidden_size,))
|
| 260 |
+
|
| 261 |
+
@nn.compact
|
| 262 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention._concatenate_to_cache
|
| 263 |
+
def _concatenate_to_cache(self, key, value, query, attention_mask):
|
| 264 |
+
"""
|
| 265 |
+
This function takes projected key, value states from a single input token and concatenates the states to cached
|
| 266 |
+
states from previous steps. This function is slighly adapted from the official Flax repository:
|
| 267 |
+
https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
|
| 268 |
+
"""
|
| 269 |
+
# detect if we're initializing by absence of existing cache data.
|
| 270 |
+
is_initialized = self.has_variable("cache", "cached_key")
|
| 271 |
+
cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
|
| 272 |
+
cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
|
| 273 |
+
cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
|
| 274 |
+
|
| 275 |
+
if is_initialized:
|
| 276 |
+
*batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
|
| 277 |
+
# update key, value caches with our new 1d spatial slices
|
| 278 |
+
cur_index = cache_index.value
|
| 279 |
+
indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
|
| 280 |
+
key = lax.dynamic_update_slice(cached_key.value, key, indices)
|
| 281 |
+
value = lax.dynamic_update_slice(cached_value.value, value, indices)
|
| 282 |
+
cached_key.value = key
|
| 283 |
+
cached_value.value = value
|
| 284 |
+
num_updated_cache_vectors = query.shape[1]
|
| 285 |
+
cache_index.value = cache_index.value + num_updated_cache_vectors
|
| 286 |
+
# causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
|
| 287 |
+
pad_mask = jnp.broadcast_to(
|
| 288 |
+
jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
|
| 289 |
+
tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
|
| 290 |
+
)
|
| 291 |
+
attention_mask = combine_masks(pad_mask, attention_mask)
|
| 292 |
+
return key, value, attention_mask
|
| 293 |
+
|
| 294 |
+
def __call__(
|
| 295 |
+
self,
|
| 296 |
+
hidden_states,
|
| 297 |
+
attention_mask,
|
| 298 |
+
layer_head_mask,
|
| 299 |
+
key_value_states: Optional[jnp.ndarray] = None,
|
| 300 |
+
init_cache: bool = False,
|
| 301 |
+
deterministic=True,
|
| 302 |
+
output_attentions: bool = False,
|
| 303 |
+
):
|
| 304 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 305 |
+
# for the decoder
|
| 306 |
+
is_cross_attention = key_value_states is not None
|
| 307 |
+
batch_size = hidden_states.shape[0]
|
| 308 |
+
|
| 309 |
+
# get query proj
|
| 310 |
+
query_states = self.query(hidden_states)
|
| 311 |
+
# get key, value proj
|
| 312 |
+
if is_cross_attention:
|
| 313 |
+
# cross_attentions
|
| 314 |
+
key_states = self.key(key_value_states)
|
| 315 |
+
value_states = self.value(key_value_states)
|
| 316 |
+
else:
|
| 317 |
+
# self_attention
|
| 318 |
+
key_states = self.key(hidden_states)
|
| 319 |
+
value_states = self.value(hidden_states)
|
| 320 |
+
|
| 321 |
+
query_states = self._split_heads(query_states)
|
| 322 |
+
key_states = self._split_heads(key_states)
|
| 323 |
+
value_states = self._split_heads(value_states)
|
| 324 |
+
|
| 325 |
+
# handle cache prepare causal attention mask
|
| 326 |
+
if self.causal:
|
| 327 |
+
query_length, key_length = query_states.shape[1], key_states.shape[1]
|
| 328 |
+
if self.has_variable("cache", "cached_key"):
|
| 329 |
+
mask_shift = self.variables["cache"]["cache_index"]
|
| 330 |
+
max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
|
| 331 |
+
causal_mask = lax.dynamic_slice(
|
| 332 |
+
self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
|
| 333 |
+
)
|
| 334 |
+
else:
|
| 335 |
+
causal_mask = self.causal_mask[:, :, :query_length, :key_length]
|
| 336 |
+
causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
|
| 337 |
+
|
| 338 |
+
# combine masks if needed
|
| 339 |
+
if attention_mask is not None and self.causal:
|
| 340 |
+
attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
|
| 341 |
+
attention_mask = combine_masks(attention_mask, causal_mask)
|
| 342 |
+
elif self.causal:
|
| 343 |
+
attention_mask = causal_mask
|
| 344 |
+
elif attention_mask is not None:
|
| 345 |
+
attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
|
| 346 |
+
|
| 347 |
+
# During fast autoregressive decoding, we feed one position at a time,
|
| 348 |
+
# and cache the keys and values step by step.
|
| 349 |
+
if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
|
| 350 |
+
key_states, value_states, attention_mask = self._concatenate_to_cache(
|
| 351 |
+
key_states, value_states, query_states, attention_mask
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# Convert the boolean attention mask to an attention bias.
|
| 355 |
+
if attention_mask is not None:
|
| 356 |
+
# attention mask in the form of attention bias
|
| 357 |
+
attention_bias = lax.select(
|
| 358 |
+
attention_mask > 0,
|
| 359 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
| 360 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
| 361 |
+
)
|
| 362 |
+
else:
|
| 363 |
+
attention_bias = None
|
| 364 |
+
|
| 365 |
+
dropout_rng = None
|
| 366 |
+
if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
|
| 367 |
+
dropout_rng = self.make_rng("dropout")
|
| 368 |
+
|
| 369 |
+
attn_weights = dot_product_attention_weights(
|
| 370 |
+
query_states,
|
| 371 |
+
key_states,
|
| 372 |
+
bias=attention_bias,
|
| 373 |
+
dropout_rng=dropout_rng,
|
| 374 |
+
dropout_rate=self.config.attention_probs_dropout_prob,
|
| 375 |
+
broadcast_dropout=True,
|
| 376 |
+
deterministic=deterministic,
|
| 377 |
+
dtype=self.dtype,
|
| 378 |
+
precision=None,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Mask heads if we want to
|
| 382 |
+
if layer_head_mask is not None:
|
| 383 |
+
attn_weights = jnp.einsum("...hqk,h->...hqk", attn_weights, layer_head_mask)
|
| 384 |
+
|
| 385 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
|
| 386 |
+
attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
|
| 387 |
+
|
| 388 |
+
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
|
| 389 |
+
return outputs
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class FlaxBertSelfOutput(nn.Module):
|
| 393 |
+
config: BertConfig
|
| 394 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 395 |
+
|
| 396 |
+
def setup(self):
|
| 397 |
+
self.dense = nn.Dense(
|
| 398 |
+
self.config.hidden_size,
|
| 399 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 400 |
+
dtype=self.dtype,
|
| 401 |
+
)
|
| 402 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 403 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 404 |
+
|
| 405 |
+
def __call__(self, hidden_states, input_tensor, deterministic: bool = True):
|
| 406 |
+
hidden_states = self.dense(hidden_states)
|
| 407 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 408 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 409 |
+
return hidden_states
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class FlaxBertAttention(nn.Module):
|
| 413 |
+
config: BertConfig
|
| 414 |
+
causal: bool = False
|
| 415 |
+
dtype: jnp.dtype = jnp.float32
|
| 416 |
+
|
| 417 |
+
def setup(self):
|
| 418 |
+
self.self = FlaxBertSelfAttention(self.config, causal=self.causal, dtype=self.dtype)
|
| 419 |
+
self.output = FlaxBertSelfOutput(self.config, dtype=self.dtype)
|
| 420 |
+
|
| 421 |
+
def __call__(
|
| 422 |
+
self,
|
| 423 |
+
hidden_states,
|
| 424 |
+
attention_mask,
|
| 425 |
+
layer_head_mask,
|
| 426 |
+
key_value_states=None,
|
| 427 |
+
init_cache=False,
|
| 428 |
+
deterministic=True,
|
| 429 |
+
output_attentions: bool = False,
|
| 430 |
+
):
|
| 431 |
+
# Attention mask comes in as attention_mask.shape == (*batch_sizes, kv_length)
|
| 432 |
+
# FLAX expects: attention_mask.shape == (*batch_sizes, 1, 1, kv_length) such that it is broadcastable
|
| 433 |
+
# with attn_weights.shape == (*batch_sizes, num_heads, q_length, kv_length)
|
| 434 |
+
attn_outputs = self.self(
|
| 435 |
+
hidden_states,
|
| 436 |
+
attention_mask,
|
| 437 |
+
layer_head_mask=layer_head_mask,
|
| 438 |
+
key_value_states=key_value_states,
|
| 439 |
+
init_cache=init_cache,
|
| 440 |
+
deterministic=deterministic,
|
| 441 |
+
output_attentions=output_attentions,
|
| 442 |
+
)
|
| 443 |
+
attn_output = attn_outputs[0]
|
| 444 |
+
hidden_states = self.output(attn_output, hidden_states, deterministic=deterministic)
|
| 445 |
+
|
| 446 |
+
outputs = (hidden_states,)
|
| 447 |
+
|
| 448 |
+
if output_attentions:
|
| 449 |
+
outputs += (attn_outputs[1],)
|
| 450 |
+
|
| 451 |
+
return outputs
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class FlaxBertIntermediate(nn.Module):
|
| 455 |
+
config: BertConfig
|
| 456 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 457 |
+
|
| 458 |
+
def setup(self):
|
| 459 |
+
self.dense = nn.Dense(
|
| 460 |
+
self.config.intermediate_size,
|
| 461 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 462 |
+
dtype=self.dtype,
|
| 463 |
+
)
|
| 464 |
+
self.activation = ACT2FN[self.config.hidden_act]
|
| 465 |
+
|
| 466 |
+
def __call__(self, hidden_states):
|
| 467 |
+
hidden_states = self.dense(hidden_states)
|
| 468 |
+
hidden_states = self.activation(hidden_states)
|
| 469 |
+
return hidden_states
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class FlaxBertOutput(nn.Module):
|
| 473 |
+
config: BertConfig
|
| 474 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 475 |
+
|
| 476 |
+
def setup(self):
|
| 477 |
+
self.dense = nn.Dense(
|
| 478 |
+
self.config.hidden_size,
|
| 479 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 480 |
+
dtype=self.dtype,
|
| 481 |
+
)
|
| 482 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 483 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 484 |
+
|
| 485 |
+
def __call__(self, hidden_states, attention_output, deterministic: bool = True):
|
| 486 |
+
hidden_states = self.dense(hidden_states)
|
| 487 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 488 |
+
hidden_states = self.LayerNorm(hidden_states + attention_output)
|
| 489 |
+
return hidden_states
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class FlaxBertLayer(nn.Module):
|
| 493 |
+
config: BertConfig
|
| 494 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 495 |
+
|
| 496 |
+
def setup(self):
|
| 497 |
+
self.attention = FlaxBertAttention(self.config, causal=self.config.is_decoder, dtype=self.dtype)
|
| 498 |
+
self.intermediate = FlaxBertIntermediate(self.config, dtype=self.dtype)
|
| 499 |
+
self.output = FlaxBertOutput(self.config, dtype=self.dtype)
|
| 500 |
+
if self.config.add_cross_attention:
|
| 501 |
+
self.crossattention = FlaxBertAttention(self.config, causal=False, dtype=self.dtype)
|
| 502 |
+
|
| 503 |
+
def __call__(
|
| 504 |
+
self,
|
| 505 |
+
hidden_states,
|
| 506 |
+
attention_mask,
|
| 507 |
+
layer_head_mask,
|
| 508 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 509 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 510 |
+
init_cache: bool = False,
|
| 511 |
+
deterministic: bool = True,
|
| 512 |
+
output_attentions: bool = False,
|
| 513 |
+
):
|
| 514 |
+
# Self Attention
|
| 515 |
+
attention_outputs = self.attention(
|
| 516 |
+
hidden_states,
|
| 517 |
+
attention_mask,
|
| 518 |
+
layer_head_mask=layer_head_mask,
|
| 519 |
+
init_cache=init_cache,
|
| 520 |
+
deterministic=deterministic,
|
| 521 |
+
output_attentions=output_attentions,
|
| 522 |
+
)
|
| 523 |
+
attention_output = attention_outputs[0]
|
| 524 |
+
|
| 525 |
+
# Cross-Attention Block
|
| 526 |
+
if encoder_hidden_states is not None:
|
| 527 |
+
cross_attention_outputs = self.crossattention(
|
| 528 |
+
attention_output,
|
| 529 |
+
attention_mask=encoder_attention_mask,
|
| 530 |
+
layer_head_mask=layer_head_mask,
|
| 531 |
+
key_value_states=encoder_hidden_states,
|
| 532 |
+
deterministic=deterministic,
|
| 533 |
+
output_attentions=output_attentions,
|
| 534 |
+
)
|
| 535 |
+
attention_output = cross_attention_outputs[0]
|
| 536 |
+
|
| 537 |
+
hidden_states = self.intermediate(attention_output)
|
| 538 |
+
hidden_states = self.output(hidden_states, attention_output, deterministic=deterministic)
|
| 539 |
+
|
| 540 |
+
outputs = (hidden_states,)
|
| 541 |
+
|
| 542 |
+
if output_attentions:
|
| 543 |
+
outputs += (attention_outputs[1],)
|
| 544 |
+
if encoder_hidden_states is not None:
|
| 545 |
+
outputs += (cross_attention_outputs[1],)
|
| 546 |
+
return outputs
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class FlaxBertLayerCollection(nn.Module):
|
| 550 |
+
config: BertConfig
|
| 551 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 552 |
+
gradient_checkpointing: bool = False
|
| 553 |
+
|
| 554 |
+
def setup(self):
|
| 555 |
+
if self.gradient_checkpointing:
|
| 556 |
+
FlaxBertCheckpointLayer = remat(FlaxBertLayer, static_argnums=(5, 6, 7))
|
| 557 |
+
self.layers = [
|
| 558 |
+
FlaxBertCheckpointLayer(self.config, name=str(i), dtype=self.dtype)
|
| 559 |
+
for i in range(self.config.num_hidden_layers)
|
| 560 |
+
]
|
| 561 |
+
else:
|
| 562 |
+
self.layers = [
|
| 563 |
+
FlaxBertLayer(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.num_hidden_layers)
|
| 564 |
+
]
|
| 565 |
+
|
| 566 |
+
def __call__(
|
| 567 |
+
self,
|
| 568 |
+
hidden_states,
|
| 569 |
+
attention_mask,
|
| 570 |
+
head_mask,
|
| 571 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 572 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 573 |
+
init_cache: bool = False,
|
| 574 |
+
deterministic: bool = True,
|
| 575 |
+
output_attentions: bool = False,
|
| 576 |
+
output_hidden_states: bool = False,
|
| 577 |
+
return_dict: bool = True,
|
| 578 |
+
):
|
| 579 |
+
all_attentions = () if output_attentions else None
|
| 580 |
+
all_hidden_states = () if output_hidden_states else None
|
| 581 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 582 |
+
|
| 583 |
+
# Check if head_mask has a correct number of layers specified if desired
|
| 584 |
+
if head_mask is not None:
|
| 585 |
+
if head_mask.shape[0] != (len(self.layers)):
|
| 586 |
+
raise ValueError(
|
| 587 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for "
|
| 588 |
+
f" {head_mask.shape[0]}."
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
for i, layer in enumerate(self.layers):
|
| 592 |
+
if output_hidden_states:
|
| 593 |
+
all_hidden_states += (hidden_states,)
|
| 594 |
+
|
| 595 |
+
layer_outputs = layer(
|
| 596 |
+
hidden_states,
|
| 597 |
+
attention_mask,
|
| 598 |
+
head_mask[i] if head_mask is not None else None,
|
| 599 |
+
encoder_hidden_states,
|
| 600 |
+
encoder_attention_mask,
|
| 601 |
+
init_cache,
|
| 602 |
+
deterministic,
|
| 603 |
+
output_attentions,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
hidden_states = layer_outputs[0]
|
| 607 |
+
|
| 608 |
+
if output_attentions:
|
| 609 |
+
all_attentions += (layer_outputs[1],)
|
| 610 |
+
|
| 611 |
+
if encoder_hidden_states is not None:
|
| 612 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 613 |
+
|
| 614 |
+
if output_hidden_states:
|
| 615 |
+
all_hidden_states += (hidden_states,)
|
| 616 |
+
|
| 617 |
+
outputs = (hidden_states, all_hidden_states, all_attentions, all_cross_attentions)
|
| 618 |
+
|
| 619 |
+
if not return_dict:
|
| 620 |
+
return tuple(v for v in outputs if v is not None)
|
| 621 |
+
|
| 622 |
+
return FlaxBaseModelOutputWithPastAndCrossAttentions(
|
| 623 |
+
last_hidden_state=hidden_states,
|
| 624 |
+
hidden_states=all_hidden_states,
|
| 625 |
+
attentions=all_attentions,
|
| 626 |
+
cross_attentions=all_cross_attentions,
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class FlaxBertEncoder(nn.Module):
|
| 631 |
+
config: BertConfig
|
| 632 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 633 |
+
gradient_checkpointing: bool = False
|
| 634 |
+
|
| 635 |
+
def setup(self):
|
| 636 |
+
self.layer = FlaxBertLayerCollection(
|
| 637 |
+
self.config,
|
| 638 |
+
dtype=self.dtype,
|
| 639 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
def __call__(
|
| 643 |
+
self,
|
| 644 |
+
hidden_states,
|
| 645 |
+
attention_mask,
|
| 646 |
+
head_mask,
|
| 647 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 648 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 649 |
+
init_cache: bool = False,
|
| 650 |
+
deterministic: bool = True,
|
| 651 |
+
output_attentions: bool = False,
|
| 652 |
+
output_hidden_states: bool = False,
|
| 653 |
+
return_dict: bool = True,
|
| 654 |
+
):
|
| 655 |
+
return self.layer(
|
| 656 |
+
hidden_states,
|
| 657 |
+
attention_mask,
|
| 658 |
+
head_mask=head_mask,
|
| 659 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 660 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 661 |
+
init_cache=init_cache,
|
| 662 |
+
deterministic=deterministic,
|
| 663 |
+
output_attentions=output_attentions,
|
| 664 |
+
output_hidden_states=output_hidden_states,
|
| 665 |
+
return_dict=return_dict,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
class FlaxBertPooler(nn.Module):
|
| 670 |
+
config: BertConfig
|
| 671 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 672 |
+
|
| 673 |
+
def setup(self):
|
| 674 |
+
self.dense = nn.Dense(
|
| 675 |
+
self.config.hidden_size,
|
| 676 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 677 |
+
dtype=self.dtype,
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
def __call__(self, hidden_states):
|
| 681 |
+
cls_hidden_state = hidden_states[:, 0]
|
| 682 |
+
cls_hidden_state = self.dense(cls_hidden_state)
|
| 683 |
+
return nn.tanh(cls_hidden_state)
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
class FlaxBertPredictionHeadTransform(nn.Module):
|
| 687 |
+
config: BertConfig
|
| 688 |
+
dtype: jnp.dtype = jnp.float32
|
| 689 |
+
|
| 690 |
+
def setup(self):
|
| 691 |
+
self.dense = nn.Dense(self.config.hidden_size, dtype=self.dtype)
|
| 692 |
+
self.activation = ACT2FN[self.config.hidden_act]
|
| 693 |
+
self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
|
| 694 |
+
|
| 695 |
+
def __call__(self, hidden_states):
|
| 696 |
+
hidden_states = self.dense(hidden_states)
|
| 697 |
+
hidden_states = self.activation(hidden_states)
|
| 698 |
+
return self.LayerNorm(hidden_states)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
class FlaxBertLMPredictionHead(nn.Module):
|
| 702 |
+
config: BertConfig
|
| 703 |
+
dtype: jnp.dtype = jnp.float32
|
| 704 |
+
bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
|
| 705 |
+
|
| 706 |
+
def setup(self):
|
| 707 |
+
self.transform = FlaxBertPredictionHeadTransform(self.config, dtype=self.dtype)
|
| 708 |
+
self.decoder = nn.Dense(self.config.vocab_size, dtype=self.dtype, use_bias=False)
|
| 709 |
+
self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
|
| 710 |
+
|
| 711 |
+
def __call__(self, hidden_states, shared_embedding=None):
|
| 712 |
+
hidden_states = self.transform(hidden_states)
|
| 713 |
+
|
| 714 |
+
if shared_embedding is not None:
|
| 715 |
+
hidden_states = self.decoder.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
|
| 716 |
+
else:
|
| 717 |
+
hidden_states = self.decoder(hidden_states)
|
| 718 |
+
|
| 719 |
+
bias = jnp.asarray(self.bias, self.dtype)
|
| 720 |
+
hidden_states += bias
|
| 721 |
+
return hidden_states
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
class FlaxBertOnlyMLMHead(nn.Module):
|
| 725 |
+
config: BertConfig
|
| 726 |
+
dtype: jnp.dtype = jnp.float32
|
| 727 |
+
|
| 728 |
+
def setup(self):
|
| 729 |
+
self.predictions = FlaxBertLMPredictionHead(self.config, dtype=self.dtype)
|
| 730 |
+
|
| 731 |
+
def __call__(self, hidden_states, shared_embedding=None):
|
| 732 |
+
hidden_states = self.predictions(hidden_states, shared_embedding=shared_embedding)
|
| 733 |
+
return hidden_states
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class FlaxBertOnlyNSPHead(nn.Module):
|
| 737 |
+
dtype: jnp.dtype = jnp.float32
|
| 738 |
+
|
| 739 |
+
def setup(self):
|
| 740 |
+
self.seq_relationship = nn.Dense(2, dtype=self.dtype)
|
| 741 |
+
|
| 742 |
+
def __call__(self, pooled_output):
|
| 743 |
+
return self.seq_relationship(pooled_output)
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
class FlaxBertPreTrainingHeads(nn.Module):
|
| 747 |
+
config: BertConfig
|
| 748 |
+
dtype: jnp.dtype = jnp.float32
|
| 749 |
+
|
| 750 |
+
def setup(self):
|
| 751 |
+
self.predictions = FlaxBertLMPredictionHead(self.config, dtype=self.dtype)
|
| 752 |
+
self.seq_relationship = nn.Dense(2, dtype=self.dtype)
|
| 753 |
+
|
| 754 |
+
def __call__(self, hidden_states, pooled_output, shared_embedding=None):
|
| 755 |
+
prediction_scores = self.predictions(hidden_states, shared_embedding=shared_embedding)
|
| 756 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
| 757 |
+
return prediction_scores, seq_relationship_score
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
class FlaxBertPreTrainedModel(FlaxPreTrainedModel):
|
| 761 |
+
"""
|
| 762 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 763 |
+
models.
|
| 764 |
+
"""
|
| 765 |
+
|
| 766 |
+
config_class = BertConfig
|
| 767 |
+
base_model_prefix = "bert"
|
| 768 |
+
module_class: nn.Module = None
|
| 769 |
+
|
| 770 |
+
def __init__(
|
| 771 |
+
self,
|
| 772 |
+
config: BertConfig,
|
| 773 |
+
input_shape: Tuple = (1, 1),
|
| 774 |
+
seed: int = 0,
|
| 775 |
+
dtype: jnp.dtype = jnp.float32,
|
| 776 |
+
_do_init: bool = True,
|
| 777 |
+
gradient_checkpointing: bool = False,
|
| 778 |
+
**kwargs,
|
| 779 |
+
):
|
| 780 |
+
module = self.module_class(
|
| 781 |
+
config=config,
|
| 782 |
+
dtype=dtype,
|
| 783 |
+
gradient_checkpointing=gradient_checkpointing,
|
| 784 |
+
**kwargs,
|
| 785 |
+
)
|
| 786 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 787 |
+
|
| 788 |
+
def enable_gradient_checkpointing(self):
|
| 789 |
+
self._module = self.module_class(
|
| 790 |
+
config=self.config,
|
| 791 |
+
dtype=self.dtype,
|
| 792 |
+
gradient_checkpointing=True,
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 796 |
+
# init input tensors
|
| 797 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 798 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 799 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
|
| 800 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 801 |
+
head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
|
| 802 |
+
|
| 803 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 804 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 805 |
+
|
| 806 |
+
if self.config.add_cross_attention:
|
| 807 |
+
encoder_hidden_states = jnp.zeros(input_shape + (self.config.hidden_size,))
|
| 808 |
+
encoder_attention_mask = attention_mask
|
| 809 |
+
module_init_outputs = self.module.init(
|
| 810 |
+
rngs,
|
| 811 |
+
input_ids,
|
| 812 |
+
attention_mask,
|
| 813 |
+
token_type_ids,
|
| 814 |
+
position_ids,
|
| 815 |
+
head_mask,
|
| 816 |
+
encoder_hidden_states,
|
| 817 |
+
encoder_attention_mask,
|
| 818 |
+
return_dict=False,
|
| 819 |
+
)
|
| 820 |
+
else:
|
| 821 |
+
module_init_outputs = self.module.init(
|
| 822 |
+
rngs, input_ids, attention_mask, token_type_ids, position_ids, head_mask, return_dict=False
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
random_params = module_init_outputs["params"]
|
| 826 |
+
|
| 827 |
+
if params is not None:
|
| 828 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 829 |
+
params = flatten_dict(unfreeze(params))
|
| 830 |
+
for missing_key in self._missing_keys:
|
| 831 |
+
params[missing_key] = random_params[missing_key]
|
| 832 |
+
self._missing_keys = set()
|
| 833 |
+
return freeze(unflatten_dict(params))
|
| 834 |
+
else:
|
| 835 |
+
return random_params
|
| 836 |
+
|
| 837 |
+
# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderPreTrainedModel.init_cache
|
| 838 |
+
def init_cache(self, batch_size, max_length):
|
| 839 |
+
r"""
|
| 840 |
+
Args:
|
| 841 |
+
batch_size (`int`):
|
| 842 |
+
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
|
| 843 |
+
max_length (`int`):
|
| 844 |
+
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
|
| 845 |
+
cache.
|
| 846 |
+
"""
|
| 847 |
+
# init input variables to retrieve cache
|
| 848 |
+
input_ids = jnp.ones((batch_size, max_length), dtype="i4")
|
| 849 |
+
attention_mask = jnp.ones_like(input_ids, dtype="i4")
|
| 850 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 851 |
+
|
| 852 |
+
init_variables = self.module.init(
|
| 853 |
+
jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
|
| 854 |
+
)
|
| 855 |
+
return unfreeze(init_variables["cache"])
|
| 856 |
+
|
| 857 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 858 |
+
def __call__(
|
| 859 |
+
self,
|
| 860 |
+
input_ids,
|
| 861 |
+
attention_mask=None,
|
| 862 |
+
token_type_ids=None,
|
| 863 |
+
position_ids=None,
|
| 864 |
+
head_mask=None,
|
| 865 |
+
encoder_hidden_states=None,
|
| 866 |
+
encoder_attention_mask=None,
|
| 867 |
+
params: dict = None,
|
| 868 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 869 |
+
train: bool = False,
|
| 870 |
+
output_attentions: Optional[bool] = None,
|
| 871 |
+
output_hidden_states: Optional[bool] = None,
|
| 872 |
+
return_dict: Optional[bool] = None,
|
| 873 |
+
past_key_values: dict = None,
|
| 874 |
+
):
|
| 875 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 876 |
+
output_hidden_states = (
|
| 877 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 878 |
+
)
|
| 879 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 880 |
+
|
| 881 |
+
# init input tensors if not passed
|
| 882 |
+
if token_type_ids is None:
|
| 883 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 884 |
+
|
| 885 |
+
if position_ids is None:
|
| 886 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 887 |
+
|
| 888 |
+
if attention_mask is None:
|
| 889 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 890 |
+
|
| 891 |
+
if head_mask is None:
|
| 892 |
+
head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
|
| 893 |
+
|
| 894 |
+
# Handle any PRNG if needed
|
| 895 |
+
rngs = {}
|
| 896 |
+
if dropout_rng is not None:
|
| 897 |
+
rngs["dropout"] = dropout_rng
|
| 898 |
+
|
| 899 |
+
inputs = {"params": params or self.params}
|
| 900 |
+
|
| 901 |
+
if self.config.add_cross_attention:
|
| 902 |
+
# if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed
|
| 903 |
+
# down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be
|
| 904 |
+
# changed by FlaxBertAttention module
|
| 905 |
+
if past_key_values:
|
| 906 |
+
inputs["cache"] = past_key_values
|
| 907 |
+
mutable = ["cache"]
|
| 908 |
+
else:
|
| 909 |
+
mutable = False
|
| 910 |
+
|
| 911 |
+
outputs = self.module.apply(
|
| 912 |
+
inputs,
|
| 913 |
+
jnp.array(input_ids, dtype="i4"),
|
| 914 |
+
jnp.array(attention_mask, dtype="i4"),
|
| 915 |
+
token_type_ids=jnp.array(token_type_ids, dtype="i4"),
|
| 916 |
+
position_ids=jnp.array(position_ids, dtype="i4"),
|
| 917 |
+
head_mask=jnp.array(head_mask, dtype="i4"),
|
| 918 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 919 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 920 |
+
deterministic=not train,
|
| 921 |
+
output_attentions=output_attentions,
|
| 922 |
+
output_hidden_states=output_hidden_states,
|
| 923 |
+
return_dict=return_dict,
|
| 924 |
+
rngs=rngs,
|
| 925 |
+
mutable=mutable,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
# add updated cache to model output
|
| 929 |
+
if past_key_values is not None and return_dict:
|
| 930 |
+
outputs, past_key_values = outputs
|
| 931 |
+
outputs["past_key_values"] = unfreeze(past_key_values["cache"])
|
| 932 |
+
return outputs
|
| 933 |
+
elif past_key_values is not None and not return_dict:
|
| 934 |
+
outputs, past_key_values = outputs
|
| 935 |
+
outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
|
| 936 |
+
|
| 937 |
+
else:
|
| 938 |
+
outputs = self.module.apply(
|
| 939 |
+
inputs,
|
| 940 |
+
jnp.array(input_ids, dtype="i4"),
|
| 941 |
+
jnp.array(attention_mask, dtype="i4"),
|
| 942 |
+
token_type_ids=jnp.array(token_type_ids, dtype="i4"),
|
| 943 |
+
position_ids=jnp.array(position_ids, dtype="i4"),
|
| 944 |
+
head_mask=jnp.array(head_mask, dtype="i4"),
|
| 945 |
+
deterministic=not train,
|
| 946 |
+
output_attentions=output_attentions,
|
| 947 |
+
output_hidden_states=output_hidden_states,
|
| 948 |
+
return_dict=return_dict,
|
| 949 |
+
rngs=rngs,
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
return outputs
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
class FlaxBertModule(nn.Module):
|
| 956 |
+
config: BertConfig
|
| 957 |
+
dtype: jnp.dtype = jnp.float32 # the dtype of the computation
|
| 958 |
+
add_pooling_layer: bool = True
|
| 959 |
+
gradient_checkpointing: bool = False
|
| 960 |
+
|
| 961 |
+
def setup(self):
|
| 962 |
+
self.embeddings = FlaxBertEmbeddings(self.config, dtype=self.dtype)
|
| 963 |
+
self.encoder = FlaxBertEncoder(
|
| 964 |
+
self.config,
|
| 965 |
+
dtype=self.dtype,
|
| 966 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 967 |
+
)
|
| 968 |
+
self.pooler = FlaxBertPooler(self.config, dtype=self.dtype)
|
| 969 |
+
|
| 970 |
+
def __call__(
|
| 971 |
+
self,
|
| 972 |
+
input_ids,
|
| 973 |
+
attention_mask,
|
| 974 |
+
token_type_ids: Optional[jnp.ndarray] = None,
|
| 975 |
+
position_ids: Optional[jnp.ndarray] = None,
|
| 976 |
+
head_mask: Optional[jnp.ndarray] = None,
|
| 977 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 978 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 979 |
+
init_cache: bool = False,
|
| 980 |
+
deterministic: bool = True,
|
| 981 |
+
output_attentions: bool = False,
|
| 982 |
+
output_hidden_states: bool = False,
|
| 983 |
+
return_dict: bool = True,
|
| 984 |
+
):
|
| 985 |
+
# make sure `token_type_ids` is correctly initialized when not passed
|
| 986 |
+
if token_type_ids is None:
|
| 987 |
+
token_type_ids = jnp.zeros_like(input_ids)
|
| 988 |
+
|
| 989 |
+
# make sure `position_ids` is correctly initialized when not passed
|
| 990 |
+
if position_ids is None:
|
| 991 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 992 |
+
|
| 993 |
+
hidden_states = self.embeddings(
|
| 994 |
+
input_ids, token_type_ids, position_ids, attention_mask, deterministic=deterministic
|
| 995 |
+
)
|
| 996 |
+
outputs = self.encoder(
|
| 997 |
+
hidden_states,
|
| 998 |
+
attention_mask,
|
| 999 |
+
head_mask=head_mask,
|
| 1000 |
+
deterministic=deterministic,
|
| 1001 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1002 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1003 |
+
init_cache=init_cache,
|
| 1004 |
+
output_attentions=output_attentions,
|
| 1005 |
+
output_hidden_states=output_hidden_states,
|
| 1006 |
+
return_dict=return_dict,
|
| 1007 |
+
)
|
| 1008 |
+
hidden_states = outputs[0]
|
| 1009 |
+
pooled = self.pooler(hidden_states) if self.add_pooling_layer else None
|
| 1010 |
+
|
| 1011 |
+
if not return_dict:
|
| 1012 |
+
# if pooled is None, don't return it
|
| 1013 |
+
if pooled is None:
|
| 1014 |
+
return (hidden_states,) + outputs[1:]
|
| 1015 |
+
return (hidden_states, pooled) + outputs[1:]
|
| 1016 |
+
|
| 1017 |
+
return FlaxBaseModelOutputWithPoolingAndCrossAttentions(
|
| 1018 |
+
last_hidden_state=hidden_states,
|
| 1019 |
+
pooler_output=pooled,
|
| 1020 |
+
hidden_states=outputs.hidden_states,
|
| 1021 |
+
attentions=outputs.attentions,
|
| 1022 |
+
cross_attentions=outputs.cross_attentions,
|
| 1023 |
+
)
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
@add_start_docstrings(
|
| 1027 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 1028 |
+
BERT_START_DOCSTRING,
|
| 1029 |
+
)
|
| 1030 |
+
class FlaxBertModel(FlaxBertPreTrainedModel):
|
| 1031 |
+
module_class = FlaxBertModule
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
append_call_sample_docstring(FlaxBertModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutputWithPooling, _CONFIG_FOR_DOC)
|
| 1035 |
+
|
| 1036 |
+
|
| 1037 |
+
class FlaxBertForPreTrainingModule(nn.Module):
|
| 1038 |
+
config: BertConfig
|
| 1039 |
+
dtype: jnp.dtype = jnp.float32
|
| 1040 |
+
gradient_checkpointing: bool = False
|
| 1041 |
+
|
| 1042 |
+
def setup(self):
|
| 1043 |
+
self.bert = FlaxBertModule(
|
| 1044 |
+
config=self.config,
|
| 1045 |
+
dtype=self.dtype,
|
| 1046 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1047 |
+
)
|
| 1048 |
+
self.cls = FlaxBertPreTrainingHeads(config=self.config, dtype=self.dtype)
|
| 1049 |
+
|
| 1050 |
+
def __call__(
|
| 1051 |
+
self,
|
| 1052 |
+
input_ids,
|
| 1053 |
+
attention_mask,
|
| 1054 |
+
token_type_ids,
|
| 1055 |
+
position_ids,
|
| 1056 |
+
head_mask,
|
| 1057 |
+
deterministic: bool = True,
|
| 1058 |
+
output_attentions: bool = False,
|
| 1059 |
+
output_hidden_states: bool = False,
|
| 1060 |
+
return_dict: bool = True,
|
| 1061 |
+
):
|
| 1062 |
+
# Model
|
| 1063 |
+
outputs = self.bert(
|
| 1064 |
+
input_ids,
|
| 1065 |
+
attention_mask,
|
| 1066 |
+
token_type_ids,
|
| 1067 |
+
position_ids,
|
| 1068 |
+
head_mask,
|
| 1069 |
+
deterministic=deterministic,
|
| 1070 |
+
output_attentions=output_attentions,
|
| 1071 |
+
output_hidden_states=output_hidden_states,
|
| 1072 |
+
return_dict=return_dict,
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
if self.config.tie_word_embeddings:
|
| 1076 |
+
shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 1077 |
+
else:
|
| 1078 |
+
shared_embedding = None
|
| 1079 |
+
|
| 1080 |
+
hidden_states = outputs[0]
|
| 1081 |
+
pooled_output = outputs[1]
|
| 1082 |
+
|
| 1083 |
+
prediction_scores, seq_relationship_score = self.cls(
|
| 1084 |
+
hidden_states, pooled_output, shared_embedding=shared_embedding
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
if not return_dict:
|
| 1088 |
+
return (prediction_scores, seq_relationship_score) + outputs[2:]
|
| 1089 |
+
|
| 1090 |
+
return FlaxBertForPreTrainingOutput(
|
| 1091 |
+
prediction_logits=prediction_scores,
|
| 1092 |
+
seq_relationship_logits=seq_relationship_score,
|
| 1093 |
+
hidden_states=outputs.hidden_states,
|
| 1094 |
+
attentions=outputs.attentions,
|
| 1095 |
+
)
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
@add_start_docstrings(
|
| 1099 |
+
"""
|
| 1100 |
+
Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
|
| 1101 |
+
sentence prediction (classification)` head.
|
| 1102 |
+
""",
|
| 1103 |
+
BERT_START_DOCSTRING,
|
| 1104 |
+
)
|
| 1105 |
+
class FlaxBertForPreTraining(FlaxBertPreTrainedModel):
|
| 1106 |
+
module_class = FlaxBertForPreTrainingModule
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
FLAX_BERT_FOR_PRETRAINING_DOCSTRING = """
|
| 1110 |
+
Returns:
|
| 1111 |
+
|
| 1112 |
+
Example:
|
| 1113 |
+
|
| 1114 |
+
```python
|
| 1115 |
+
>>> from transformers import AutoTokenizer, FlaxBertForPreTraining
|
| 1116 |
+
|
| 1117 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 1118 |
+
>>> model = FlaxBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
|
| 1119 |
+
|
| 1120 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
|
| 1121 |
+
>>> outputs = model(**inputs)
|
| 1122 |
+
|
| 1123 |
+
>>> prediction_logits = outputs.prediction_logits
|
| 1124 |
+
>>> seq_relationship_logits = outputs.seq_relationship_logits
|
| 1125 |
+
```
|
| 1126 |
+
"""
|
| 1127 |
+
|
| 1128 |
+
overwrite_call_docstring(
|
| 1129 |
+
FlaxBertForPreTraining,
|
| 1130 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_BERT_FOR_PRETRAINING_DOCSTRING,
|
| 1131 |
+
)
|
| 1132 |
+
append_replace_return_docstrings(
|
| 1133 |
+
FlaxBertForPreTraining, output_type=FlaxBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
|
| 1137 |
+
class FlaxBertForMaskedLMModule(nn.Module):
|
| 1138 |
+
config: BertConfig
|
| 1139 |
+
dtype: jnp.dtype = jnp.float32
|
| 1140 |
+
gradient_checkpointing: bool = False
|
| 1141 |
+
|
| 1142 |
+
def setup(self):
|
| 1143 |
+
self.bert = FlaxBertModule(
|
| 1144 |
+
config=self.config,
|
| 1145 |
+
add_pooling_layer=False,
|
| 1146 |
+
dtype=self.dtype,
|
| 1147 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1148 |
+
)
|
| 1149 |
+
self.cls = FlaxBertOnlyMLMHead(config=self.config, dtype=self.dtype)
|
| 1150 |
+
|
| 1151 |
+
def __call__(
|
| 1152 |
+
self,
|
| 1153 |
+
input_ids,
|
| 1154 |
+
attention_mask,
|
| 1155 |
+
token_type_ids,
|
| 1156 |
+
position_ids,
|
| 1157 |
+
head_mask,
|
| 1158 |
+
deterministic: bool = True,
|
| 1159 |
+
output_attentions: bool = False,
|
| 1160 |
+
output_hidden_states: bool = False,
|
| 1161 |
+
return_dict: bool = True,
|
| 1162 |
+
):
|
| 1163 |
+
# Model
|
| 1164 |
+
outputs = self.bert(
|
| 1165 |
+
input_ids,
|
| 1166 |
+
attention_mask,
|
| 1167 |
+
token_type_ids,
|
| 1168 |
+
position_ids,
|
| 1169 |
+
head_mask,
|
| 1170 |
+
deterministic=deterministic,
|
| 1171 |
+
output_attentions=output_attentions,
|
| 1172 |
+
output_hidden_states=output_hidden_states,
|
| 1173 |
+
return_dict=return_dict,
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
hidden_states = outputs[0]
|
| 1177 |
+
if self.config.tie_word_embeddings:
|
| 1178 |
+
shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 1179 |
+
else:
|
| 1180 |
+
shared_embedding = None
|
| 1181 |
+
|
| 1182 |
+
# Compute the prediction scores
|
| 1183 |
+
logits = self.cls(hidden_states, shared_embedding=shared_embedding)
|
| 1184 |
+
|
| 1185 |
+
if not return_dict:
|
| 1186 |
+
return (logits,) + outputs[1:]
|
| 1187 |
+
|
| 1188 |
+
return FlaxMaskedLMOutput(
|
| 1189 |
+
logits=logits,
|
| 1190 |
+
hidden_states=outputs.hidden_states,
|
| 1191 |
+
attentions=outputs.attentions,
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
@add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
|
| 1196 |
+
class FlaxBertForMaskedLM(FlaxBertPreTrainedModel):
|
| 1197 |
+
module_class = FlaxBertForMaskedLMModule
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
append_call_sample_docstring(FlaxBertForMaskedLM, _CHECKPOINT_FOR_DOC, FlaxMaskedLMOutput, _CONFIG_FOR_DOC)
|
| 1201 |
+
|
| 1202 |
+
|
| 1203 |
+
class FlaxBertForNextSentencePredictionModule(nn.Module):
|
| 1204 |
+
config: BertConfig
|
| 1205 |
+
dtype: jnp.dtype = jnp.float32
|
| 1206 |
+
gradient_checkpointing: bool = False
|
| 1207 |
+
|
| 1208 |
+
def setup(self):
|
| 1209 |
+
self.bert = FlaxBertModule(
|
| 1210 |
+
config=self.config,
|
| 1211 |
+
dtype=self.dtype,
|
| 1212 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1213 |
+
)
|
| 1214 |
+
self.cls = FlaxBertOnlyNSPHead(dtype=self.dtype)
|
| 1215 |
+
|
| 1216 |
+
def __call__(
|
| 1217 |
+
self,
|
| 1218 |
+
input_ids,
|
| 1219 |
+
attention_mask,
|
| 1220 |
+
token_type_ids,
|
| 1221 |
+
position_ids,
|
| 1222 |
+
head_mask,
|
| 1223 |
+
deterministic: bool = True,
|
| 1224 |
+
output_attentions: bool = False,
|
| 1225 |
+
output_hidden_states: bool = False,
|
| 1226 |
+
return_dict: bool = True,
|
| 1227 |
+
):
|
| 1228 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 1229 |
+
|
| 1230 |
+
# Model
|
| 1231 |
+
outputs = self.bert(
|
| 1232 |
+
input_ids,
|
| 1233 |
+
attention_mask,
|
| 1234 |
+
token_type_ids,
|
| 1235 |
+
position_ids,
|
| 1236 |
+
head_mask,
|
| 1237 |
+
deterministic=deterministic,
|
| 1238 |
+
output_attentions=output_attentions,
|
| 1239 |
+
output_hidden_states=output_hidden_states,
|
| 1240 |
+
return_dict=return_dict,
|
| 1241 |
+
)
|
| 1242 |
+
|
| 1243 |
+
pooled_output = outputs[1]
|
| 1244 |
+
seq_relationship_scores = self.cls(pooled_output)
|
| 1245 |
+
|
| 1246 |
+
if not return_dict:
|
| 1247 |
+
return (seq_relationship_scores,) + outputs[2:]
|
| 1248 |
+
|
| 1249 |
+
return FlaxNextSentencePredictorOutput(
|
| 1250 |
+
logits=seq_relationship_scores,
|
| 1251 |
+
hidden_states=outputs.hidden_states,
|
| 1252 |
+
attentions=outputs.attentions,
|
| 1253 |
+
)
|
| 1254 |
+
|
| 1255 |
+
|
| 1256 |
+
@add_start_docstrings(
|
| 1257 |
+
"""Bert Model with a `next sentence prediction (classification)` head on top.""",
|
| 1258 |
+
BERT_START_DOCSTRING,
|
| 1259 |
+
)
|
| 1260 |
+
class FlaxBertForNextSentencePrediction(FlaxBertPreTrainedModel):
|
| 1261 |
+
module_class = FlaxBertForNextSentencePredictionModule
|
| 1262 |
+
|
| 1263 |
+
|
| 1264 |
+
FLAX_BERT_FOR_NEXT_SENT_PRED_DOCSTRING = """
|
| 1265 |
+
Returns:
|
| 1266 |
+
|
| 1267 |
+
Example:
|
| 1268 |
+
|
| 1269 |
+
```python
|
| 1270 |
+
>>> from transformers import AutoTokenizer, FlaxBertForNextSentencePrediction
|
| 1271 |
+
|
| 1272 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 1273 |
+
>>> model = FlaxBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
|
| 1274 |
+
|
| 1275 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 1276 |
+
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
|
| 1277 |
+
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="jax")
|
| 1278 |
+
|
| 1279 |
+
>>> outputs = model(**encoding)
|
| 1280 |
+
>>> logits = outputs.logits
|
| 1281 |
+
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
|
| 1282 |
+
```
|
| 1283 |
+
"""
|
| 1284 |
+
|
| 1285 |
+
|
| 1286 |
+
overwrite_call_docstring(
|
| 1287 |
+
FlaxBertForNextSentencePrediction,
|
| 1288 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length") + FLAX_BERT_FOR_NEXT_SENT_PRED_DOCSTRING,
|
| 1289 |
+
)
|
| 1290 |
+
append_replace_return_docstrings(
|
| 1291 |
+
FlaxBertForNextSentencePrediction, output_type=FlaxNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
class FlaxBertForSequenceClassificationModule(nn.Module):
|
| 1296 |
+
config: BertConfig
|
| 1297 |
+
dtype: jnp.dtype = jnp.float32
|
| 1298 |
+
gradient_checkpointing: bool = False
|
| 1299 |
+
|
| 1300 |
+
def setup(self):
|
| 1301 |
+
self.bert = FlaxBertModule(
|
| 1302 |
+
config=self.config,
|
| 1303 |
+
dtype=self.dtype,
|
| 1304 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1305 |
+
)
|
| 1306 |
+
classifier_dropout = (
|
| 1307 |
+
self.config.classifier_dropout
|
| 1308 |
+
if self.config.classifier_dropout is not None
|
| 1309 |
+
else self.config.hidden_dropout_prob
|
| 1310 |
+
)
|
| 1311 |
+
self.dropout = nn.Dropout(rate=classifier_dropout)
|
| 1312 |
+
self.classifier = nn.Dense(
|
| 1313 |
+
self.config.num_labels,
|
| 1314 |
+
dtype=self.dtype,
|
| 1315 |
+
)
|
| 1316 |
+
|
| 1317 |
+
def __call__(
|
| 1318 |
+
self,
|
| 1319 |
+
input_ids,
|
| 1320 |
+
attention_mask,
|
| 1321 |
+
token_type_ids,
|
| 1322 |
+
position_ids,
|
| 1323 |
+
head_mask,
|
| 1324 |
+
deterministic: bool = True,
|
| 1325 |
+
output_attentions: bool = False,
|
| 1326 |
+
output_hidden_states: bool = False,
|
| 1327 |
+
return_dict: bool = True,
|
| 1328 |
+
):
|
| 1329 |
+
# Model
|
| 1330 |
+
outputs = self.bert(
|
| 1331 |
+
input_ids,
|
| 1332 |
+
attention_mask,
|
| 1333 |
+
token_type_ids,
|
| 1334 |
+
position_ids,
|
| 1335 |
+
head_mask,
|
| 1336 |
+
deterministic=deterministic,
|
| 1337 |
+
output_attentions=output_attentions,
|
| 1338 |
+
output_hidden_states=output_hidden_states,
|
| 1339 |
+
return_dict=return_dict,
|
| 1340 |
+
)
|
| 1341 |
+
|
| 1342 |
+
pooled_output = outputs[1]
|
| 1343 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 1344 |
+
logits = self.classifier(pooled_output)
|
| 1345 |
+
|
| 1346 |
+
if not return_dict:
|
| 1347 |
+
return (logits,) + outputs[2:]
|
| 1348 |
+
|
| 1349 |
+
return FlaxSequenceClassifierOutput(
|
| 1350 |
+
logits=logits,
|
| 1351 |
+
hidden_states=outputs.hidden_states,
|
| 1352 |
+
attentions=outputs.attentions,
|
| 1353 |
+
)
|
| 1354 |
+
|
| 1355 |
+
|
| 1356 |
+
@add_start_docstrings(
|
| 1357 |
+
"""
|
| 1358 |
+
Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1359 |
+
output) e.g. for GLUE tasks.
|
| 1360 |
+
""",
|
| 1361 |
+
BERT_START_DOCSTRING,
|
| 1362 |
+
)
|
| 1363 |
+
class FlaxBertForSequenceClassification(FlaxBertPreTrainedModel):
|
| 1364 |
+
module_class = FlaxBertForSequenceClassificationModule
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
append_call_sample_docstring(
|
| 1368 |
+
FlaxBertForSequenceClassification,
|
| 1369 |
+
_CHECKPOINT_FOR_DOC,
|
| 1370 |
+
FlaxSequenceClassifierOutput,
|
| 1371 |
+
_CONFIG_FOR_DOC,
|
| 1372 |
+
)
|
| 1373 |
+
|
| 1374 |
+
|
| 1375 |
+
class FlaxBertForMultipleChoiceModule(nn.Module):
|
| 1376 |
+
config: BertConfig
|
| 1377 |
+
dtype: jnp.dtype = jnp.float32
|
| 1378 |
+
gradient_checkpointing: bool = False
|
| 1379 |
+
|
| 1380 |
+
def setup(self):
|
| 1381 |
+
self.bert = FlaxBertModule(
|
| 1382 |
+
config=self.config,
|
| 1383 |
+
dtype=self.dtype,
|
| 1384 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1385 |
+
)
|
| 1386 |
+
self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
|
| 1387 |
+
self.classifier = nn.Dense(1, dtype=self.dtype)
|
| 1388 |
+
|
| 1389 |
+
def __call__(
|
| 1390 |
+
self,
|
| 1391 |
+
input_ids,
|
| 1392 |
+
attention_mask,
|
| 1393 |
+
token_type_ids,
|
| 1394 |
+
position_ids,
|
| 1395 |
+
head_mask,
|
| 1396 |
+
deterministic: bool = True,
|
| 1397 |
+
output_attentions: bool = False,
|
| 1398 |
+
output_hidden_states: bool = False,
|
| 1399 |
+
return_dict: bool = True,
|
| 1400 |
+
):
|
| 1401 |
+
num_choices = input_ids.shape[1]
|
| 1402 |
+
input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
|
| 1403 |
+
attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
|
| 1404 |
+
token_type_ids = token_type_ids.reshape(-1, token_type_ids.shape[-1]) if token_type_ids is not None else None
|
| 1405 |
+
position_ids = position_ids.reshape(-1, position_ids.shape[-1]) if position_ids is not None else None
|
| 1406 |
+
|
| 1407 |
+
# Model
|
| 1408 |
+
outputs = self.bert(
|
| 1409 |
+
input_ids,
|
| 1410 |
+
attention_mask,
|
| 1411 |
+
token_type_ids,
|
| 1412 |
+
position_ids,
|
| 1413 |
+
head_mask,
|
| 1414 |
+
deterministic=deterministic,
|
| 1415 |
+
output_attentions=output_attentions,
|
| 1416 |
+
output_hidden_states=output_hidden_states,
|
| 1417 |
+
return_dict=return_dict,
|
| 1418 |
+
)
|
| 1419 |
+
|
| 1420 |
+
pooled_output = outputs[1]
|
| 1421 |
+
pooled_output = self.dropout(pooled_output, deterministic=deterministic)
|
| 1422 |
+
logits = self.classifier(pooled_output)
|
| 1423 |
+
|
| 1424 |
+
reshaped_logits = logits.reshape(-1, num_choices)
|
| 1425 |
+
|
| 1426 |
+
if not return_dict:
|
| 1427 |
+
return (reshaped_logits,) + outputs[2:]
|
| 1428 |
+
|
| 1429 |
+
return FlaxMultipleChoiceModelOutput(
|
| 1430 |
+
logits=reshaped_logits,
|
| 1431 |
+
hidden_states=outputs.hidden_states,
|
| 1432 |
+
attentions=outputs.attentions,
|
| 1433 |
+
)
|
| 1434 |
+
|
| 1435 |
+
|
| 1436 |
+
@add_start_docstrings(
|
| 1437 |
+
"""
|
| 1438 |
+
Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1439 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1440 |
+
""",
|
| 1441 |
+
BERT_START_DOCSTRING,
|
| 1442 |
+
)
|
| 1443 |
+
class FlaxBertForMultipleChoice(FlaxBertPreTrainedModel):
|
| 1444 |
+
module_class = FlaxBertForMultipleChoiceModule
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
overwrite_call_docstring(
|
| 1448 |
+
FlaxBertForMultipleChoice, BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
| 1449 |
+
)
|
| 1450 |
+
append_call_sample_docstring(
|
| 1451 |
+
FlaxBertForMultipleChoice, _CHECKPOINT_FOR_DOC, FlaxMultipleChoiceModelOutput, _CONFIG_FOR_DOC
|
| 1452 |
+
)
|
| 1453 |
+
|
| 1454 |
+
|
| 1455 |
+
class FlaxBertForTokenClassificationModule(nn.Module):
|
| 1456 |
+
config: BertConfig
|
| 1457 |
+
dtype: jnp.dtype = jnp.float32
|
| 1458 |
+
gradient_checkpointing: bool = False
|
| 1459 |
+
|
| 1460 |
+
def setup(self):
|
| 1461 |
+
self.bert = FlaxBertModule(
|
| 1462 |
+
config=self.config,
|
| 1463 |
+
dtype=self.dtype,
|
| 1464 |
+
add_pooling_layer=False,
|
| 1465 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1466 |
+
)
|
| 1467 |
+
classifier_dropout = (
|
| 1468 |
+
self.config.classifier_dropout
|
| 1469 |
+
if self.config.classifier_dropout is not None
|
| 1470 |
+
else self.config.hidden_dropout_prob
|
| 1471 |
+
)
|
| 1472 |
+
self.dropout = nn.Dropout(rate=classifier_dropout)
|
| 1473 |
+
self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 1474 |
+
|
| 1475 |
+
def __call__(
|
| 1476 |
+
self,
|
| 1477 |
+
input_ids,
|
| 1478 |
+
attention_mask,
|
| 1479 |
+
token_type_ids,
|
| 1480 |
+
position_ids,
|
| 1481 |
+
head_mask,
|
| 1482 |
+
deterministic: bool = True,
|
| 1483 |
+
output_attentions: bool = False,
|
| 1484 |
+
output_hidden_states: bool = False,
|
| 1485 |
+
return_dict: bool = True,
|
| 1486 |
+
):
|
| 1487 |
+
# Model
|
| 1488 |
+
outputs = self.bert(
|
| 1489 |
+
input_ids,
|
| 1490 |
+
attention_mask,
|
| 1491 |
+
token_type_ids,
|
| 1492 |
+
position_ids,
|
| 1493 |
+
head_mask,
|
| 1494 |
+
deterministic=deterministic,
|
| 1495 |
+
output_attentions=output_attentions,
|
| 1496 |
+
output_hidden_states=output_hidden_states,
|
| 1497 |
+
return_dict=return_dict,
|
| 1498 |
+
)
|
| 1499 |
+
|
| 1500 |
+
hidden_states = outputs[0]
|
| 1501 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 1502 |
+
logits = self.classifier(hidden_states)
|
| 1503 |
+
|
| 1504 |
+
if not return_dict:
|
| 1505 |
+
return (logits,) + outputs[1:]
|
| 1506 |
+
|
| 1507 |
+
return FlaxTokenClassifierOutput(
|
| 1508 |
+
logits=logits,
|
| 1509 |
+
hidden_states=outputs.hidden_states,
|
| 1510 |
+
attentions=outputs.attentions,
|
| 1511 |
+
)
|
| 1512 |
+
|
| 1513 |
+
|
| 1514 |
+
@add_start_docstrings(
|
| 1515 |
+
"""
|
| 1516 |
+
Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1517 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1518 |
+
""",
|
| 1519 |
+
BERT_START_DOCSTRING,
|
| 1520 |
+
)
|
| 1521 |
+
class FlaxBertForTokenClassification(FlaxBertPreTrainedModel):
|
| 1522 |
+
module_class = FlaxBertForTokenClassificationModule
|
| 1523 |
+
|
| 1524 |
+
|
| 1525 |
+
append_call_sample_docstring(
|
| 1526 |
+
FlaxBertForTokenClassification, _CHECKPOINT_FOR_DOC, FlaxTokenClassifierOutput, _CONFIG_FOR_DOC
|
| 1527 |
+
)
|
| 1528 |
+
|
| 1529 |
+
|
| 1530 |
+
class FlaxBertForQuestionAnsweringModule(nn.Module):
|
| 1531 |
+
config: BertConfig
|
| 1532 |
+
dtype: jnp.dtype = jnp.float32
|
| 1533 |
+
gradient_checkpointing: bool = False
|
| 1534 |
+
|
| 1535 |
+
def setup(self):
|
| 1536 |
+
self.bert = FlaxBertModule(
|
| 1537 |
+
config=self.config,
|
| 1538 |
+
dtype=self.dtype,
|
| 1539 |
+
add_pooling_layer=False,
|
| 1540 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1541 |
+
)
|
| 1542 |
+
self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
|
| 1543 |
+
|
| 1544 |
+
def __call__(
|
| 1545 |
+
self,
|
| 1546 |
+
input_ids,
|
| 1547 |
+
attention_mask,
|
| 1548 |
+
token_type_ids,
|
| 1549 |
+
position_ids,
|
| 1550 |
+
head_mask,
|
| 1551 |
+
deterministic: bool = True,
|
| 1552 |
+
output_attentions: bool = False,
|
| 1553 |
+
output_hidden_states: bool = False,
|
| 1554 |
+
return_dict: bool = True,
|
| 1555 |
+
):
|
| 1556 |
+
# Model
|
| 1557 |
+
outputs = self.bert(
|
| 1558 |
+
input_ids,
|
| 1559 |
+
attention_mask,
|
| 1560 |
+
token_type_ids,
|
| 1561 |
+
position_ids,
|
| 1562 |
+
head_mask,
|
| 1563 |
+
deterministic=deterministic,
|
| 1564 |
+
output_attentions=output_attentions,
|
| 1565 |
+
output_hidden_states=output_hidden_states,
|
| 1566 |
+
return_dict=return_dict,
|
| 1567 |
+
)
|
| 1568 |
+
|
| 1569 |
+
hidden_states = outputs[0]
|
| 1570 |
+
|
| 1571 |
+
logits = self.qa_outputs(hidden_states)
|
| 1572 |
+
start_logits, end_logits = jnp.split(logits, self.config.num_labels, axis=-1)
|
| 1573 |
+
start_logits = start_logits.squeeze(-1)
|
| 1574 |
+
end_logits = end_logits.squeeze(-1)
|
| 1575 |
+
|
| 1576 |
+
if not return_dict:
|
| 1577 |
+
return (start_logits, end_logits) + outputs[1:]
|
| 1578 |
+
|
| 1579 |
+
return FlaxQuestionAnsweringModelOutput(
|
| 1580 |
+
start_logits=start_logits,
|
| 1581 |
+
end_logits=end_logits,
|
| 1582 |
+
hidden_states=outputs.hidden_states,
|
| 1583 |
+
attentions=outputs.attentions,
|
| 1584 |
+
)
|
| 1585 |
+
|
| 1586 |
+
|
| 1587 |
+
@add_start_docstrings(
|
| 1588 |
+
"""
|
| 1589 |
+
Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 1590 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1591 |
+
""",
|
| 1592 |
+
BERT_START_DOCSTRING,
|
| 1593 |
+
)
|
| 1594 |
+
class FlaxBertForQuestionAnswering(FlaxBertPreTrainedModel):
|
| 1595 |
+
module_class = FlaxBertForQuestionAnsweringModule
|
| 1596 |
+
|
| 1597 |
+
|
| 1598 |
+
append_call_sample_docstring(
|
| 1599 |
+
FlaxBertForQuestionAnswering,
|
| 1600 |
+
_CHECKPOINT_FOR_DOC,
|
| 1601 |
+
FlaxQuestionAnsweringModelOutput,
|
| 1602 |
+
_CONFIG_FOR_DOC,
|
| 1603 |
+
)
|
| 1604 |
+
|
| 1605 |
+
|
| 1606 |
+
class FlaxBertForCausalLMModule(nn.Module):
|
| 1607 |
+
config: BertConfig
|
| 1608 |
+
dtype: jnp.dtype = jnp.float32
|
| 1609 |
+
gradient_checkpointing: bool = False
|
| 1610 |
+
|
| 1611 |
+
def setup(self):
|
| 1612 |
+
self.bert = FlaxBertModule(
|
| 1613 |
+
config=self.config,
|
| 1614 |
+
add_pooling_layer=False,
|
| 1615 |
+
dtype=self.dtype,
|
| 1616 |
+
gradient_checkpointing=self.gradient_checkpointing,
|
| 1617 |
+
)
|
| 1618 |
+
self.cls = FlaxBertOnlyMLMHead(config=self.config, dtype=self.dtype)
|
| 1619 |
+
|
| 1620 |
+
def __call__(
|
| 1621 |
+
self,
|
| 1622 |
+
input_ids,
|
| 1623 |
+
attention_mask,
|
| 1624 |
+
position_ids,
|
| 1625 |
+
token_type_ids: Optional[jnp.ndarray] = None,
|
| 1626 |
+
head_mask: Optional[jnp.ndarray] = None,
|
| 1627 |
+
encoder_hidden_states: Optional[jnp.ndarray] = None,
|
| 1628 |
+
encoder_attention_mask: Optional[jnp.ndarray] = None,
|
| 1629 |
+
init_cache: bool = False,
|
| 1630 |
+
deterministic: bool = True,
|
| 1631 |
+
output_attentions: bool = False,
|
| 1632 |
+
output_hidden_states: bool = False,
|
| 1633 |
+
return_dict: bool = True,
|
| 1634 |
+
):
|
| 1635 |
+
# Model
|
| 1636 |
+
outputs = self.bert(
|
| 1637 |
+
input_ids,
|
| 1638 |
+
attention_mask,
|
| 1639 |
+
token_type_ids,
|
| 1640 |
+
position_ids,
|
| 1641 |
+
head_mask,
|
| 1642 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1643 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1644 |
+
init_cache=init_cache,
|
| 1645 |
+
deterministic=deterministic,
|
| 1646 |
+
output_attentions=output_attentions,
|
| 1647 |
+
output_hidden_states=output_hidden_states,
|
| 1648 |
+
return_dict=return_dict,
|
| 1649 |
+
)
|
| 1650 |
+
|
| 1651 |
+
hidden_states = outputs[0]
|
| 1652 |
+
if self.config.tie_word_embeddings:
|
| 1653 |
+
shared_embedding = self.bert.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
|
| 1654 |
+
else:
|
| 1655 |
+
shared_embedding = None
|
| 1656 |
+
|
| 1657 |
+
# Compute the prediction scores
|
| 1658 |
+
logits = self.cls(hidden_states, shared_embedding=shared_embedding)
|
| 1659 |
+
|
| 1660 |
+
if not return_dict:
|
| 1661 |
+
return (logits,) + outputs[1:]
|
| 1662 |
+
|
| 1663 |
+
return FlaxCausalLMOutputWithCrossAttentions(
|
| 1664 |
+
logits=logits,
|
| 1665 |
+
hidden_states=outputs.hidden_states,
|
| 1666 |
+
attentions=outputs.attentions,
|
| 1667 |
+
cross_attentions=outputs.cross_attentions,
|
| 1668 |
+
)
|
| 1669 |
+
|
| 1670 |
+
|
| 1671 |
+
@add_start_docstrings(
|
| 1672 |
+
"""
|
| 1673 |
+
Bert Model with a language modeling head on top (a linear layer on top of the hidden-states output) e.g for
|
| 1674 |
+
autoregressive tasks.
|
| 1675 |
+
""",
|
| 1676 |
+
BERT_START_DOCSTRING,
|
| 1677 |
+
)
|
| 1678 |
+
class FlaxBertForCausalLM(FlaxBertPreTrainedModel):
|
| 1679 |
+
module_class = FlaxBertForCausalLMModule
|
| 1680 |
+
|
| 1681 |
+
def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
|
| 1682 |
+
# initializing the cache
|
| 1683 |
+
batch_size, seq_length = input_ids.shape
|
| 1684 |
+
|
| 1685 |
+
past_key_values = self.init_cache(batch_size, max_length)
|
| 1686 |
+
# Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
|
| 1687 |
+
# But since the decoder uses a causal mask, those positions are masked anyway.
|
| 1688 |
+
# Thus, we can create a single static attention_mask here, which is more efficient for compilation
|
| 1689 |
+
extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
|
| 1690 |
+
if attention_mask is not None:
|
| 1691 |
+
position_ids = attention_mask.cumsum(axis=-1) - 1
|
| 1692 |
+
extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
|
| 1693 |
+
else:
|
| 1694 |
+
position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
|
| 1695 |
+
|
| 1696 |
+
return {
|
| 1697 |
+
"past_key_values": past_key_values,
|
| 1698 |
+
"attention_mask": extended_attention_mask,
|
| 1699 |
+
"position_ids": position_ids,
|
| 1700 |
+
}
|
| 1701 |
+
|
| 1702 |
+
def update_inputs_for_generation(self, model_outputs, model_kwargs):
|
| 1703 |
+
model_kwargs["past_key_values"] = model_outputs.past_key_values
|
| 1704 |
+
model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
|
| 1705 |
+
return model_kwargs
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
append_call_sample_docstring(
|
| 1709 |
+
FlaxBertForCausalLM,
|
| 1710 |
+
_CHECKPOINT_FOR_DOC,
|
| 1711 |
+
FlaxCausalLMOutputWithCrossAttentions,
|
| 1712 |
+
_CONFIG_FOR_DOC,
|
| 1713 |
+
)
|
| 1714 |
+
|
| 1715 |
+
|
| 1716 |
+
__all__ = [
|
| 1717 |
+
"FlaxBertForCausalLM",
|
| 1718 |
+
"FlaxBertForMaskedLM",
|
| 1719 |
+
"FlaxBertForMultipleChoice",
|
| 1720 |
+
"FlaxBertForNextSentencePrediction",
|
| 1721 |
+
"FlaxBertForPreTraining",
|
| 1722 |
+
"FlaxBertForQuestionAnswering",
|
| 1723 |
+
"FlaxBertForSequenceClassification",
|
| 1724 |
+
"FlaxBertForTokenClassification",
|
| 1725 |
+
"FlaxBertModel",
|
| 1726 |
+
"FlaxBertPreTrainedModel",
|
| 1727 |
+
]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/modeling_tf_bert.py
ADDED
|
@@ -0,0 +1,2126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""TF 2.0 BERT model."""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import math
|
| 21 |
+
import warnings
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Dict, Optional, Tuple, Union
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import tensorflow as tf
|
| 27 |
+
|
| 28 |
+
from ...activations_tf import get_tf_activation
|
| 29 |
+
from ...modeling_tf_outputs import (
|
| 30 |
+
TFBaseModelOutputWithPastAndCrossAttentions,
|
| 31 |
+
TFBaseModelOutputWithPoolingAndCrossAttentions,
|
| 32 |
+
TFCausalLMOutputWithCrossAttentions,
|
| 33 |
+
TFMaskedLMOutput,
|
| 34 |
+
TFMultipleChoiceModelOutput,
|
| 35 |
+
TFNextSentencePredictorOutput,
|
| 36 |
+
TFQuestionAnsweringModelOutput,
|
| 37 |
+
TFSequenceClassifierOutput,
|
| 38 |
+
TFTokenClassifierOutput,
|
| 39 |
+
)
|
| 40 |
+
from ...modeling_tf_utils import (
|
| 41 |
+
TFCausalLanguageModelingLoss,
|
| 42 |
+
TFMaskedLanguageModelingLoss,
|
| 43 |
+
TFModelInputType,
|
| 44 |
+
TFMultipleChoiceLoss,
|
| 45 |
+
TFNextSentencePredictionLoss,
|
| 46 |
+
TFPreTrainedModel,
|
| 47 |
+
TFQuestionAnsweringLoss,
|
| 48 |
+
TFSequenceClassificationLoss,
|
| 49 |
+
TFTokenClassificationLoss,
|
| 50 |
+
get_initializer,
|
| 51 |
+
keras,
|
| 52 |
+
keras_serializable,
|
| 53 |
+
unpack_inputs,
|
| 54 |
+
)
|
| 55 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 56 |
+
from ...utils import (
|
| 57 |
+
ModelOutput,
|
| 58 |
+
add_code_sample_docstrings,
|
| 59 |
+
add_start_docstrings,
|
| 60 |
+
add_start_docstrings_to_model_forward,
|
| 61 |
+
logging,
|
| 62 |
+
replace_return_docstrings,
|
| 63 |
+
)
|
| 64 |
+
from .configuration_bert import BertConfig
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
logger = logging.get_logger(__name__)
|
| 68 |
+
|
| 69 |
+
_CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
|
| 70 |
+
_CONFIG_FOR_DOC = "BertConfig"
|
| 71 |
+
|
| 72 |
+
# TokenClassification docstring
|
| 73 |
+
_CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
|
| 74 |
+
_TOKEN_CLASS_EXPECTED_OUTPUT = (
|
| 75 |
+
"['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
|
| 76 |
+
)
|
| 77 |
+
_TOKEN_CLASS_EXPECTED_LOSS = 0.01
|
| 78 |
+
|
| 79 |
+
# QuestionAnswering docstring
|
| 80 |
+
_CHECKPOINT_FOR_QA = "ydshieh/bert-base-cased-squad2"
|
| 81 |
+
_QA_EXPECTED_OUTPUT = "'a nice puppet'"
|
| 82 |
+
_QA_EXPECTED_LOSS = 7.41
|
| 83 |
+
_QA_TARGET_START_INDEX = 14
|
| 84 |
+
_QA_TARGET_END_INDEX = 15
|
| 85 |
+
|
| 86 |
+
# SequenceClassification docstring
|
| 87 |
+
_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ydshieh/bert-base-uncased-yelp-polarity"
|
| 88 |
+
_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
|
| 89 |
+
_SEQ_CLASS_EXPECTED_LOSS = 0.01
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class TFBertPreTrainingLoss:
|
| 93 |
+
"""
|
| 94 |
+
Loss function suitable for BERT-like pretraining, that is, the task of pretraining a language model by combining
|
| 95 |
+
NSP + MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss
|
| 96 |
+
computation.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
|
| 100 |
+
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=keras.losses.Reduction.NONE)
|
| 101 |
+
|
| 102 |
+
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
|
| 103 |
+
unmasked_lm_losses = loss_fn(y_true=tf.nn.relu(labels["labels"]), y_pred=logits[0])
|
| 104 |
+
# make sure only labels that are not equal to -100
|
| 105 |
+
# are taken into account for the loss computation
|
| 106 |
+
lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype)
|
| 107 |
+
masked_lm_losses = unmasked_lm_losses * lm_loss_mask
|
| 108 |
+
reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses) / tf.reduce_sum(lm_loss_mask)
|
| 109 |
+
|
| 110 |
+
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
|
| 111 |
+
unmasked_ns_loss = loss_fn(y_true=tf.nn.relu(labels["next_sentence_label"]), y_pred=logits[1])
|
| 112 |
+
ns_loss_mask = tf.cast(labels["next_sentence_label"] != -100, dtype=unmasked_ns_loss.dtype)
|
| 113 |
+
masked_ns_loss = unmasked_ns_loss * ns_loss_mask
|
| 114 |
+
|
| 115 |
+
reduced_masked_ns_loss = tf.reduce_sum(masked_ns_loss) / tf.reduce_sum(ns_loss_mask)
|
| 116 |
+
|
| 117 |
+
return tf.reshape(reduced_masked_lm_loss + reduced_masked_ns_loss, (1,))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class TFBertEmbeddings(keras.layers.Layer):
|
| 121 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
| 122 |
+
|
| 123 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 124 |
+
super().__init__(**kwargs)
|
| 125 |
+
|
| 126 |
+
self.config = config
|
| 127 |
+
self.hidden_size = config.hidden_size
|
| 128 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 129 |
+
self.initializer_range = config.initializer_range
|
| 130 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 131 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 132 |
+
|
| 133 |
+
def build(self, input_shape=None):
|
| 134 |
+
with tf.name_scope("word_embeddings"):
|
| 135 |
+
self.weight = self.add_weight(
|
| 136 |
+
name="weight",
|
| 137 |
+
shape=[self.config.vocab_size, self.hidden_size],
|
| 138 |
+
initializer=get_initializer(self.initializer_range),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
with tf.name_scope("token_type_embeddings"):
|
| 142 |
+
self.token_type_embeddings = self.add_weight(
|
| 143 |
+
name="embeddings",
|
| 144 |
+
shape=[self.config.type_vocab_size, self.hidden_size],
|
| 145 |
+
initializer=get_initializer(self.initializer_range),
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
with tf.name_scope("position_embeddings"):
|
| 149 |
+
self.position_embeddings = self.add_weight(
|
| 150 |
+
name="embeddings",
|
| 151 |
+
shape=[self.max_position_embeddings, self.hidden_size],
|
| 152 |
+
initializer=get_initializer(self.initializer_range),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
if self.built:
|
| 156 |
+
return
|
| 157 |
+
self.built = True
|
| 158 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 159 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 160 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 161 |
+
|
| 162 |
+
def call(
|
| 163 |
+
self,
|
| 164 |
+
input_ids: tf.Tensor = None,
|
| 165 |
+
position_ids: tf.Tensor = None,
|
| 166 |
+
token_type_ids: tf.Tensor = None,
|
| 167 |
+
inputs_embeds: tf.Tensor = None,
|
| 168 |
+
past_key_values_length=0,
|
| 169 |
+
training: bool = False,
|
| 170 |
+
) -> tf.Tensor:
|
| 171 |
+
"""
|
| 172 |
+
Applies embedding based on inputs tensor.
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
| 176 |
+
"""
|
| 177 |
+
if input_ids is None and inputs_embeds is None:
|
| 178 |
+
raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
|
| 179 |
+
|
| 180 |
+
if input_ids is not None:
|
| 181 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
| 182 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
| 183 |
+
|
| 184 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 185 |
+
|
| 186 |
+
if token_type_ids is None:
|
| 187 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 188 |
+
|
| 189 |
+
if position_ids is None:
|
| 190 |
+
position_ids = tf.expand_dims(
|
| 191 |
+
tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
|
| 195 |
+
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
|
| 196 |
+
final_embeddings = inputs_embeds + position_embeds + token_type_embeds
|
| 197 |
+
final_embeddings = self.LayerNorm(inputs=final_embeddings)
|
| 198 |
+
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
|
| 199 |
+
|
| 200 |
+
return final_embeddings
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class TFBertSelfAttention(keras.layers.Layer):
|
| 204 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 205 |
+
super().__init__(**kwargs)
|
| 206 |
+
|
| 207 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 208 |
+
raise ValueError(
|
| 209 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number "
|
| 210 |
+
f"of attention heads ({config.num_attention_heads})"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
self.num_attention_heads = config.num_attention_heads
|
| 214 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 215 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 216 |
+
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
|
| 217 |
+
|
| 218 |
+
self.query = keras.layers.Dense(
|
| 219 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
|
| 220 |
+
)
|
| 221 |
+
self.key = keras.layers.Dense(
|
| 222 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
|
| 223 |
+
)
|
| 224 |
+
self.value = keras.layers.Dense(
|
| 225 |
+
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
|
| 226 |
+
)
|
| 227 |
+
self.dropout = keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
|
| 228 |
+
|
| 229 |
+
self.is_decoder = config.is_decoder
|
| 230 |
+
self.config = config
|
| 231 |
+
|
| 232 |
+
def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
|
| 233 |
+
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
|
| 234 |
+
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
|
| 235 |
+
|
| 236 |
+
# Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
|
| 237 |
+
return tf.transpose(tensor, perm=[0, 2, 1, 3])
|
| 238 |
+
|
| 239 |
+
def call(
|
| 240 |
+
self,
|
| 241 |
+
hidden_states: tf.Tensor,
|
| 242 |
+
attention_mask: tf.Tensor,
|
| 243 |
+
head_mask: tf.Tensor,
|
| 244 |
+
encoder_hidden_states: tf.Tensor,
|
| 245 |
+
encoder_attention_mask: tf.Tensor,
|
| 246 |
+
past_key_value: Tuple[tf.Tensor],
|
| 247 |
+
output_attentions: bool,
|
| 248 |
+
training: bool = False,
|
| 249 |
+
) -> Tuple[tf.Tensor]:
|
| 250 |
+
batch_size = shape_list(hidden_states)[0]
|
| 251 |
+
mixed_query_layer = self.query(inputs=hidden_states)
|
| 252 |
+
|
| 253 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 254 |
+
# and values come from an encoder; the attention mask needs to be
|
| 255 |
+
# such that the encoder's padding tokens are not attended to.
|
| 256 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 257 |
+
|
| 258 |
+
if is_cross_attention and past_key_value is not None:
|
| 259 |
+
# reuse k,v, cross_attentions
|
| 260 |
+
key_layer = past_key_value[0]
|
| 261 |
+
value_layer = past_key_value[1]
|
| 262 |
+
attention_mask = encoder_attention_mask
|
| 263 |
+
elif is_cross_attention:
|
| 264 |
+
key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
|
| 265 |
+
value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
|
| 266 |
+
attention_mask = encoder_attention_mask
|
| 267 |
+
elif past_key_value is not None:
|
| 268 |
+
key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
|
| 269 |
+
value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
|
| 270 |
+
key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
|
| 271 |
+
value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
|
| 272 |
+
else:
|
| 273 |
+
key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
|
| 274 |
+
value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
|
| 275 |
+
|
| 276 |
+
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
|
| 277 |
+
|
| 278 |
+
if self.is_decoder:
|
| 279 |
+
# if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
|
| 280 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 281 |
+
# key/value_states (first "if" case)
|
| 282 |
+
# if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
|
| 283 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 284 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 285 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 286 |
+
past_key_value = (key_layer, value_layer)
|
| 287 |
+
|
| 288 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 289 |
+
# (batch size, num_heads, seq_len_q, seq_len_k)
|
| 290 |
+
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
|
| 291 |
+
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
|
| 292 |
+
attention_scores = tf.divide(attention_scores, dk)
|
| 293 |
+
|
| 294 |
+
if attention_mask is not None:
|
| 295 |
+
# Apply the attention mask is (precomputed for all layers in TFBertModel call() function)
|
| 296 |
+
attention_scores = tf.add(attention_scores, attention_mask)
|
| 297 |
+
|
| 298 |
+
# Normalize the attention scores to probabilities.
|
| 299 |
+
attention_probs = stable_softmax(logits=attention_scores, axis=-1)
|
| 300 |
+
|
| 301 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 302 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 303 |
+
attention_probs = self.dropout(inputs=attention_probs, training=training)
|
| 304 |
+
|
| 305 |
+
# Mask heads if we want to
|
| 306 |
+
if head_mask is not None:
|
| 307 |
+
attention_probs = tf.multiply(attention_probs, head_mask)
|
| 308 |
+
|
| 309 |
+
attention_output = tf.matmul(attention_probs, value_layer)
|
| 310 |
+
attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
|
| 311 |
+
|
| 312 |
+
# (batch_size, seq_len_q, all_head_size)
|
| 313 |
+
attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
|
| 314 |
+
outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
|
| 315 |
+
|
| 316 |
+
if self.is_decoder:
|
| 317 |
+
outputs = outputs + (past_key_value,)
|
| 318 |
+
return outputs
|
| 319 |
+
|
| 320 |
+
def build(self, input_shape=None):
|
| 321 |
+
if self.built:
|
| 322 |
+
return
|
| 323 |
+
self.built = True
|
| 324 |
+
if getattr(self, "query", None) is not None:
|
| 325 |
+
with tf.name_scope(self.query.name):
|
| 326 |
+
self.query.build([None, None, self.config.hidden_size])
|
| 327 |
+
if getattr(self, "key", None) is not None:
|
| 328 |
+
with tf.name_scope(self.key.name):
|
| 329 |
+
self.key.build([None, None, self.config.hidden_size])
|
| 330 |
+
if getattr(self, "value", None) is not None:
|
| 331 |
+
with tf.name_scope(self.value.name):
|
| 332 |
+
self.value.build([None, None, self.config.hidden_size])
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class TFBertSelfOutput(keras.layers.Layer):
|
| 336 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 337 |
+
super().__init__(**kwargs)
|
| 338 |
+
|
| 339 |
+
self.dense = keras.layers.Dense(
|
| 340 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 341 |
+
)
|
| 342 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 343 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 344 |
+
self.config = config
|
| 345 |
+
|
| 346 |
+
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 347 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 348 |
+
hidden_states = self.dropout(inputs=hidden_states, training=training)
|
| 349 |
+
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 350 |
+
|
| 351 |
+
return hidden_states
|
| 352 |
+
|
| 353 |
+
def build(self, input_shape=None):
|
| 354 |
+
if self.built:
|
| 355 |
+
return
|
| 356 |
+
self.built = True
|
| 357 |
+
if getattr(self, "dense", None) is not None:
|
| 358 |
+
with tf.name_scope(self.dense.name):
|
| 359 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 360 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 361 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 362 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class TFBertAttention(keras.layers.Layer):
|
| 366 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 367 |
+
super().__init__(**kwargs)
|
| 368 |
+
|
| 369 |
+
self.self_attention = TFBertSelfAttention(config, name="self")
|
| 370 |
+
self.dense_output = TFBertSelfOutput(config, name="output")
|
| 371 |
+
|
| 372 |
+
def prune_heads(self, heads):
|
| 373 |
+
raise NotImplementedError
|
| 374 |
+
|
| 375 |
+
def call(
|
| 376 |
+
self,
|
| 377 |
+
input_tensor: tf.Tensor,
|
| 378 |
+
attention_mask: tf.Tensor,
|
| 379 |
+
head_mask: tf.Tensor,
|
| 380 |
+
encoder_hidden_states: tf.Tensor,
|
| 381 |
+
encoder_attention_mask: tf.Tensor,
|
| 382 |
+
past_key_value: Tuple[tf.Tensor],
|
| 383 |
+
output_attentions: bool,
|
| 384 |
+
training: bool = False,
|
| 385 |
+
) -> Tuple[tf.Tensor]:
|
| 386 |
+
self_outputs = self.self_attention(
|
| 387 |
+
hidden_states=input_tensor,
|
| 388 |
+
attention_mask=attention_mask,
|
| 389 |
+
head_mask=head_mask,
|
| 390 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 391 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 392 |
+
past_key_value=past_key_value,
|
| 393 |
+
output_attentions=output_attentions,
|
| 394 |
+
training=training,
|
| 395 |
+
)
|
| 396 |
+
attention_output = self.dense_output(
|
| 397 |
+
hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
|
| 398 |
+
)
|
| 399 |
+
# add attentions (possibly with past_key_value) if we output them
|
| 400 |
+
outputs = (attention_output,) + self_outputs[1:]
|
| 401 |
+
|
| 402 |
+
return outputs
|
| 403 |
+
|
| 404 |
+
def build(self, input_shape=None):
|
| 405 |
+
if self.built:
|
| 406 |
+
return
|
| 407 |
+
self.built = True
|
| 408 |
+
if getattr(self, "self_attention", None) is not None:
|
| 409 |
+
with tf.name_scope(self.self_attention.name):
|
| 410 |
+
self.self_attention.build(None)
|
| 411 |
+
if getattr(self, "dense_output", None) is not None:
|
| 412 |
+
with tf.name_scope(self.dense_output.name):
|
| 413 |
+
self.dense_output.build(None)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
class TFBertIntermediate(keras.layers.Layer):
|
| 417 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 418 |
+
super().__init__(**kwargs)
|
| 419 |
+
|
| 420 |
+
self.dense = keras.layers.Dense(
|
| 421 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
if isinstance(config.hidden_act, str):
|
| 425 |
+
self.intermediate_act_fn = get_tf_activation(config.hidden_act)
|
| 426 |
+
else:
|
| 427 |
+
self.intermediate_act_fn = config.hidden_act
|
| 428 |
+
self.config = config
|
| 429 |
+
|
| 430 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 431 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 432 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 433 |
+
|
| 434 |
+
return hidden_states
|
| 435 |
+
|
| 436 |
+
def build(self, input_shape=None):
|
| 437 |
+
if self.built:
|
| 438 |
+
return
|
| 439 |
+
self.built = True
|
| 440 |
+
if getattr(self, "dense", None) is not None:
|
| 441 |
+
with tf.name_scope(self.dense.name):
|
| 442 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class TFBertOutput(keras.layers.Layer):
|
| 446 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 447 |
+
super().__init__(**kwargs)
|
| 448 |
+
|
| 449 |
+
self.dense = keras.layers.Dense(
|
| 450 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 451 |
+
)
|
| 452 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 453 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 454 |
+
self.config = config
|
| 455 |
+
|
| 456 |
+
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 457 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 458 |
+
hidden_states = self.dropout(inputs=hidden_states, training=training)
|
| 459 |
+
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 460 |
+
|
| 461 |
+
return hidden_states
|
| 462 |
+
|
| 463 |
+
def build(self, input_shape=None):
|
| 464 |
+
if self.built:
|
| 465 |
+
return
|
| 466 |
+
self.built = True
|
| 467 |
+
if getattr(self, "dense", None) is not None:
|
| 468 |
+
with tf.name_scope(self.dense.name):
|
| 469 |
+
self.dense.build([None, None, self.config.intermediate_size])
|
| 470 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 471 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 472 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class TFBertLayer(keras.layers.Layer):
|
| 476 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 477 |
+
super().__init__(**kwargs)
|
| 478 |
+
|
| 479 |
+
self.attention = TFBertAttention(config, name="attention")
|
| 480 |
+
self.is_decoder = config.is_decoder
|
| 481 |
+
self.add_cross_attention = config.add_cross_attention
|
| 482 |
+
if self.add_cross_attention:
|
| 483 |
+
if not self.is_decoder:
|
| 484 |
+
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
|
| 485 |
+
self.crossattention = TFBertAttention(config, name="crossattention")
|
| 486 |
+
self.intermediate = TFBertIntermediate(config, name="intermediate")
|
| 487 |
+
self.bert_output = TFBertOutput(config, name="output")
|
| 488 |
+
|
| 489 |
+
def call(
|
| 490 |
+
self,
|
| 491 |
+
hidden_states: tf.Tensor,
|
| 492 |
+
attention_mask: tf.Tensor,
|
| 493 |
+
head_mask: tf.Tensor,
|
| 494 |
+
encoder_hidden_states: tf.Tensor | None,
|
| 495 |
+
encoder_attention_mask: tf.Tensor | None,
|
| 496 |
+
past_key_value: Tuple[tf.Tensor] | None,
|
| 497 |
+
output_attentions: bool,
|
| 498 |
+
training: bool = False,
|
| 499 |
+
) -> Tuple[tf.Tensor]:
|
| 500 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 501 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 502 |
+
self_attention_outputs = self.attention(
|
| 503 |
+
input_tensor=hidden_states,
|
| 504 |
+
attention_mask=attention_mask,
|
| 505 |
+
head_mask=head_mask,
|
| 506 |
+
encoder_hidden_states=None,
|
| 507 |
+
encoder_attention_mask=None,
|
| 508 |
+
past_key_value=self_attn_past_key_value,
|
| 509 |
+
output_attentions=output_attentions,
|
| 510 |
+
training=training,
|
| 511 |
+
)
|
| 512 |
+
attention_output = self_attention_outputs[0]
|
| 513 |
+
|
| 514 |
+
# if decoder, the last output is tuple of self-attn cache
|
| 515 |
+
if self.is_decoder:
|
| 516 |
+
outputs = self_attention_outputs[1:-1]
|
| 517 |
+
present_key_value = self_attention_outputs[-1]
|
| 518 |
+
else:
|
| 519 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 520 |
+
|
| 521 |
+
cross_attn_present_key_value = None
|
| 522 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
| 523 |
+
if not hasattr(self, "crossattention"):
|
| 524 |
+
raise ValueError(
|
| 525 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
| 526 |
+
" by setting `config.add_cross_attention=True`"
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
| 530 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 531 |
+
cross_attention_outputs = self.crossattention(
|
| 532 |
+
input_tensor=attention_output,
|
| 533 |
+
attention_mask=attention_mask,
|
| 534 |
+
head_mask=head_mask,
|
| 535 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 536 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 537 |
+
past_key_value=cross_attn_past_key_value,
|
| 538 |
+
output_attentions=output_attentions,
|
| 539 |
+
training=training,
|
| 540 |
+
)
|
| 541 |
+
attention_output = cross_attention_outputs[0]
|
| 542 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 543 |
+
|
| 544 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
| 545 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
| 546 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 547 |
+
|
| 548 |
+
intermediate_output = self.intermediate(hidden_states=attention_output)
|
| 549 |
+
layer_output = self.bert_output(
|
| 550 |
+
hidden_states=intermediate_output, input_tensor=attention_output, training=training
|
| 551 |
+
)
|
| 552 |
+
outputs = (layer_output,) + outputs # add attentions if we output them
|
| 553 |
+
|
| 554 |
+
# if decoder, return the attn key/values as the last output
|
| 555 |
+
if self.is_decoder:
|
| 556 |
+
outputs = outputs + (present_key_value,)
|
| 557 |
+
|
| 558 |
+
return outputs
|
| 559 |
+
|
| 560 |
+
def build(self, input_shape=None):
|
| 561 |
+
if self.built:
|
| 562 |
+
return
|
| 563 |
+
self.built = True
|
| 564 |
+
if getattr(self, "attention", None) is not None:
|
| 565 |
+
with tf.name_scope(self.attention.name):
|
| 566 |
+
self.attention.build(None)
|
| 567 |
+
if getattr(self, "intermediate", None) is not None:
|
| 568 |
+
with tf.name_scope(self.intermediate.name):
|
| 569 |
+
self.intermediate.build(None)
|
| 570 |
+
if getattr(self, "bert_output", None) is not None:
|
| 571 |
+
with tf.name_scope(self.bert_output.name):
|
| 572 |
+
self.bert_output.build(None)
|
| 573 |
+
if getattr(self, "crossattention", None) is not None:
|
| 574 |
+
with tf.name_scope(self.crossattention.name):
|
| 575 |
+
self.crossattention.build(None)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class TFBertEncoder(keras.layers.Layer):
|
| 579 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 580 |
+
super().__init__(**kwargs)
|
| 581 |
+
self.config = config
|
| 582 |
+
self.layer = [TFBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
|
| 583 |
+
|
| 584 |
+
def call(
|
| 585 |
+
self,
|
| 586 |
+
hidden_states: tf.Tensor,
|
| 587 |
+
attention_mask: tf.Tensor,
|
| 588 |
+
head_mask: tf.Tensor,
|
| 589 |
+
encoder_hidden_states: tf.Tensor | None,
|
| 590 |
+
encoder_attention_mask: tf.Tensor | None,
|
| 591 |
+
past_key_values: Tuple[Tuple[tf.Tensor]] | None,
|
| 592 |
+
use_cache: Optional[bool],
|
| 593 |
+
output_attentions: bool,
|
| 594 |
+
output_hidden_states: bool,
|
| 595 |
+
return_dict: bool,
|
| 596 |
+
training: bool = False,
|
| 597 |
+
) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
|
| 598 |
+
all_hidden_states = () if output_hidden_states else None
|
| 599 |
+
all_attentions = () if output_attentions else None
|
| 600 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
| 601 |
+
|
| 602 |
+
next_decoder_cache = () if use_cache else None
|
| 603 |
+
for i, layer_module in enumerate(self.layer):
|
| 604 |
+
if output_hidden_states:
|
| 605 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 606 |
+
|
| 607 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 608 |
+
|
| 609 |
+
layer_outputs = layer_module(
|
| 610 |
+
hidden_states=hidden_states,
|
| 611 |
+
attention_mask=attention_mask,
|
| 612 |
+
head_mask=head_mask[i],
|
| 613 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 614 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 615 |
+
past_key_value=past_key_value,
|
| 616 |
+
output_attentions=output_attentions,
|
| 617 |
+
training=training,
|
| 618 |
+
)
|
| 619 |
+
hidden_states = layer_outputs[0]
|
| 620 |
+
|
| 621 |
+
if use_cache:
|
| 622 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 623 |
+
|
| 624 |
+
if output_attentions:
|
| 625 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 626 |
+
if self.config.add_cross_attention and encoder_hidden_states is not None:
|
| 627 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 628 |
+
|
| 629 |
+
# Add last layer
|
| 630 |
+
if output_hidden_states:
|
| 631 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 632 |
+
|
| 633 |
+
if not return_dict:
|
| 634 |
+
return tuple(
|
| 635 |
+
v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
return TFBaseModelOutputWithPastAndCrossAttentions(
|
| 639 |
+
last_hidden_state=hidden_states,
|
| 640 |
+
past_key_values=next_decoder_cache,
|
| 641 |
+
hidden_states=all_hidden_states,
|
| 642 |
+
attentions=all_attentions,
|
| 643 |
+
cross_attentions=all_cross_attentions,
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
def build(self, input_shape=None):
|
| 647 |
+
if self.built:
|
| 648 |
+
return
|
| 649 |
+
self.built = True
|
| 650 |
+
if getattr(self, "layer", None) is not None:
|
| 651 |
+
for layer in self.layer:
|
| 652 |
+
with tf.name_scope(layer.name):
|
| 653 |
+
layer.build(None)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
class TFBertPooler(keras.layers.Layer):
|
| 657 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 658 |
+
super().__init__(**kwargs)
|
| 659 |
+
|
| 660 |
+
self.dense = keras.layers.Dense(
|
| 661 |
+
units=config.hidden_size,
|
| 662 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 663 |
+
activation="tanh",
|
| 664 |
+
name="dense",
|
| 665 |
+
)
|
| 666 |
+
self.config = config
|
| 667 |
+
|
| 668 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 669 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 670 |
+
# to the first token.
|
| 671 |
+
first_token_tensor = hidden_states[:, 0]
|
| 672 |
+
pooled_output = self.dense(inputs=first_token_tensor)
|
| 673 |
+
|
| 674 |
+
return pooled_output
|
| 675 |
+
|
| 676 |
+
def build(self, input_shape=None):
|
| 677 |
+
if self.built:
|
| 678 |
+
return
|
| 679 |
+
self.built = True
|
| 680 |
+
if getattr(self, "dense", None) is not None:
|
| 681 |
+
with tf.name_scope(self.dense.name):
|
| 682 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class TFBertPredictionHeadTransform(keras.layers.Layer):
|
| 686 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 687 |
+
super().__init__(**kwargs)
|
| 688 |
+
|
| 689 |
+
self.dense = keras.layers.Dense(
|
| 690 |
+
units=config.hidden_size,
|
| 691 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 692 |
+
name="dense",
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
if isinstance(config.hidden_act, str):
|
| 696 |
+
self.transform_act_fn = get_tf_activation(config.hidden_act)
|
| 697 |
+
else:
|
| 698 |
+
self.transform_act_fn = config.hidden_act
|
| 699 |
+
|
| 700 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 701 |
+
self.config = config
|
| 702 |
+
|
| 703 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 704 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 705 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 706 |
+
hidden_states = self.LayerNorm(inputs=hidden_states)
|
| 707 |
+
|
| 708 |
+
return hidden_states
|
| 709 |
+
|
| 710 |
+
def build(self, input_shape=None):
|
| 711 |
+
if self.built:
|
| 712 |
+
return
|
| 713 |
+
self.built = True
|
| 714 |
+
if getattr(self, "dense", None) is not None:
|
| 715 |
+
with tf.name_scope(self.dense.name):
|
| 716 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 717 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 718 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 719 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
class TFBertLMPredictionHead(keras.layers.Layer):
|
| 723 |
+
def __init__(self, config: BertConfig, input_embeddings: keras.layers.Layer, **kwargs):
|
| 724 |
+
super().__init__(**kwargs)
|
| 725 |
+
|
| 726 |
+
self.config = config
|
| 727 |
+
self.hidden_size = config.hidden_size
|
| 728 |
+
|
| 729 |
+
self.transform = TFBertPredictionHeadTransform(config, name="transform")
|
| 730 |
+
|
| 731 |
+
# The output weights are the same as the input embeddings, but there is
|
| 732 |
+
# an output-only bias for each token.
|
| 733 |
+
self.input_embeddings = input_embeddings
|
| 734 |
+
|
| 735 |
+
def build(self, input_shape=None):
|
| 736 |
+
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
|
| 737 |
+
|
| 738 |
+
if self.built:
|
| 739 |
+
return
|
| 740 |
+
self.built = True
|
| 741 |
+
if getattr(self, "transform", None) is not None:
|
| 742 |
+
with tf.name_scope(self.transform.name):
|
| 743 |
+
self.transform.build(None)
|
| 744 |
+
|
| 745 |
+
def get_output_embeddings(self) -> keras.layers.Layer:
|
| 746 |
+
return self.input_embeddings
|
| 747 |
+
|
| 748 |
+
def set_output_embeddings(self, value: tf.Variable):
|
| 749 |
+
self.input_embeddings.weight = value
|
| 750 |
+
self.input_embeddings.vocab_size = shape_list(value)[0]
|
| 751 |
+
|
| 752 |
+
def get_bias(self) -> Dict[str, tf.Variable]:
|
| 753 |
+
return {"bias": self.bias}
|
| 754 |
+
|
| 755 |
+
def set_bias(self, value: tf.Variable):
|
| 756 |
+
self.bias = value["bias"]
|
| 757 |
+
self.config.vocab_size = shape_list(value["bias"])[0]
|
| 758 |
+
|
| 759 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 760 |
+
hidden_states = self.transform(hidden_states=hidden_states)
|
| 761 |
+
seq_length = shape_list(hidden_states)[1]
|
| 762 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
|
| 763 |
+
hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
|
| 764 |
+
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
|
| 765 |
+
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
|
| 766 |
+
|
| 767 |
+
return hidden_states
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
class TFBertMLMHead(keras.layers.Layer):
|
| 771 |
+
def __init__(self, config: BertConfig, input_embeddings: keras.layers.Layer, **kwargs):
|
| 772 |
+
super().__init__(**kwargs)
|
| 773 |
+
|
| 774 |
+
self.predictions = TFBertLMPredictionHead(config, input_embeddings, name="predictions")
|
| 775 |
+
|
| 776 |
+
def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
|
| 777 |
+
prediction_scores = self.predictions(hidden_states=sequence_output)
|
| 778 |
+
|
| 779 |
+
return prediction_scores
|
| 780 |
+
|
| 781 |
+
def build(self, input_shape=None):
|
| 782 |
+
if self.built:
|
| 783 |
+
return
|
| 784 |
+
self.built = True
|
| 785 |
+
if getattr(self, "predictions", None) is not None:
|
| 786 |
+
with tf.name_scope(self.predictions.name):
|
| 787 |
+
self.predictions.build(None)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
class TFBertNSPHead(keras.layers.Layer):
|
| 791 |
+
def __init__(self, config: BertConfig, **kwargs):
|
| 792 |
+
super().__init__(**kwargs)
|
| 793 |
+
|
| 794 |
+
self.seq_relationship = keras.layers.Dense(
|
| 795 |
+
units=2,
|
| 796 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 797 |
+
name="seq_relationship",
|
| 798 |
+
)
|
| 799 |
+
self.config = config
|
| 800 |
+
|
| 801 |
+
def call(self, pooled_output: tf.Tensor) -> tf.Tensor:
|
| 802 |
+
seq_relationship_score = self.seq_relationship(inputs=pooled_output)
|
| 803 |
+
|
| 804 |
+
return seq_relationship_score
|
| 805 |
+
|
| 806 |
+
def build(self, input_shape=None):
|
| 807 |
+
if self.built:
|
| 808 |
+
return
|
| 809 |
+
self.built = True
|
| 810 |
+
if getattr(self, "seq_relationship", None) is not None:
|
| 811 |
+
with tf.name_scope(self.seq_relationship.name):
|
| 812 |
+
self.seq_relationship.build([None, None, self.config.hidden_size])
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
@keras_serializable
|
| 816 |
+
class TFBertMainLayer(keras.layers.Layer):
|
| 817 |
+
config_class = BertConfig
|
| 818 |
+
|
| 819 |
+
def __init__(self, config: BertConfig, add_pooling_layer: bool = True, **kwargs):
|
| 820 |
+
super().__init__(**kwargs)
|
| 821 |
+
|
| 822 |
+
self.config = config
|
| 823 |
+
self.is_decoder = config.is_decoder
|
| 824 |
+
|
| 825 |
+
self.embeddings = TFBertEmbeddings(config, name="embeddings")
|
| 826 |
+
self.encoder = TFBertEncoder(config, name="encoder")
|
| 827 |
+
self.pooler = TFBertPooler(config, name="pooler") if add_pooling_layer else None
|
| 828 |
+
|
| 829 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
| 830 |
+
return self.embeddings
|
| 831 |
+
|
| 832 |
+
def set_input_embeddings(self, value: tf.Variable):
|
| 833 |
+
self.embeddings.weight = value
|
| 834 |
+
self.embeddings.vocab_size = shape_list(value)[0]
|
| 835 |
+
|
| 836 |
+
def _prune_heads(self, heads_to_prune):
|
| 837 |
+
"""
|
| 838 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 839 |
+
class PreTrainedModel
|
| 840 |
+
"""
|
| 841 |
+
raise NotImplementedError
|
| 842 |
+
|
| 843 |
+
@unpack_inputs
|
| 844 |
+
def call(
|
| 845 |
+
self,
|
| 846 |
+
input_ids: TFModelInputType | None = None,
|
| 847 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 848 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 849 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 850 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 851 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 852 |
+
encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
|
| 853 |
+
encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 854 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 855 |
+
use_cache: Optional[bool] = None,
|
| 856 |
+
output_attentions: Optional[bool] = None,
|
| 857 |
+
output_hidden_states: Optional[bool] = None,
|
| 858 |
+
return_dict: Optional[bool] = None,
|
| 859 |
+
training: bool = False,
|
| 860 |
+
) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:
|
| 861 |
+
if not self.config.is_decoder:
|
| 862 |
+
use_cache = False
|
| 863 |
+
|
| 864 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 865 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 866 |
+
elif input_ids is not None:
|
| 867 |
+
input_shape = shape_list(input_ids)
|
| 868 |
+
elif inputs_embeds is not None:
|
| 869 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 870 |
+
else:
|
| 871 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 872 |
+
|
| 873 |
+
batch_size, seq_length = input_shape
|
| 874 |
+
|
| 875 |
+
if past_key_values is None:
|
| 876 |
+
past_key_values_length = 0
|
| 877 |
+
past_key_values = [None] * len(self.encoder.layer)
|
| 878 |
+
else:
|
| 879 |
+
past_key_values_length = shape_list(past_key_values[0][0])[-2]
|
| 880 |
+
|
| 881 |
+
if attention_mask is None:
|
| 882 |
+
attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
|
| 883 |
+
|
| 884 |
+
if token_type_ids is None:
|
| 885 |
+
token_type_ids = tf.fill(dims=input_shape, value=0)
|
| 886 |
+
|
| 887 |
+
embedding_output = self.embeddings(
|
| 888 |
+
input_ids=input_ids,
|
| 889 |
+
position_ids=position_ids,
|
| 890 |
+
token_type_ids=token_type_ids,
|
| 891 |
+
inputs_embeds=inputs_embeds,
|
| 892 |
+
past_key_values_length=past_key_values_length,
|
| 893 |
+
training=training,
|
| 894 |
+
)
|
| 895 |
+
|
| 896 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 897 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 898 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 899 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 900 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 901 |
+
attention_mask_shape = shape_list(attention_mask)
|
| 902 |
+
|
| 903 |
+
mask_seq_length = seq_length + past_key_values_length
|
| 904 |
+
# Copied from `modeling_tf_t5.py`
|
| 905 |
+
# Provided a padding mask of dimensions [batch_size, mask_seq_length]
|
| 906 |
+
# - if the model is a decoder, apply a causal mask in addition to the padding mask
|
| 907 |
+
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
|
| 908 |
+
if self.is_decoder:
|
| 909 |
+
seq_ids = tf.range(mask_seq_length)
|
| 910 |
+
causal_mask = tf.less_equal(
|
| 911 |
+
tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
|
| 912 |
+
seq_ids[None, :, None],
|
| 913 |
+
)
|
| 914 |
+
causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
|
| 915 |
+
extended_attention_mask = causal_mask * attention_mask[:, None, :]
|
| 916 |
+
attention_mask_shape = shape_list(extended_attention_mask)
|
| 917 |
+
extended_attention_mask = tf.reshape(
|
| 918 |
+
extended_attention_mask, (attention_mask_shape[0], 1, attention_mask_shape[1], attention_mask_shape[2])
|
| 919 |
+
)
|
| 920 |
+
if past_key_values[0] is not None:
|
| 921 |
+
# attention_mask needs to be sliced to the shape `[batch_size, 1, from_seq_length - cached_seq_length, to_seq_length]
|
| 922 |
+
extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
|
| 923 |
+
else:
|
| 924 |
+
extended_attention_mask = tf.reshape(
|
| 925 |
+
attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 929 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 930 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 931 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 932 |
+
# effectively the same as removing these entirely.
|
| 933 |
+
extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
|
| 934 |
+
one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
|
| 935 |
+
ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
|
| 936 |
+
extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
|
| 937 |
+
|
| 938 |
+
# Copied from `modeling_tf_t5.py` with -1e9 -> -10000
|
| 939 |
+
if self.is_decoder and encoder_attention_mask is not None:
|
| 940 |
+
# If a 2D ou 3D attention mask is provided for the cross-attention
|
| 941 |
+
# we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
|
| 942 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 943 |
+
encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
|
| 944 |
+
num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
|
| 945 |
+
if num_dims_encoder_attention_mask == 3:
|
| 946 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
|
| 947 |
+
if num_dims_encoder_attention_mask == 2:
|
| 948 |
+
encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
|
| 949 |
+
|
| 950 |
+
# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
|
| 951 |
+
# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
|
| 952 |
+
# encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
|
| 953 |
+
# tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
|
| 954 |
+
|
| 955 |
+
encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
|
| 956 |
+
else:
|
| 957 |
+
encoder_extended_attention_mask = None
|
| 958 |
+
|
| 959 |
+
# Prepare head mask if needed
|
| 960 |
+
# 1.0 in head_mask indicate we keep the head
|
| 961 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 962 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 963 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 964 |
+
if head_mask is not None:
|
| 965 |
+
raise NotImplementedError
|
| 966 |
+
else:
|
| 967 |
+
head_mask = [None] * self.config.num_hidden_layers
|
| 968 |
+
|
| 969 |
+
encoder_outputs = self.encoder(
|
| 970 |
+
hidden_states=embedding_output,
|
| 971 |
+
attention_mask=extended_attention_mask,
|
| 972 |
+
head_mask=head_mask,
|
| 973 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 974 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 975 |
+
past_key_values=past_key_values,
|
| 976 |
+
use_cache=use_cache,
|
| 977 |
+
output_attentions=output_attentions,
|
| 978 |
+
output_hidden_states=output_hidden_states,
|
| 979 |
+
return_dict=return_dict,
|
| 980 |
+
training=training,
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
sequence_output = encoder_outputs[0]
|
| 984 |
+
pooled_output = self.pooler(hidden_states=sequence_output) if self.pooler is not None else None
|
| 985 |
+
|
| 986 |
+
if not return_dict:
|
| 987 |
+
return (
|
| 988 |
+
sequence_output,
|
| 989 |
+
pooled_output,
|
| 990 |
+
) + encoder_outputs[1:]
|
| 991 |
+
|
| 992 |
+
return TFBaseModelOutputWithPoolingAndCrossAttentions(
|
| 993 |
+
last_hidden_state=sequence_output,
|
| 994 |
+
pooler_output=pooled_output,
|
| 995 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 996 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 997 |
+
attentions=encoder_outputs.attentions,
|
| 998 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 999 |
+
)
|
| 1000 |
+
|
| 1001 |
+
def build(self, input_shape=None):
|
| 1002 |
+
if self.built:
|
| 1003 |
+
return
|
| 1004 |
+
self.built = True
|
| 1005 |
+
if getattr(self, "embeddings", None) is not None:
|
| 1006 |
+
with tf.name_scope(self.embeddings.name):
|
| 1007 |
+
self.embeddings.build(None)
|
| 1008 |
+
if getattr(self, "encoder", None) is not None:
|
| 1009 |
+
with tf.name_scope(self.encoder.name):
|
| 1010 |
+
self.encoder.build(None)
|
| 1011 |
+
if getattr(self, "pooler", None) is not None:
|
| 1012 |
+
with tf.name_scope(self.pooler.name):
|
| 1013 |
+
self.pooler.build(None)
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
class TFBertPreTrainedModel(TFPreTrainedModel):
|
| 1017 |
+
"""
|
| 1018 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 1019 |
+
models.
|
| 1020 |
+
"""
|
| 1021 |
+
|
| 1022 |
+
config_class = BertConfig
|
| 1023 |
+
base_model_prefix = "bert"
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
@dataclass
|
| 1027 |
+
class TFBertForPreTrainingOutput(ModelOutput):
|
| 1028 |
+
"""
|
| 1029 |
+
Output type of [`TFBertForPreTraining`].
|
| 1030 |
+
|
| 1031 |
+
Args:
|
| 1032 |
+
prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 1033 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 1034 |
+
seq_relationship_logits (`tf.Tensor` of shape `(batch_size, 2)`):
|
| 1035 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
| 1036 |
+
before SoftMax).
|
| 1037 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 1038 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
|
| 1039 |
+
`(batch_size, sequence_length, hidden_size)`.
|
| 1040 |
+
|
| 1041 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 1042 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 1043 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 1044 |
+
sequence_length)`.
|
| 1045 |
+
|
| 1046 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 1047 |
+
heads.
|
| 1048 |
+
"""
|
| 1049 |
+
|
| 1050 |
+
loss: tf.Tensor | None = None
|
| 1051 |
+
prediction_logits: tf.Tensor = None
|
| 1052 |
+
seq_relationship_logits: tf.Tensor = None
|
| 1053 |
+
hidden_states: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None
|
| 1054 |
+
attentions: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
BERT_START_DOCSTRING = r"""
|
| 1058 |
+
|
| 1059 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 1060 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 1061 |
+
etc.)
|
| 1062 |
+
|
| 1063 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 1064 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 1065 |
+
behavior.
|
| 1066 |
+
|
| 1067 |
+
<Tip>
|
| 1068 |
+
|
| 1069 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 1070 |
+
|
| 1071 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 1072 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 1073 |
+
|
| 1074 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 1075 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 1076 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 1077 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 1078 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 1079 |
+
positional argument:
|
| 1080 |
+
|
| 1081 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 1082 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 1083 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 1084 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 1085 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 1086 |
+
|
| 1087 |
+
Note that when creating models and layers with
|
| 1088 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 1089 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 1090 |
+
|
| 1091 |
+
</Tip>
|
| 1092 |
+
|
| 1093 |
+
Args:
|
| 1094 |
+
config ([`BertConfig`]): Model configuration class with all the parameters of the model.
|
| 1095 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 1096 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 1097 |
+
"""
|
| 1098 |
+
|
| 1099 |
+
BERT_INPUTS_DOCSTRING = r"""
|
| 1100 |
+
Args:
|
| 1101 |
+
input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
|
| 1102 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1103 |
+
|
| 1104 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 1105 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 1106 |
+
|
| 1107 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1108 |
+
attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 1109 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1110 |
+
|
| 1111 |
+
- 1 for tokens that are **not masked**,
|
| 1112 |
+
- 0 for tokens that are **masked**.
|
| 1113 |
+
|
| 1114 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1115 |
+
token_type_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 1116 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 1117 |
+
1]`:
|
| 1118 |
+
|
| 1119 |
+
- 0 corresponds to a *sentence A* token,
|
| 1120 |
+
- 1 corresponds to a *sentence B* token.
|
| 1121 |
+
|
| 1122 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 1123 |
+
position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
|
| 1124 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 1125 |
+
config.max_position_embeddings - 1]`.
|
| 1126 |
+
|
| 1127 |
+
[What are position IDs?](../glossary#position-ids)
|
| 1128 |
+
head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 1129 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 1130 |
+
|
| 1131 |
+
- 1 indicates the head is **not masked**,
|
| 1132 |
+
- 0 indicates the head is **masked**.
|
| 1133 |
+
|
| 1134 |
+
inputs_embeds (`np.ndarray` or `tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
|
| 1135 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1136 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 1137 |
+
model's internal embedding lookup matrix.
|
| 1138 |
+
output_attentions (`bool`, *optional*):
|
| 1139 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 1140 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 1141 |
+
config will be used instead.
|
| 1142 |
+
output_hidden_states (`bool`, *optional*):
|
| 1143 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 1144 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 1145 |
+
used instead.
|
| 1146 |
+
return_dict (`bool`, *optional*):
|
| 1147 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
|
| 1148 |
+
eager mode, in graph mode the value will always be set to True.
|
| 1149 |
+
training (`bool`, *optional*, defaults to `False``):
|
| 1150 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 1151 |
+
behaviors between training and evaluation).
|
| 1152 |
+
"""
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
@add_start_docstrings(
|
| 1156 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
| 1157 |
+
BERT_START_DOCSTRING,
|
| 1158 |
+
)
|
| 1159 |
+
class TFBertModel(TFBertPreTrainedModel):
|
| 1160 |
+
def __init__(self, config: BertConfig, add_pooling_layer: bool = True, *inputs, **kwargs):
|
| 1161 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1162 |
+
|
| 1163 |
+
self.bert = TFBertMainLayer(config, add_pooling_layer, name="bert")
|
| 1164 |
+
|
| 1165 |
+
@unpack_inputs
|
| 1166 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1167 |
+
@add_code_sample_docstrings(
|
| 1168 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1169 |
+
output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,
|
| 1170 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1171 |
+
)
|
| 1172 |
+
def call(
|
| 1173 |
+
self,
|
| 1174 |
+
input_ids: TFModelInputType | None = None,
|
| 1175 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1176 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1177 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1178 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1179 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1180 |
+
encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
|
| 1181 |
+
encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1182 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 1183 |
+
use_cache: Optional[bool] = None,
|
| 1184 |
+
output_attentions: Optional[bool] = None,
|
| 1185 |
+
output_hidden_states: Optional[bool] = None,
|
| 1186 |
+
return_dict: Optional[bool] = None,
|
| 1187 |
+
training: Optional[bool] = False,
|
| 1188 |
+
) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:
|
| 1189 |
+
r"""
|
| 1190 |
+
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1191 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1192 |
+
the model is configured as a decoder.
|
| 1193 |
+
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1194 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1195 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1196 |
+
|
| 1197 |
+
- 1 for tokens that are **not masked**,
|
| 1198 |
+
- 0 for tokens that are **masked**.
|
| 1199 |
+
|
| 1200 |
+
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
|
| 1201 |
+
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1202 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1203 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1204 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1205 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 1206 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1207 |
+
`past_key_values`). Set to `False` during training, `True` during generation
|
| 1208 |
+
"""
|
| 1209 |
+
outputs = self.bert(
|
| 1210 |
+
input_ids=input_ids,
|
| 1211 |
+
attention_mask=attention_mask,
|
| 1212 |
+
token_type_ids=token_type_ids,
|
| 1213 |
+
position_ids=position_ids,
|
| 1214 |
+
head_mask=head_mask,
|
| 1215 |
+
inputs_embeds=inputs_embeds,
|
| 1216 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1217 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1218 |
+
past_key_values=past_key_values,
|
| 1219 |
+
use_cache=use_cache,
|
| 1220 |
+
output_attentions=output_attentions,
|
| 1221 |
+
output_hidden_states=output_hidden_states,
|
| 1222 |
+
return_dict=return_dict,
|
| 1223 |
+
training=training,
|
| 1224 |
+
)
|
| 1225 |
+
return outputs
|
| 1226 |
+
|
| 1227 |
+
def build(self, input_shape=None):
|
| 1228 |
+
if self.built:
|
| 1229 |
+
return
|
| 1230 |
+
self.built = True
|
| 1231 |
+
if getattr(self, "bert", None) is not None:
|
| 1232 |
+
with tf.name_scope(self.bert.name):
|
| 1233 |
+
self.bert.build(None)
|
| 1234 |
+
|
| 1235 |
+
|
| 1236 |
+
@add_start_docstrings(
|
| 1237 |
+
"""
|
| 1238 |
+
Bert Model with two heads on top as done during the pretraining:
|
| 1239 |
+
a `masked language modeling` head and a `next sentence prediction (classification)` head.
|
| 1240 |
+
""",
|
| 1241 |
+
BERT_START_DOCSTRING,
|
| 1242 |
+
)
|
| 1243 |
+
class TFBertForPreTraining(TFBertPreTrainedModel, TFBertPreTrainingLoss):
|
| 1244 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1245 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 1246 |
+
r"position_ids",
|
| 1247 |
+
r"cls.predictions.decoder.weight",
|
| 1248 |
+
r"cls.predictions.decoder.bias",
|
| 1249 |
+
]
|
| 1250 |
+
|
| 1251 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 1252 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1253 |
+
|
| 1254 |
+
self.bert = TFBertMainLayer(config, name="bert")
|
| 1255 |
+
self.nsp = TFBertNSPHead(config, name="nsp___cls")
|
| 1256 |
+
self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
|
| 1257 |
+
|
| 1258 |
+
def get_lm_head(self) -> keras.layers.Layer:
|
| 1259 |
+
return self.mlm.predictions
|
| 1260 |
+
|
| 1261 |
+
def get_prefix_bias_name(self) -> str:
|
| 1262 |
+
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
|
| 1263 |
+
return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
|
| 1264 |
+
|
| 1265 |
+
@unpack_inputs
|
| 1266 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1267 |
+
@replace_return_docstrings(output_type=TFBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 1268 |
+
def call(
|
| 1269 |
+
self,
|
| 1270 |
+
input_ids: TFModelInputType | None = None,
|
| 1271 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1272 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1273 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1274 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1275 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1276 |
+
output_attentions: Optional[bool] = None,
|
| 1277 |
+
output_hidden_states: Optional[bool] = None,
|
| 1278 |
+
return_dict: Optional[bool] = None,
|
| 1279 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1280 |
+
next_sentence_label: np.ndarray | tf.Tensor | None = None,
|
| 1281 |
+
training: Optional[bool] = False,
|
| 1282 |
+
) -> Union[TFBertForPreTrainingOutput, Tuple[tf.Tensor]]:
|
| 1283 |
+
r"""
|
| 1284 |
+
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1285 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1286 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1287 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1288 |
+
next_sentence_label (`tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1289 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
| 1290 |
+
(see `input_ids` docstring) Indices should be in `[0, 1]`:
|
| 1291 |
+
|
| 1292 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
| 1293 |
+
- 1 indicates sequence B is a random sequence.
|
| 1294 |
+
kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
|
| 1295 |
+
Used to hide legacy arguments that have been deprecated.
|
| 1296 |
+
|
| 1297 |
+
Return:
|
| 1298 |
+
|
| 1299 |
+
Examples:
|
| 1300 |
+
|
| 1301 |
+
```python
|
| 1302 |
+
>>> import tensorflow as tf
|
| 1303 |
+
>>> from transformers import AutoTokenizer, TFBertForPreTraining
|
| 1304 |
+
|
| 1305 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 1306 |
+
>>> model = TFBertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
|
| 1307 |
+
>>> input_ids = tokenizer("Hello, my dog is cute", add_special_tokens=True, return_tensors="tf")
|
| 1308 |
+
>>> # Batch size 1
|
| 1309 |
+
|
| 1310 |
+
>>> outputs = model(input_ids)
|
| 1311 |
+
>>> prediction_logits, seq_relationship_logits = outputs[:2]
|
| 1312 |
+
```"""
|
| 1313 |
+
outputs = self.bert(
|
| 1314 |
+
input_ids=input_ids,
|
| 1315 |
+
attention_mask=attention_mask,
|
| 1316 |
+
token_type_ids=token_type_ids,
|
| 1317 |
+
position_ids=position_ids,
|
| 1318 |
+
head_mask=head_mask,
|
| 1319 |
+
inputs_embeds=inputs_embeds,
|
| 1320 |
+
output_attentions=output_attentions,
|
| 1321 |
+
output_hidden_states=output_hidden_states,
|
| 1322 |
+
return_dict=return_dict,
|
| 1323 |
+
training=training,
|
| 1324 |
+
)
|
| 1325 |
+
sequence_output, pooled_output = outputs[:2]
|
| 1326 |
+
prediction_scores = self.mlm(sequence_output=sequence_output, training=training)
|
| 1327 |
+
seq_relationship_score = self.nsp(pooled_output=pooled_output)
|
| 1328 |
+
total_loss = None
|
| 1329 |
+
|
| 1330 |
+
if labels is not None and next_sentence_label is not None:
|
| 1331 |
+
d_labels = {"labels": labels}
|
| 1332 |
+
d_labels["next_sentence_label"] = next_sentence_label
|
| 1333 |
+
total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, seq_relationship_score))
|
| 1334 |
+
|
| 1335 |
+
if not return_dict:
|
| 1336 |
+
output = (prediction_scores, seq_relationship_score) + outputs[2:]
|
| 1337 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1338 |
+
|
| 1339 |
+
return TFBertForPreTrainingOutput(
|
| 1340 |
+
loss=total_loss,
|
| 1341 |
+
prediction_logits=prediction_scores,
|
| 1342 |
+
seq_relationship_logits=seq_relationship_score,
|
| 1343 |
+
hidden_states=outputs.hidden_states,
|
| 1344 |
+
attentions=outputs.attentions,
|
| 1345 |
+
)
|
| 1346 |
+
|
| 1347 |
+
def build(self, input_shape=None):
|
| 1348 |
+
if self.built:
|
| 1349 |
+
return
|
| 1350 |
+
self.built = True
|
| 1351 |
+
if getattr(self, "bert", None) is not None:
|
| 1352 |
+
with tf.name_scope(self.bert.name):
|
| 1353 |
+
self.bert.build(None)
|
| 1354 |
+
if getattr(self, "nsp", None) is not None:
|
| 1355 |
+
with tf.name_scope(self.nsp.name):
|
| 1356 |
+
self.nsp.build(None)
|
| 1357 |
+
if getattr(self, "mlm", None) is not None:
|
| 1358 |
+
with tf.name_scope(self.mlm.name):
|
| 1359 |
+
self.mlm.build(None)
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
@add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
|
| 1363 |
+
class TFBertForMaskedLM(TFBertPreTrainedModel, TFMaskedLanguageModelingLoss):
|
| 1364 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1365 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 1366 |
+
r"pooler",
|
| 1367 |
+
r"cls.seq_relationship",
|
| 1368 |
+
r"cls.predictions.decoder.weight",
|
| 1369 |
+
r"nsp___cls",
|
| 1370 |
+
]
|
| 1371 |
+
|
| 1372 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 1373 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1374 |
+
|
| 1375 |
+
if config.is_decoder:
|
| 1376 |
+
logger.warning(
|
| 1377 |
+
"If you want to use `TFBertForMaskedLM` make sure `config.is_decoder=False` for "
|
| 1378 |
+
"bi-directional self-attention."
|
| 1379 |
+
)
|
| 1380 |
+
|
| 1381 |
+
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
|
| 1382 |
+
self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
|
| 1383 |
+
|
| 1384 |
+
def get_lm_head(self) -> keras.layers.Layer:
|
| 1385 |
+
return self.mlm.predictions
|
| 1386 |
+
|
| 1387 |
+
def get_prefix_bias_name(self) -> str:
|
| 1388 |
+
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
|
| 1389 |
+
return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
|
| 1390 |
+
|
| 1391 |
+
@unpack_inputs
|
| 1392 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1393 |
+
@add_code_sample_docstrings(
|
| 1394 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1395 |
+
output_type=TFMaskedLMOutput,
|
| 1396 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1397 |
+
expected_output="'paris'",
|
| 1398 |
+
expected_loss=0.88,
|
| 1399 |
+
)
|
| 1400 |
+
def call(
|
| 1401 |
+
self,
|
| 1402 |
+
input_ids: TFModelInputType | None = None,
|
| 1403 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1404 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1405 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1406 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1407 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1408 |
+
output_attentions: Optional[bool] = None,
|
| 1409 |
+
output_hidden_states: Optional[bool] = None,
|
| 1410 |
+
return_dict: Optional[bool] = None,
|
| 1411 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1412 |
+
training: Optional[bool] = False,
|
| 1413 |
+
) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
|
| 1414 |
+
r"""
|
| 1415 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1416 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
| 1417 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
| 1418 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
| 1419 |
+
"""
|
| 1420 |
+
outputs = self.bert(
|
| 1421 |
+
input_ids=input_ids,
|
| 1422 |
+
attention_mask=attention_mask,
|
| 1423 |
+
token_type_ids=token_type_ids,
|
| 1424 |
+
position_ids=position_ids,
|
| 1425 |
+
head_mask=head_mask,
|
| 1426 |
+
inputs_embeds=inputs_embeds,
|
| 1427 |
+
output_attentions=output_attentions,
|
| 1428 |
+
output_hidden_states=output_hidden_states,
|
| 1429 |
+
return_dict=return_dict,
|
| 1430 |
+
training=training,
|
| 1431 |
+
)
|
| 1432 |
+
sequence_output = outputs[0]
|
| 1433 |
+
prediction_scores = self.mlm(sequence_output=sequence_output, training=training)
|
| 1434 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores)
|
| 1435 |
+
|
| 1436 |
+
if not return_dict:
|
| 1437 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1438 |
+
return ((loss,) + output) if loss is not None else output
|
| 1439 |
+
|
| 1440 |
+
return TFMaskedLMOutput(
|
| 1441 |
+
loss=loss,
|
| 1442 |
+
logits=prediction_scores,
|
| 1443 |
+
hidden_states=outputs.hidden_states,
|
| 1444 |
+
attentions=outputs.attentions,
|
| 1445 |
+
)
|
| 1446 |
+
|
| 1447 |
+
def build(self, input_shape=None):
|
| 1448 |
+
if self.built:
|
| 1449 |
+
return
|
| 1450 |
+
self.built = True
|
| 1451 |
+
if getattr(self, "bert", None) is not None:
|
| 1452 |
+
with tf.name_scope(self.bert.name):
|
| 1453 |
+
self.bert.build(None)
|
| 1454 |
+
if getattr(self, "mlm", None) is not None:
|
| 1455 |
+
with tf.name_scope(self.mlm.name):
|
| 1456 |
+
self.mlm.build(None)
|
| 1457 |
+
|
| 1458 |
+
|
| 1459 |
+
class TFBertLMHeadModel(TFBertPreTrainedModel, TFCausalLanguageModelingLoss):
|
| 1460 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1461 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 1462 |
+
r"pooler",
|
| 1463 |
+
r"cls.seq_relationship",
|
| 1464 |
+
r"cls.predictions.decoder.weight",
|
| 1465 |
+
r"nsp___cls",
|
| 1466 |
+
]
|
| 1467 |
+
|
| 1468 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 1469 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1470 |
+
|
| 1471 |
+
if not config.is_decoder:
|
| 1472 |
+
logger.warning("If you want to use `TFBertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
| 1473 |
+
|
| 1474 |
+
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
|
| 1475 |
+
self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
|
| 1476 |
+
|
| 1477 |
+
def get_lm_head(self) -> keras.layers.Layer:
|
| 1478 |
+
return self.mlm.predictions
|
| 1479 |
+
|
| 1480 |
+
def get_prefix_bias_name(self) -> str:
|
| 1481 |
+
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
|
| 1482 |
+
return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
|
| 1483 |
+
|
| 1484 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
| 1485 |
+
input_shape = input_ids.shape
|
| 1486 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 1487 |
+
if attention_mask is None:
|
| 1488 |
+
attention_mask = tf.ones(input_shape)
|
| 1489 |
+
|
| 1490 |
+
# cut decoder_input_ids if past is used
|
| 1491 |
+
if past_key_values is not None:
|
| 1492 |
+
input_ids = input_ids[:, -1:]
|
| 1493 |
+
|
| 1494 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
|
| 1495 |
+
|
| 1496 |
+
@unpack_inputs
|
| 1497 |
+
@add_code_sample_docstrings(
|
| 1498 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1499 |
+
output_type=TFCausalLMOutputWithCrossAttentions,
|
| 1500 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1501 |
+
)
|
| 1502 |
+
def call(
|
| 1503 |
+
self,
|
| 1504 |
+
input_ids: TFModelInputType | None = None,
|
| 1505 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1506 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1507 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1508 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1509 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1510 |
+
encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
|
| 1511 |
+
encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1512 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 1513 |
+
use_cache: Optional[bool] = None,
|
| 1514 |
+
output_attentions: Optional[bool] = None,
|
| 1515 |
+
output_hidden_states: Optional[bool] = None,
|
| 1516 |
+
return_dict: Optional[bool] = None,
|
| 1517 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1518 |
+
training: Optional[bool] = False,
|
| 1519 |
+
**kwargs,
|
| 1520 |
+
) -> Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]:
|
| 1521 |
+
r"""
|
| 1522 |
+
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1523 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 1524 |
+
the model is configured as a decoder.
|
| 1525 |
+
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1526 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1527 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1528 |
+
|
| 1529 |
+
- 1 for tokens that are **not masked**,
|
| 1530 |
+
- 0 for tokens that are **masked**.
|
| 1531 |
+
|
| 1532 |
+
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
|
| 1533 |
+
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1534 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1535 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1536 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1537 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 1538 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1539 |
+
`past_key_values`). Set to `False` during training, `True` during generation
|
| 1540 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1541 |
+
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
|
| 1542 |
+
config.vocab_size - 1]`.
|
| 1543 |
+
"""
|
| 1544 |
+
outputs = self.bert(
|
| 1545 |
+
input_ids=input_ids,
|
| 1546 |
+
attention_mask=attention_mask,
|
| 1547 |
+
token_type_ids=token_type_ids,
|
| 1548 |
+
position_ids=position_ids,
|
| 1549 |
+
head_mask=head_mask,
|
| 1550 |
+
inputs_embeds=inputs_embeds,
|
| 1551 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1552 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1553 |
+
past_key_values=past_key_values,
|
| 1554 |
+
use_cache=use_cache,
|
| 1555 |
+
output_attentions=output_attentions,
|
| 1556 |
+
output_hidden_states=output_hidden_states,
|
| 1557 |
+
return_dict=return_dict,
|
| 1558 |
+
training=training,
|
| 1559 |
+
)
|
| 1560 |
+
sequence_output = outputs[0]
|
| 1561 |
+
logits = self.mlm(sequence_output=sequence_output, training=training)
|
| 1562 |
+
loss = None
|
| 1563 |
+
|
| 1564 |
+
if labels is not None:
|
| 1565 |
+
# shift labels to the left and cut last logit token
|
| 1566 |
+
shifted_logits = logits[:, :-1]
|
| 1567 |
+
labels = labels[:, 1:]
|
| 1568 |
+
loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)
|
| 1569 |
+
|
| 1570 |
+
if not return_dict:
|
| 1571 |
+
output = (logits,) + outputs[2:]
|
| 1572 |
+
return ((loss,) + output) if loss is not None else output
|
| 1573 |
+
|
| 1574 |
+
return TFCausalLMOutputWithCrossAttentions(
|
| 1575 |
+
loss=loss,
|
| 1576 |
+
logits=logits,
|
| 1577 |
+
past_key_values=outputs.past_key_values,
|
| 1578 |
+
hidden_states=outputs.hidden_states,
|
| 1579 |
+
attentions=outputs.attentions,
|
| 1580 |
+
cross_attentions=outputs.cross_attentions,
|
| 1581 |
+
)
|
| 1582 |
+
|
| 1583 |
+
def build(self, input_shape=None):
|
| 1584 |
+
if self.built:
|
| 1585 |
+
return
|
| 1586 |
+
self.built = True
|
| 1587 |
+
if getattr(self, "bert", None) is not None:
|
| 1588 |
+
with tf.name_scope(self.bert.name):
|
| 1589 |
+
self.bert.build(None)
|
| 1590 |
+
if getattr(self, "mlm", None) is not None:
|
| 1591 |
+
with tf.name_scope(self.mlm.name):
|
| 1592 |
+
self.mlm.build(None)
|
| 1593 |
+
|
| 1594 |
+
|
| 1595 |
+
@add_start_docstrings(
|
| 1596 |
+
"""Bert Model with a `next sentence prediction (classification)` head on top.""",
|
| 1597 |
+
BERT_START_DOCSTRING,
|
| 1598 |
+
)
|
| 1599 |
+
class TFBertForNextSentencePrediction(TFBertPreTrainedModel, TFNextSentencePredictionLoss):
|
| 1600 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1601 |
+
_keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"cls.predictions"]
|
| 1602 |
+
|
| 1603 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 1604 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1605 |
+
|
| 1606 |
+
self.bert = TFBertMainLayer(config, name="bert")
|
| 1607 |
+
self.nsp = TFBertNSPHead(config, name="nsp___cls")
|
| 1608 |
+
|
| 1609 |
+
@unpack_inputs
|
| 1610 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1611 |
+
@replace_return_docstrings(output_type=TFNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
|
| 1612 |
+
def call(
|
| 1613 |
+
self,
|
| 1614 |
+
input_ids: TFModelInputType | None = None,
|
| 1615 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1616 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1617 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1618 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1619 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1620 |
+
output_attentions: Optional[bool] = None,
|
| 1621 |
+
output_hidden_states: Optional[bool] = None,
|
| 1622 |
+
return_dict: Optional[bool] = None,
|
| 1623 |
+
next_sentence_label: np.ndarray | tf.Tensor | None = None,
|
| 1624 |
+
training: Optional[bool] = False,
|
| 1625 |
+
) -> Union[TFNextSentencePredictorOutput, Tuple[tf.Tensor]]:
|
| 1626 |
+
r"""
|
| 1627 |
+
Return:
|
| 1628 |
+
|
| 1629 |
+
Examples:
|
| 1630 |
+
|
| 1631 |
+
```python
|
| 1632 |
+
>>> import tensorflow as tf
|
| 1633 |
+
>>> from transformers import AutoTokenizer, TFBertForNextSentencePrediction
|
| 1634 |
+
|
| 1635 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 1636 |
+
>>> model = TFBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
|
| 1637 |
+
|
| 1638 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
| 1639 |
+
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
|
| 1640 |
+
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="tf")
|
| 1641 |
+
|
| 1642 |
+
>>> logits = model(encoding["input_ids"], token_type_ids=encoding["token_type_ids"])[0]
|
| 1643 |
+
>>> assert logits[0][0] < logits[0][1] # the next sentence was random
|
| 1644 |
+
```"""
|
| 1645 |
+
outputs = self.bert(
|
| 1646 |
+
input_ids=input_ids,
|
| 1647 |
+
attention_mask=attention_mask,
|
| 1648 |
+
token_type_ids=token_type_ids,
|
| 1649 |
+
position_ids=position_ids,
|
| 1650 |
+
head_mask=head_mask,
|
| 1651 |
+
inputs_embeds=inputs_embeds,
|
| 1652 |
+
output_attentions=output_attentions,
|
| 1653 |
+
output_hidden_states=output_hidden_states,
|
| 1654 |
+
return_dict=return_dict,
|
| 1655 |
+
training=training,
|
| 1656 |
+
)
|
| 1657 |
+
pooled_output = outputs[1]
|
| 1658 |
+
seq_relationship_scores = self.nsp(pooled_output=pooled_output)
|
| 1659 |
+
next_sentence_loss = (
|
| 1660 |
+
None
|
| 1661 |
+
if next_sentence_label is None
|
| 1662 |
+
else self.hf_compute_loss(labels=next_sentence_label, logits=seq_relationship_scores)
|
| 1663 |
+
)
|
| 1664 |
+
|
| 1665 |
+
if not return_dict:
|
| 1666 |
+
output = (seq_relationship_scores,) + outputs[2:]
|
| 1667 |
+
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
|
| 1668 |
+
|
| 1669 |
+
return TFNextSentencePredictorOutput(
|
| 1670 |
+
loss=next_sentence_loss,
|
| 1671 |
+
logits=seq_relationship_scores,
|
| 1672 |
+
hidden_states=outputs.hidden_states,
|
| 1673 |
+
attentions=outputs.attentions,
|
| 1674 |
+
)
|
| 1675 |
+
|
| 1676 |
+
def build(self, input_shape=None):
|
| 1677 |
+
if self.built:
|
| 1678 |
+
return
|
| 1679 |
+
self.built = True
|
| 1680 |
+
if getattr(self, "bert", None) is not None:
|
| 1681 |
+
with tf.name_scope(self.bert.name):
|
| 1682 |
+
self.bert.build(None)
|
| 1683 |
+
if getattr(self, "nsp", None) is not None:
|
| 1684 |
+
with tf.name_scope(self.nsp.name):
|
| 1685 |
+
self.nsp.build(None)
|
| 1686 |
+
|
| 1687 |
+
|
| 1688 |
+
@add_start_docstrings(
|
| 1689 |
+
"""
|
| 1690 |
+
Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
| 1691 |
+
output) e.g. for GLUE tasks.
|
| 1692 |
+
""",
|
| 1693 |
+
BERT_START_DOCSTRING,
|
| 1694 |
+
)
|
| 1695 |
+
class TFBertForSequenceClassification(TFBertPreTrainedModel, TFSequenceClassificationLoss):
|
| 1696 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1697 |
+
_keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"nsp___cls", r"cls.predictions", r"cls.seq_relationship"]
|
| 1698 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1699 |
+
|
| 1700 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 1701 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1702 |
+
|
| 1703 |
+
self.num_labels = config.num_labels
|
| 1704 |
+
|
| 1705 |
+
self.bert = TFBertMainLayer(config, name="bert")
|
| 1706 |
+
classifier_dropout = (
|
| 1707 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1708 |
+
)
|
| 1709 |
+
self.dropout = keras.layers.Dropout(rate=classifier_dropout)
|
| 1710 |
+
self.classifier = keras.layers.Dense(
|
| 1711 |
+
units=config.num_labels,
|
| 1712 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1713 |
+
name="classifier",
|
| 1714 |
+
)
|
| 1715 |
+
self.config = config
|
| 1716 |
+
|
| 1717 |
+
@unpack_inputs
|
| 1718 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1719 |
+
@add_code_sample_docstrings(
|
| 1720 |
+
checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
|
| 1721 |
+
output_type=TFSequenceClassifierOutput,
|
| 1722 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1723 |
+
expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
|
| 1724 |
+
expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
|
| 1725 |
+
)
|
| 1726 |
+
def call(
|
| 1727 |
+
self,
|
| 1728 |
+
input_ids: TFModelInputType | None = None,
|
| 1729 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1730 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1731 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1732 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1733 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1734 |
+
output_attentions: Optional[bool] = None,
|
| 1735 |
+
output_hidden_states: Optional[bool] = None,
|
| 1736 |
+
return_dict: Optional[bool] = None,
|
| 1737 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1738 |
+
training: Optional[bool] = False,
|
| 1739 |
+
) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
|
| 1740 |
+
r"""
|
| 1741 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 1742 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1743 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1744 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1745 |
+
"""
|
| 1746 |
+
outputs = self.bert(
|
| 1747 |
+
input_ids=input_ids,
|
| 1748 |
+
attention_mask=attention_mask,
|
| 1749 |
+
token_type_ids=token_type_ids,
|
| 1750 |
+
position_ids=position_ids,
|
| 1751 |
+
head_mask=head_mask,
|
| 1752 |
+
inputs_embeds=inputs_embeds,
|
| 1753 |
+
output_attentions=output_attentions,
|
| 1754 |
+
output_hidden_states=output_hidden_states,
|
| 1755 |
+
return_dict=return_dict,
|
| 1756 |
+
training=training,
|
| 1757 |
+
)
|
| 1758 |
+
pooled_output = outputs[1]
|
| 1759 |
+
pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 1760 |
+
logits = self.classifier(inputs=pooled_output)
|
| 1761 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1762 |
+
|
| 1763 |
+
if not return_dict:
|
| 1764 |
+
output = (logits,) + outputs[2:]
|
| 1765 |
+
return ((loss,) + output) if loss is not None else output
|
| 1766 |
+
|
| 1767 |
+
return TFSequenceClassifierOutput(
|
| 1768 |
+
loss=loss,
|
| 1769 |
+
logits=logits,
|
| 1770 |
+
hidden_states=outputs.hidden_states,
|
| 1771 |
+
attentions=outputs.attentions,
|
| 1772 |
+
)
|
| 1773 |
+
|
| 1774 |
+
def build(self, input_shape=None):
|
| 1775 |
+
if self.built:
|
| 1776 |
+
return
|
| 1777 |
+
self.built = True
|
| 1778 |
+
if getattr(self, "bert", None) is not None:
|
| 1779 |
+
with tf.name_scope(self.bert.name):
|
| 1780 |
+
self.bert.build(None)
|
| 1781 |
+
if getattr(self, "classifier", None) is not None:
|
| 1782 |
+
with tf.name_scope(self.classifier.name):
|
| 1783 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1784 |
+
|
| 1785 |
+
|
| 1786 |
+
@add_start_docstrings(
|
| 1787 |
+
"""
|
| 1788 |
+
Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
| 1789 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
| 1790 |
+
""",
|
| 1791 |
+
BERT_START_DOCSTRING,
|
| 1792 |
+
)
|
| 1793 |
+
class TFBertForMultipleChoice(TFBertPreTrainedModel, TFMultipleChoiceLoss):
|
| 1794 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1795 |
+
_keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"nsp___cls", r"cls.predictions", r"cls.seq_relationship"]
|
| 1796 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1797 |
+
|
| 1798 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 1799 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1800 |
+
|
| 1801 |
+
self.bert = TFBertMainLayer(config, name="bert")
|
| 1802 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 1803 |
+
self.classifier = keras.layers.Dense(
|
| 1804 |
+
units=1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
|
| 1805 |
+
)
|
| 1806 |
+
self.config = config
|
| 1807 |
+
|
| 1808 |
+
@unpack_inputs
|
| 1809 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
|
| 1810 |
+
@add_code_sample_docstrings(
|
| 1811 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1812 |
+
output_type=TFMultipleChoiceModelOutput,
|
| 1813 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1814 |
+
)
|
| 1815 |
+
def call(
|
| 1816 |
+
self,
|
| 1817 |
+
input_ids: TFModelInputType | None = None,
|
| 1818 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1819 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1820 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1821 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1822 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1823 |
+
output_attentions: Optional[bool] = None,
|
| 1824 |
+
output_hidden_states: Optional[bool] = None,
|
| 1825 |
+
return_dict: Optional[bool] = None,
|
| 1826 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1827 |
+
training: Optional[bool] = False,
|
| 1828 |
+
) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
|
| 1829 |
+
r"""
|
| 1830 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 1831 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
|
| 1832 |
+
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
|
| 1833 |
+
"""
|
| 1834 |
+
if input_ids is not None:
|
| 1835 |
+
num_choices = shape_list(input_ids)[1]
|
| 1836 |
+
seq_length = shape_list(input_ids)[2]
|
| 1837 |
+
else:
|
| 1838 |
+
num_choices = shape_list(inputs_embeds)[1]
|
| 1839 |
+
seq_length = shape_list(inputs_embeds)[2]
|
| 1840 |
+
|
| 1841 |
+
flat_input_ids = tf.reshape(tensor=input_ids, shape=(-1, seq_length)) if input_ids is not None else None
|
| 1842 |
+
flat_attention_mask = (
|
| 1843 |
+
tf.reshape(tensor=attention_mask, shape=(-1, seq_length)) if attention_mask is not None else None
|
| 1844 |
+
)
|
| 1845 |
+
flat_token_type_ids = (
|
| 1846 |
+
tf.reshape(tensor=token_type_ids, shape=(-1, seq_length)) if token_type_ids is not None else None
|
| 1847 |
+
)
|
| 1848 |
+
flat_position_ids = (
|
| 1849 |
+
tf.reshape(tensor=position_ids, shape=(-1, seq_length)) if position_ids is not None else None
|
| 1850 |
+
)
|
| 1851 |
+
flat_inputs_embeds = (
|
| 1852 |
+
tf.reshape(tensor=inputs_embeds, shape=(-1, seq_length, shape_list(inputs_embeds)[3]))
|
| 1853 |
+
if inputs_embeds is not None
|
| 1854 |
+
else None
|
| 1855 |
+
)
|
| 1856 |
+
outputs = self.bert(
|
| 1857 |
+
input_ids=flat_input_ids,
|
| 1858 |
+
attention_mask=flat_attention_mask,
|
| 1859 |
+
token_type_ids=flat_token_type_ids,
|
| 1860 |
+
position_ids=flat_position_ids,
|
| 1861 |
+
head_mask=head_mask,
|
| 1862 |
+
inputs_embeds=flat_inputs_embeds,
|
| 1863 |
+
output_attentions=output_attentions,
|
| 1864 |
+
output_hidden_states=output_hidden_states,
|
| 1865 |
+
return_dict=return_dict,
|
| 1866 |
+
training=training,
|
| 1867 |
+
)
|
| 1868 |
+
pooled_output = outputs[1]
|
| 1869 |
+
pooled_output = self.dropout(inputs=pooled_output, training=training)
|
| 1870 |
+
logits = self.classifier(inputs=pooled_output)
|
| 1871 |
+
reshaped_logits = tf.reshape(tensor=logits, shape=(-1, num_choices))
|
| 1872 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=reshaped_logits)
|
| 1873 |
+
|
| 1874 |
+
if not return_dict:
|
| 1875 |
+
output = (reshaped_logits,) + outputs[2:]
|
| 1876 |
+
return ((loss,) + output) if loss is not None else output
|
| 1877 |
+
|
| 1878 |
+
return TFMultipleChoiceModelOutput(
|
| 1879 |
+
loss=loss,
|
| 1880 |
+
logits=reshaped_logits,
|
| 1881 |
+
hidden_states=outputs.hidden_states,
|
| 1882 |
+
attentions=outputs.attentions,
|
| 1883 |
+
)
|
| 1884 |
+
|
| 1885 |
+
def build(self, input_shape=None):
|
| 1886 |
+
if self.built:
|
| 1887 |
+
return
|
| 1888 |
+
self.built = True
|
| 1889 |
+
if getattr(self, "bert", None) is not None:
|
| 1890 |
+
with tf.name_scope(self.bert.name):
|
| 1891 |
+
self.bert.build(None)
|
| 1892 |
+
if getattr(self, "classifier", None) is not None:
|
| 1893 |
+
with tf.name_scope(self.classifier.name):
|
| 1894 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1895 |
+
|
| 1896 |
+
|
| 1897 |
+
@add_start_docstrings(
|
| 1898 |
+
"""
|
| 1899 |
+
Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
| 1900 |
+
Named-Entity-Recognition (NER) tasks.
|
| 1901 |
+
""",
|
| 1902 |
+
BERT_START_DOCSTRING,
|
| 1903 |
+
)
|
| 1904 |
+
class TFBertForTokenClassification(TFBertPreTrainedModel, TFTokenClassificationLoss):
|
| 1905 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 1906 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 1907 |
+
r"pooler",
|
| 1908 |
+
r"mlm___cls",
|
| 1909 |
+
r"nsp___cls",
|
| 1910 |
+
r"cls.predictions",
|
| 1911 |
+
r"cls.seq_relationship",
|
| 1912 |
+
]
|
| 1913 |
+
_keys_to_ignore_on_load_missing = [r"dropout"]
|
| 1914 |
+
|
| 1915 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 1916 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1917 |
+
|
| 1918 |
+
self.num_labels = config.num_labels
|
| 1919 |
+
|
| 1920 |
+
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
|
| 1921 |
+
classifier_dropout = (
|
| 1922 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1923 |
+
)
|
| 1924 |
+
self.dropout = keras.layers.Dropout(rate=classifier_dropout)
|
| 1925 |
+
self.classifier = keras.layers.Dense(
|
| 1926 |
+
units=config.num_labels,
|
| 1927 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1928 |
+
name="classifier",
|
| 1929 |
+
)
|
| 1930 |
+
self.config = config
|
| 1931 |
+
|
| 1932 |
+
@unpack_inputs
|
| 1933 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1934 |
+
@add_code_sample_docstrings(
|
| 1935 |
+
checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
|
| 1936 |
+
output_type=TFTokenClassifierOutput,
|
| 1937 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1938 |
+
expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
|
| 1939 |
+
expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
|
| 1940 |
+
)
|
| 1941 |
+
def call(
|
| 1942 |
+
self,
|
| 1943 |
+
input_ids: TFModelInputType | None = None,
|
| 1944 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1945 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1946 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1947 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1948 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1949 |
+
output_attentions: Optional[bool] = None,
|
| 1950 |
+
output_hidden_states: Optional[bool] = None,
|
| 1951 |
+
return_dict: Optional[bool] = None,
|
| 1952 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 1953 |
+
training: Optional[bool] = False,
|
| 1954 |
+
) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
|
| 1955 |
+
r"""
|
| 1956 |
+
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1957 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
| 1958 |
+
"""
|
| 1959 |
+
outputs = self.bert(
|
| 1960 |
+
input_ids=input_ids,
|
| 1961 |
+
attention_mask=attention_mask,
|
| 1962 |
+
token_type_ids=token_type_ids,
|
| 1963 |
+
position_ids=position_ids,
|
| 1964 |
+
head_mask=head_mask,
|
| 1965 |
+
inputs_embeds=inputs_embeds,
|
| 1966 |
+
output_attentions=output_attentions,
|
| 1967 |
+
output_hidden_states=output_hidden_states,
|
| 1968 |
+
return_dict=return_dict,
|
| 1969 |
+
training=training,
|
| 1970 |
+
)
|
| 1971 |
+
sequence_output = outputs[0]
|
| 1972 |
+
sequence_output = self.dropout(inputs=sequence_output, training=training)
|
| 1973 |
+
logits = self.classifier(inputs=sequence_output)
|
| 1974 |
+
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
|
| 1975 |
+
|
| 1976 |
+
if not return_dict:
|
| 1977 |
+
output = (logits,) + outputs[2:]
|
| 1978 |
+
return ((loss,) + output) if loss is not None else output
|
| 1979 |
+
|
| 1980 |
+
return TFTokenClassifierOutput(
|
| 1981 |
+
loss=loss,
|
| 1982 |
+
logits=logits,
|
| 1983 |
+
hidden_states=outputs.hidden_states,
|
| 1984 |
+
attentions=outputs.attentions,
|
| 1985 |
+
)
|
| 1986 |
+
|
| 1987 |
+
def build(self, input_shape=None):
|
| 1988 |
+
if self.built:
|
| 1989 |
+
return
|
| 1990 |
+
self.built = True
|
| 1991 |
+
if getattr(self, "bert", None) is not None:
|
| 1992 |
+
with tf.name_scope(self.bert.name):
|
| 1993 |
+
self.bert.build(None)
|
| 1994 |
+
if getattr(self, "classifier", None) is not None:
|
| 1995 |
+
with tf.name_scope(self.classifier.name):
|
| 1996 |
+
self.classifier.build([None, None, self.config.hidden_size])
|
| 1997 |
+
|
| 1998 |
+
|
| 1999 |
+
@add_start_docstrings(
|
| 2000 |
+
"""
|
| 2001 |
+
Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
| 2002 |
+
layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 2003 |
+
""",
|
| 2004 |
+
BERT_START_DOCSTRING,
|
| 2005 |
+
)
|
| 2006 |
+
class TFBertForQuestionAnswering(TFBertPreTrainedModel, TFQuestionAnsweringLoss):
|
| 2007 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 2008 |
+
_keys_to_ignore_on_load_unexpected = [
|
| 2009 |
+
r"pooler",
|
| 2010 |
+
r"mlm___cls",
|
| 2011 |
+
r"nsp___cls",
|
| 2012 |
+
r"cls.predictions",
|
| 2013 |
+
r"cls.seq_relationship",
|
| 2014 |
+
]
|
| 2015 |
+
|
| 2016 |
+
def __init__(self, config: BertConfig, *inputs, **kwargs):
|
| 2017 |
+
super().__init__(config, *inputs, **kwargs)
|
| 2018 |
+
|
| 2019 |
+
self.num_labels = config.num_labels
|
| 2020 |
+
|
| 2021 |
+
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
|
| 2022 |
+
self.qa_outputs = keras.layers.Dense(
|
| 2023 |
+
units=config.num_labels,
|
| 2024 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 2025 |
+
name="qa_outputs",
|
| 2026 |
+
)
|
| 2027 |
+
self.config = config
|
| 2028 |
+
|
| 2029 |
+
@unpack_inputs
|
| 2030 |
+
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 2031 |
+
@add_code_sample_docstrings(
|
| 2032 |
+
checkpoint=_CHECKPOINT_FOR_QA,
|
| 2033 |
+
output_type=TFQuestionAnsweringModelOutput,
|
| 2034 |
+
config_class=_CONFIG_FOR_DOC,
|
| 2035 |
+
qa_target_start_index=_QA_TARGET_START_INDEX,
|
| 2036 |
+
qa_target_end_index=_QA_TARGET_END_INDEX,
|
| 2037 |
+
expected_output=_QA_EXPECTED_OUTPUT,
|
| 2038 |
+
expected_loss=_QA_EXPECTED_LOSS,
|
| 2039 |
+
)
|
| 2040 |
+
def call(
|
| 2041 |
+
self,
|
| 2042 |
+
input_ids: TFModelInputType | None = None,
|
| 2043 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 2044 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 2045 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 2046 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 2047 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 2048 |
+
output_attentions: Optional[bool] = None,
|
| 2049 |
+
output_hidden_states: Optional[bool] = None,
|
| 2050 |
+
return_dict: Optional[bool] = None,
|
| 2051 |
+
start_positions: np.ndarray | tf.Tensor | None = None,
|
| 2052 |
+
end_positions: np.ndarray | tf.Tensor | None = None,
|
| 2053 |
+
training: Optional[bool] = False,
|
| 2054 |
+
) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
|
| 2055 |
+
r"""
|
| 2056 |
+
start_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 2057 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 2058 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 2059 |
+
are not taken into account for computing the loss.
|
| 2060 |
+
end_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
|
| 2061 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 2062 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 2063 |
+
are not taken into account for computing the loss.
|
| 2064 |
+
"""
|
| 2065 |
+
outputs = self.bert(
|
| 2066 |
+
input_ids=input_ids,
|
| 2067 |
+
attention_mask=attention_mask,
|
| 2068 |
+
token_type_ids=token_type_ids,
|
| 2069 |
+
position_ids=position_ids,
|
| 2070 |
+
head_mask=head_mask,
|
| 2071 |
+
inputs_embeds=inputs_embeds,
|
| 2072 |
+
output_attentions=output_attentions,
|
| 2073 |
+
output_hidden_states=output_hidden_states,
|
| 2074 |
+
return_dict=return_dict,
|
| 2075 |
+
training=training,
|
| 2076 |
+
)
|
| 2077 |
+
sequence_output = outputs[0]
|
| 2078 |
+
logits = self.qa_outputs(inputs=sequence_output)
|
| 2079 |
+
start_logits, end_logits = tf.split(value=logits, num_or_size_splits=2, axis=-1)
|
| 2080 |
+
start_logits = tf.squeeze(input=start_logits, axis=-1)
|
| 2081 |
+
end_logits = tf.squeeze(input=end_logits, axis=-1)
|
| 2082 |
+
loss = None
|
| 2083 |
+
|
| 2084 |
+
if start_positions is not None and end_positions is not None:
|
| 2085 |
+
labels = {"start_position": start_positions}
|
| 2086 |
+
labels["end_position"] = end_positions
|
| 2087 |
+
loss = self.hf_compute_loss(labels=labels, logits=(start_logits, end_logits))
|
| 2088 |
+
|
| 2089 |
+
if not return_dict:
|
| 2090 |
+
output = (start_logits, end_logits) + outputs[2:]
|
| 2091 |
+
return ((loss,) + output) if loss is not None else output
|
| 2092 |
+
|
| 2093 |
+
return TFQuestionAnsweringModelOutput(
|
| 2094 |
+
loss=loss,
|
| 2095 |
+
start_logits=start_logits,
|
| 2096 |
+
end_logits=end_logits,
|
| 2097 |
+
hidden_states=outputs.hidden_states,
|
| 2098 |
+
attentions=outputs.attentions,
|
| 2099 |
+
)
|
| 2100 |
+
|
| 2101 |
+
def build(self, input_shape=None):
|
| 2102 |
+
if self.built:
|
| 2103 |
+
return
|
| 2104 |
+
self.built = True
|
| 2105 |
+
if getattr(self, "bert", None) is not None:
|
| 2106 |
+
with tf.name_scope(self.bert.name):
|
| 2107 |
+
self.bert.build(None)
|
| 2108 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 2109 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 2110 |
+
self.qa_outputs.build([None, None, self.config.hidden_size])
|
| 2111 |
+
|
| 2112 |
+
|
| 2113 |
+
__all__ = [
|
| 2114 |
+
"TFBertEmbeddings",
|
| 2115 |
+
"TFBertForMaskedLM",
|
| 2116 |
+
"TFBertForMultipleChoice",
|
| 2117 |
+
"TFBertForNextSentencePrediction",
|
| 2118 |
+
"TFBertForPreTraining",
|
| 2119 |
+
"TFBertForQuestionAnswering",
|
| 2120 |
+
"TFBertForSequenceClassification",
|
| 2121 |
+
"TFBertForTokenClassification",
|
| 2122 |
+
"TFBertLMHeadModel",
|
| 2123 |
+
"TFBertMainLayer",
|
| 2124 |
+
"TFBertModel",
|
| 2125 |
+
"TFBertPreTrainedModel",
|
| 2126 |
+
]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 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 |
+
"""Tokenization classes for Bert."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import os
|
| 19 |
+
import unicodedata
|
| 20 |
+
from typing import List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load_vocab(vocab_file):
|
| 32 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 33 |
+
vocab = collections.OrderedDict()
|
| 34 |
+
with open(vocab_file, "r", encoding="utf-8") as reader:
|
| 35 |
+
tokens = reader.readlines()
|
| 36 |
+
for index, token in enumerate(tokens):
|
| 37 |
+
token = token.rstrip("\n")
|
| 38 |
+
vocab[token] = index
|
| 39 |
+
return vocab
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def whitespace_tokenize(text):
|
| 43 |
+
"""Runs basic whitespace cleaning and splitting on a piece of text."""
|
| 44 |
+
text = text.strip()
|
| 45 |
+
if not text:
|
| 46 |
+
return []
|
| 47 |
+
tokens = text.split()
|
| 48 |
+
return tokens
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class BertTokenizer(PreTrainedTokenizer):
|
| 52 |
+
r"""
|
| 53 |
+
Construct a BERT tokenizer. Based on WordPiece.
|
| 54 |
+
|
| 55 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 56 |
+
this superclass for more information regarding those methods.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
vocab_file (`str`):
|
| 60 |
+
File containing the vocabulary.
|
| 61 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 62 |
+
Whether or not to lowercase the input when tokenizing.
|
| 63 |
+
do_basic_tokenize (`bool`, *optional*, defaults to `True`):
|
| 64 |
+
Whether or not to do basic tokenization before WordPiece.
|
| 65 |
+
never_split (`Iterable`, *optional*):
|
| 66 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 67 |
+
`do_basic_tokenize=True`
|
| 68 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 69 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 70 |
+
token instead.
|
| 71 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 72 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 73 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 74 |
+
token of a sequence built with special tokens.
|
| 75 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 76 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 77 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 78 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 79 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 80 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 81 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 82 |
+
modeling. This is the token which the model will try to predict.
|
| 83 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether or not to tokenize Chinese characters.
|
| 85 |
+
|
| 86 |
+
This should likely be deactivated for Japanese (see this
|
| 87 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 88 |
+
strip_accents (`bool`, *optional*):
|
| 89 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 90 |
+
value for `lowercase` (as in the original BERT).
|
| 91 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
|
| 92 |
+
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
|
| 93 |
+
extra spaces.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
vocab_file,
|
| 101 |
+
do_lower_case=True,
|
| 102 |
+
do_basic_tokenize=True,
|
| 103 |
+
never_split=None,
|
| 104 |
+
unk_token="[UNK]",
|
| 105 |
+
sep_token="[SEP]",
|
| 106 |
+
pad_token="[PAD]",
|
| 107 |
+
cls_token="[CLS]",
|
| 108 |
+
mask_token="[MASK]",
|
| 109 |
+
tokenize_chinese_chars=True,
|
| 110 |
+
strip_accents=None,
|
| 111 |
+
clean_up_tokenization_spaces=True,
|
| 112 |
+
**kwargs,
|
| 113 |
+
):
|
| 114 |
+
if not os.path.isfile(vocab_file):
|
| 115 |
+
raise ValueError(
|
| 116 |
+
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
|
| 117 |
+
" model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
|
| 118 |
+
)
|
| 119 |
+
self.vocab = load_vocab(vocab_file)
|
| 120 |
+
self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
|
| 121 |
+
self.do_basic_tokenize = do_basic_tokenize
|
| 122 |
+
if do_basic_tokenize:
|
| 123 |
+
self.basic_tokenizer = BasicTokenizer(
|
| 124 |
+
do_lower_case=do_lower_case,
|
| 125 |
+
never_split=never_split,
|
| 126 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 127 |
+
strip_accents=strip_accents,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
|
| 131 |
+
|
| 132 |
+
super().__init__(
|
| 133 |
+
do_lower_case=do_lower_case,
|
| 134 |
+
do_basic_tokenize=do_basic_tokenize,
|
| 135 |
+
never_split=never_split,
|
| 136 |
+
unk_token=unk_token,
|
| 137 |
+
sep_token=sep_token,
|
| 138 |
+
pad_token=pad_token,
|
| 139 |
+
cls_token=cls_token,
|
| 140 |
+
mask_token=mask_token,
|
| 141 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 142 |
+
strip_accents=strip_accents,
|
| 143 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 144 |
+
**kwargs,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def do_lower_case(self):
|
| 149 |
+
return self.basic_tokenizer.do_lower_case
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def vocab_size(self):
|
| 153 |
+
return len(self.vocab)
|
| 154 |
+
|
| 155 |
+
def get_vocab(self):
|
| 156 |
+
return dict(self.vocab, **self.added_tokens_encoder)
|
| 157 |
+
|
| 158 |
+
def _tokenize(self, text, split_special_tokens=False):
|
| 159 |
+
split_tokens = []
|
| 160 |
+
if self.do_basic_tokenize:
|
| 161 |
+
for token in self.basic_tokenizer.tokenize(
|
| 162 |
+
text, never_split=self.all_special_tokens if not split_special_tokens else None
|
| 163 |
+
):
|
| 164 |
+
# If the token is part of the never_split set
|
| 165 |
+
if token in self.basic_tokenizer.never_split:
|
| 166 |
+
split_tokens.append(token)
|
| 167 |
+
else:
|
| 168 |
+
split_tokens += self.wordpiece_tokenizer.tokenize(token)
|
| 169 |
+
else:
|
| 170 |
+
split_tokens = self.wordpiece_tokenizer.tokenize(text)
|
| 171 |
+
return split_tokens
|
| 172 |
+
|
| 173 |
+
def _convert_token_to_id(self, token):
|
| 174 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 175 |
+
return self.vocab.get(token, self.vocab.get(self.unk_token))
|
| 176 |
+
|
| 177 |
+
def _convert_id_to_token(self, index):
|
| 178 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 179 |
+
return self.ids_to_tokens.get(index, self.unk_token)
|
| 180 |
+
|
| 181 |
+
def convert_tokens_to_string(self, tokens):
|
| 182 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 183 |
+
out_string = " ".join(tokens).replace(" ##", "").strip()
|
| 184 |
+
return out_string
|
| 185 |
+
|
| 186 |
+
def build_inputs_with_special_tokens(
|
| 187 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 188 |
+
) -> List[int]:
|
| 189 |
+
"""
|
| 190 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 191 |
+
adding special tokens. A BERT sequence has the following format:
|
| 192 |
+
|
| 193 |
+
- single sequence: `[CLS] X [SEP]`
|
| 194 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
token_ids_0 (`List[int]`):
|
| 198 |
+
List of IDs to which the special tokens will be added.
|
| 199 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 200 |
+
Optional second list of IDs for sequence pairs.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 204 |
+
"""
|
| 205 |
+
if token_ids_1 is None:
|
| 206 |
+
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 207 |
+
cls = [self.cls_token_id]
|
| 208 |
+
sep = [self.sep_token_id]
|
| 209 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 210 |
+
|
| 211 |
+
def get_special_tokens_mask(
|
| 212 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
| 213 |
+
) -> List[int]:
|
| 214 |
+
"""
|
| 215 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
| 216 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
token_ids_0 (`List[int]`):
|
| 220 |
+
List of IDs.
|
| 221 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 222 |
+
Optional second list of IDs for sequence pairs.
|
| 223 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 224 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
if already_has_special_tokens:
|
| 231 |
+
return super().get_special_tokens_mask(
|
| 232 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
if token_ids_1 is not None:
|
| 236 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
|
| 237 |
+
return [1] + ([0] * len(token_ids_0)) + [1]
|
| 238 |
+
|
| 239 |
+
def create_token_type_ids_from_sequences(
|
| 240 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 241 |
+
) -> List[int]:
|
| 242 |
+
"""
|
| 243 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
|
| 244 |
+
pair mask has the following format:
|
| 245 |
+
|
| 246 |
+
```
|
| 247 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 248 |
+
| first sequence | second sequence |
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
token_ids_0 (`List[int]`):
|
| 255 |
+
List of IDs.
|
| 256 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 257 |
+
Optional second list of IDs for sequence pairs.
|
| 258 |
+
|
| 259 |
+
Returns:
|
| 260 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 261 |
+
"""
|
| 262 |
+
sep = [self.sep_token_id]
|
| 263 |
+
cls = [self.cls_token_id]
|
| 264 |
+
if token_ids_1 is None:
|
| 265 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 266 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 267 |
+
|
| 268 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 269 |
+
index = 0
|
| 270 |
+
if os.path.isdir(save_directory):
|
| 271 |
+
vocab_file = os.path.join(
|
| 272 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 273 |
+
)
|
| 274 |
+
else:
|
| 275 |
+
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
|
| 276 |
+
with open(vocab_file, "w", encoding="utf-8") as writer:
|
| 277 |
+
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
|
| 278 |
+
if index != token_index:
|
| 279 |
+
logger.warning(
|
| 280 |
+
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
|
| 281 |
+
" Please check that the vocabulary is not corrupted!"
|
| 282 |
+
)
|
| 283 |
+
index = token_index
|
| 284 |
+
writer.write(token + "\n")
|
| 285 |
+
index += 1
|
| 286 |
+
return (vocab_file,)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class BasicTokenizer:
|
| 290 |
+
"""
|
| 291 |
+
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
|
| 292 |
+
|
| 293 |
+
Args:
|
| 294 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 295 |
+
Whether or not to lowercase the input when tokenizing.
|
| 296 |
+
never_split (`Iterable`, *optional*):
|
| 297 |
+
Collection of tokens which will never be split during tokenization. Only has an effect when
|
| 298 |
+
`do_basic_tokenize=True`
|
| 299 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 300 |
+
Whether or not to tokenize Chinese characters.
|
| 301 |
+
|
| 302 |
+
This should likely be deactivated for Japanese (see this
|
| 303 |
+
[issue](https://github.com/huggingface/transformers/issues/328)).
|
| 304 |
+
strip_accents (`bool`, *optional*):
|
| 305 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 306 |
+
value for `lowercase` (as in the original BERT).
|
| 307 |
+
do_split_on_punc (`bool`, *optional*, defaults to `True`):
|
| 308 |
+
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
|
| 309 |
+
the full context of the words, such as contractions.
|
| 310 |
+
"""
|
| 311 |
+
|
| 312 |
+
def __init__(
|
| 313 |
+
self,
|
| 314 |
+
do_lower_case=True,
|
| 315 |
+
never_split=None,
|
| 316 |
+
tokenize_chinese_chars=True,
|
| 317 |
+
strip_accents=None,
|
| 318 |
+
do_split_on_punc=True,
|
| 319 |
+
):
|
| 320 |
+
if never_split is None:
|
| 321 |
+
never_split = []
|
| 322 |
+
self.do_lower_case = do_lower_case
|
| 323 |
+
self.never_split = set(never_split)
|
| 324 |
+
self.tokenize_chinese_chars = tokenize_chinese_chars
|
| 325 |
+
self.strip_accents = strip_accents
|
| 326 |
+
self.do_split_on_punc = do_split_on_punc
|
| 327 |
+
|
| 328 |
+
def tokenize(self, text, never_split=None):
|
| 329 |
+
"""
|
| 330 |
+
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
never_split (`List[str]`, *optional*)
|
| 334 |
+
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
|
| 335 |
+
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
|
| 336 |
+
"""
|
| 337 |
+
# union() returns a new set by concatenating the two sets.
|
| 338 |
+
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
|
| 339 |
+
text = self._clean_text(text)
|
| 340 |
+
|
| 341 |
+
# This was added on November 1st, 2018 for the multilingual and Chinese
|
| 342 |
+
# models. This is also applied to the English models now, but it doesn't
|
| 343 |
+
# matter since the English models were not trained on any Chinese data
|
| 344 |
+
# and generally don't have any Chinese data in them (there are Chinese
|
| 345 |
+
# characters in the vocabulary because Wikipedia does have some Chinese
|
| 346 |
+
# words in the English Wikipedia.).
|
| 347 |
+
if self.tokenize_chinese_chars:
|
| 348 |
+
text = self._tokenize_chinese_chars(text)
|
| 349 |
+
# prevents treating the same character with different unicode codepoints as different characters
|
| 350 |
+
unicode_normalized_text = unicodedata.normalize("NFC", text)
|
| 351 |
+
orig_tokens = whitespace_tokenize(unicode_normalized_text)
|
| 352 |
+
split_tokens = []
|
| 353 |
+
for token in orig_tokens:
|
| 354 |
+
if token not in never_split:
|
| 355 |
+
if self.do_lower_case:
|
| 356 |
+
token = token.lower()
|
| 357 |
+
if self.strip_accents is not False:
|
| 358 |
+
token = self._run_strip_accents(token)
|
| 359 |
+
elif self.strip_accents:
|
| 360 |
+
token = self._run_strip_accents(token)
|
| 361 |
+
split_tokens.extend(self._run_split_on_punc(token, never_split))
|
| 362 |
+
|
| 363 |
+
output_tokens = whitespace_tokenize(" ".join(split_tokens))
|
| 364 |
+
return output_tokens
|
| 365 |
+
|
| 366 |
+
def _run_strip_accents(self, text):
|
| 367 |
+
"""Strips accents from a piece of text."""
|
| 368 |
+
text = unicodedata.normalize("NFD", text)
|
| 369 |
+
output = []
|
| 370 |
+
for char in text:
|
| 371 |
+
cat = unicodedata.category(char)
|
| 372 |
+
if cat == "Mn":
|
| 373 |
+
continue
|
| 374 |
+
output.append(char)
|
| 375 |
+
return "".join(output)
|
| 376 |
+
|
| 377 |
+
def _run_split_on_punc(self, text, never_split=None):
|
| 378 |
+
"""Splits punctuation on a piece of text."""
|
| 379 |
+
if not self.do_split_on_punc or (never_split is not None and text in never_split):
|
| 380 |
+
return [text]
|
| 381 |
+
chars = list(text)
|
| 382 |
+
i = 0
|
| 383 |
+
start_new_word = True
|
| 384 |
+
output = []
|
| 385 |
+
while i < len(chars):
|
| 386 |
+
char = chars[i]
|
| 387 |
+
if _is_punctuation(char):
|
| 388 |
+
output.append([char])
|
| 389 |
+
start_new_word = True
|
| 390 |
+
else:
|
| 391 |
+
if start_new_word:
|
| 392 |
+
output.append([])
|
| 393 |
+
start_new_word = False
|
| 394 |
+
output[-1].append(char)
|
| 395 |
+
i += 1
|
| 396 |
+
|
| 397 |
+
return ["".join(x) for x in output]
|
| 398 |
+
|
| 399 |
+
def _tokenize_chinese_chars(self, text):
|
| 400 |
+
"""Adds whitespace around any CJK character."""
|
| 401 |
+
output = []
|
| 402 |
+
for char in text:
|
| 403 |
+
cp = ord(char)
|
| 404 |
+
if self._is_chinese_char(cp):
|
| 405 |
+
output.append(" ")
|
| 406 |
+
output.append(char)
|
| 407 |
+
output.append(" ")
|
| 408 |
+
else:
|
| 409 |
+
output.append(char)
|
| 410 |
+
return "".join(output)
|
| 411 |
+
|
| 412 |
+
def _is_chinese_char(self, cp):
|
| 413 |
+
"""Checks whether CP is the codepoint of a CJK character."""
|
| 414 |
+
# This defines a "chinese character" as anything in the CJK Unicode block:
|
| 415 |
+
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
|
| 416 |
+
#
|
| 417 |
+
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
|
| 418 |
+
# despite its name. The modern Korean Hangul alphabet is a different block,
|
| 419 |
+
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
|
| 420 |
+
# space-separated words, so they are not treated specially and handled
|
| 421 |
+
# like the all of the other languages.
|
| 422 |
+
if (
|
| 423 |
+
(cp >= 0x4E00 and cp <= 0x9FFF)
|
| 424 |
+
or (cp >= 0x3400 and cp <= 0x4DBF) #
|
| 425 |
+
or (cp >= 0x20000 and cp <= 0x2A6DF) #
|
| 426 |
+
or (cp >= 0x2A700 and cp <= 0x2B73F) #
|
| 427 |
+
or (cp >= 0x2B740 and cp <= 0x2B81F) #
|
| 428 |
+
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
|
| 429 |
+
or (cp >= 0xF900 and cp <= 0xFAFF)
|
| 430 |
+
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
|
| 431 |
+
): #
|
| 432 |
+
return True
|
| 433 |
+
|
| 434 |
+
return False
|
| 435 |
+
|
| 436 |
+
def _clean_text(self, text):
|
| 437 |
+
"""Performs invalid character removal and whitespace cleanup on text."""
|
| 438 |
+
output = []
|
| 439 |
+
for char in text:
|
| 440 |
+
cp = ord(char)
|
| 441 |
+
if cp == 0 or cp == 0xFFFD or _is_control(char):
|
| 442 |
+
continue
|
| 443 |
+
if _is_whitespace(char):
|
| 444 |
+
output.append(" ")
|
| 445 |
+
else:
|
| 446 |
+
output.append(char)
|
| 447 |
+
return "".join(output)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class WordpieceTokenizer:
|
| 451 |
+
"""Runs WordPiece tokenization."""
|
| 452 |
+
|
| 453 |
+
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
|
| 454 |
+
self.vocab = vocab
|
| 455 |
+
self.unk_token = unk_token
|
| 456 |
+
self.max_input_chars_per_word = max_input_chars_per_word
|
| 457 |
+
|
| 458 |
+
def tokenize(self, text):
|
| 459 |
+
"""
|
| 460 |
+
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
|
| 461 |
+
tokenization using the given vocabulary.
|
| 462 |
+
|
| 463 |
+
For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
text: A single token or whitespace separated tokens. This should have
|
| 467 |
+
already been passed through *BasicTokenizer*.
|
| 468 |
+
|
| 469 |
+
Returns:
|
| 470 |
+
A list of wordpiece tokens.
|
| 471 |
+
"""
|
| 472 |
+
|
| 473 |
+
output_tokens = []
|
| 474 |
+
for token in whitespace_tokenize(text):
|
| 475 |
+
chars = list(token)
|
| 476 |
+
if len(chars) > self.max_input_chars_per_word:
|
| 477 |
+
output_tokens.append(self.unk_token)
|
| 478 |
+
continue
|
| 479 |
+
|
| 480 |
+
is_bad = False
|
| 481 |
+
start = 0
|
| 482 |
+
sub_tokens = []
|
| 483 |
+
while start < len(chars):
|
| 484 |
+
end = len(chars)
|
| 485 |
+
cur_substr = None
|
| 486 |
+
while start < end:
|
| 487 |
+
substr = "".join(chars[start:end])
|
| 488 |
+
if start > 0:
|
| 489 |
+
substr = "##" + substr
|
| 490 |
+
if substr in self.vocab:
|
| 491 |
+
cur_substr = substr
|
| 492 |
+
break
|
| 493 |
+
end -= 1
|
| 494 |
+
if cur_substr is None:
|
| 495 |
+
is_bad = True
|
| 496 |
+
break
|
| 497 |
+
sub_tokens.append(cur_substr)
|
| 498 |
+
start = end
|
| 499 |
+
|
| 500 |
+
if is_bad:
|
| 501 |
+
output_tokens.append(self.unk_token)
|
| 502 |
+
else:
|
| 503 |
+
output_tokens.extend(sub_tokens)
|
| 504 |
+
return output_tokens
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
__all__ = ["BasicTokenizer", "BertTokenizer", "WordpieceTokenizer"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert_fast.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 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 |
+
"""Fast Tokenization classes for Bert."""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from typing import List, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from tokenizers import normalizers
|
| 21 |
+
|
| 22 |
+
from ...tokenization_utils_fast import PreTrainedTokenizerFast
|
| 23 |
+
from ...utils import logging
|
| 24 |
+
from .tokenization_bert import BertTokenizer
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class BertTokenizerFast(PreTrainedTokenizerFast):
|
| 33 |
+
r"""
|
| 34 |
+
Construct a "fast" BERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
|
| 35 |
+
|
| 36 |
+
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
|
| 37 |
+
refer to this superclass for more information regarding those methods.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
vocab_file (`str`):
|
| 41 |
+
File containing the vocabulary.
|
| 42 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 43 |
+
Whether or not to lowercase the input when tokenizing.
|
| 44 |
+
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
|
| 45 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 46 |
+
token instead.
|
| 47 |
+
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
|
| 48 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 49 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 50 |
+
token of a sequence built with special tokens.
|
| 51 |
+
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
|
| 52 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 53 |
+
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
|
| 54 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 55 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 56 |
+
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
|
| 57 |
+
The token used for masking values. This is the token used when training this model with masked language
|
| 58 |
+
modeling. This is the token which the model will try to predict.
|
| 59 |
+
clean_text (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether or not to clean the text before tokenization by removing any control characters and replacing all
|
| 61 |
+
whitespaces by the classic one.
|
| 62 |
+
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
|
| 64 |
+
issue](https://github.com/huggingface/transformers/issues/328)).
|
| 65 |
+
strip_accents (`bool`, *optional*):
|
| 66 |
+
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
|
| 67 |
+
value for `lowercase` (as in the original BERT).
|
| 68 |
+
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
|
| 69 |
+
The prefix for subwords.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 73 |
+
slow_tokenizer_class = BertTokenizer
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
vocab_file=None,
|
| 78 |
+
tokenizer_file=None,
|
| 79 |
+
do_lower_case=True,
|
| 80 |
+
unk_token="[UNK]",
|
| 81 |
+
sep_token="[SEP]",
|
| 82 |
+
pad_token="[PAD]",
|
| 83 |
+
cls_token="[CLS]",
|
| 84 |
+
mask_token="[MASK]",
|
| 85 |
+
tokenize_chinese_chars=True,
|
| 86 |
+
strip_accents=None,
|
| 87 |
+
**kwargs,
|
| 88 |
+
):
|
| 89 |
+
super().__init__(
|
| 90 |
+
vocab_file,
|
| 91 |
+
tokenizer_file=tokenizer_file,
|
| 92 |
+
do_lower_case=do_lower_case,
|
| 93 |
+
unk_token=unk_token,
|
| 94 |
+
sep_token=sep_token,
|
| 95 |
+
pad_token=pad_token,
|
| 96 |
+
cls_token=cls_token,
|
| 97 |
+
mask_token=mask_token,
|
| 98 |
+
tokenize_chinese_chars=tokenize_chinese_chars,
|
| 99 |
+
strip_accents=strip_accents,
|
| 100 |
+
**kwargs,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
|
| 104 |
+
if (
|
| 105 |
+
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
|
| 106 |
+
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
|
| 107 |
+
or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
|
| 108 |
+
):
|
| 109 |
+
normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
|
| 110 |
+
normalizer_state["lowercase"] = do_lower_case
|
| 111 |
+
normalizer_state["strip_accents"] = strip_accents
|
| 112 |
+
normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
|
| 113 |
+
self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
|
| 114 |
+
|
| 115 |
+
self.do_lower_case = do_lower_case
|
| 116 |
+
|
| 117 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
| 118 |
+
"""
|
| 119 |
+
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
|
| 120 |
+
adding special tokens. A BERT sequence has the following format:
|
| 121 |
+
|
| 122 |
+
- single sequence: `[CLS] X [SEP]`
|
| 123 |
+
- pair of sequences: `[CLS] A [SEP] B [SEP]`
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
token_ids_0 (`List[int]`):
|
| 127 |
+
List of IDs to which the special tokens will be added.
|
| 128 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 129 |
+
Optional second list of IDs for sequence pairs.
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
|
| 133 |
+
"""
|
| 134 |
+
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
|
| 135 |
+
|
| 136 |
+
if token_ids_1 is not None:
|
| 137 |
+
output += token_ids_1 + [self.sep_token_id]
|
| 138 |
+
|
| 139 |
+
return output
|
| 140 |
+
|
| 141 |
+
def create_token_type_ids_from_sequences(
|
| 142 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
| 143 |
+
) -> List[int]:
|
| 144 |
+
"""
|
| 145 |
+
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
|
| 146 |
+
pair mask has the following format:
|
| 147 |
+
|
| 148 |
+
```
|
| 149 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
| 150 |
+
| first sequence | second sequence |
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
token_ids_0 (`List[int]`):
|
| 157 |
+
List of IDs.
|
| 158 |
+
token_ids_1 (`List[int]`, *optional*):
|
| 159 |
+
Optional second list of IDs for sequence pairs.
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
| 163 |
+
"""
|
| 164 |
+
sep = [self.sep_token_id]
|
| 165 |
+
cls = [self.cls_token_id]
|
| 166 |
+
if token_ids_1 is None:
|
| 167 |
+
return len(cls + token_ids_0 + sep) * [0]
|
| 168 |
+
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
|
| 169 |
+
|
| 170 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 171 |
+
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
|
| 172 |
+
return tuple(files)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
__all__ = ["BertTokenizerFast"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/bert/tokenization_bert_tf.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
from tensorflow_text import BertTokenizer as BertTokenizerLayer
|
| 6 |
+
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utf8, combine_segments, pad_model_inputs
|
| 7 |
+
|
| 8 |
+
from ...modeling_tf_utils import keras
|
| 9 |
+
from .tokenization_bert import BertTokenizer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TFBertTokenizer(keras.layers.Layer):
|
| 13 |
+
"""
|
| 14 |
+
This is an in-graph tokenizer for BERT. It should be initialized similarly to other tokenizers, using the
|
| 15 |
+
`from_pretrained()` method. It can also be initialized with the `from_tokenizer()` method, which imports settings
|
| 16 |
+
from an existing standard tokenizer object.
|
| 17 |
+
|
| 18 |
+
In-graph tokenizers, unlike other Hugging Face tokenizers, are actually Keras layers and are designed to be run
|
| 19 |
+
when the model is called, rather than during preprocessing. As a result, they have somewhat more limited options
|
| 20 |
+
than standard tokenizer classes. They are most useful when you want to create an end-to-end model that goes
|
| 21 |
+
straight from `tf.string` inputs to outputs.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
vocab_list (`list`):
|
| 25 |
+
List containing the vocabulary.
|
| 26 |
+
do_lower_case (`bool`, *optional*, defaults to `True`):
|
| 27 |
+
Whether or not to lowercase the input when tokenizing.
|
| 28 |
+
cls_token_id (`str`, *optional*, defaults to `"[CLS]"`):
|
| 29 |
+
The classifier token which is used when doing sequence classification (classification of the whole sequence
|
| 30 |
+
instead of per-token classification). It is the first token of the sequence when built with special tokens.
|
| 31 |
+
sep_token_id (`str`, *optional*, defaults to `"[SEP]"`):
|
| 32 |
+
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
|
| 33 |
+
sequence classification or for a text and a question for question answering. It is also used as the last
|
| 34 |
+
token of a sequence built with special tokens.
|
| 35 |
+
pad_token_id (`str`, *optional*, defaults to `"[PAD]"`):
|
| 36 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 37 |
+
padding (`str`, defaults to `"longest"`):
|
| 38 |
+
The type of padding to use. Can be either `"longest"`, to pad only up to the longest sample in the batch,
|
| 39 |
+
or `"max_length", to pad all inputs to the maximum length supported by the tokenizer.
|
| 40 |
+
truncation (`bool`, *optional*, defaults to `True`):
|
| 41 |
+
Whether to truncate the sequence to the maximum length.
|
| 42 |
+
max_length (`int`, *optional*, defaults to `512`):
|
| 43 |
+
The maximum length of the sequence, used for padding (if `padding` is "max_length") and/or truncation (if
|
| 44 |
+
`truncation` is `True`).
|
| 45 |
+
pad_to_multiple_of (`int`, *optional*, defaults to `None`):
|
| 46 |
+
If set, the sequence will be padded to a multiple of this value.
|
| 47 |
+
return_token_type_ids (`bool`, *optional*, defaults to `True`):
|
| 48 |
+
Whether to return token_type_ids.
|
| 49 |
+
return_attention_mask (`bool`, *optional*, defaults to `True`):
|
| 50 |
+
Whether to return the attention_mask.
|
| 51 |
+
use_fast_bert_tokenizer (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
If True, will use the FastBertTokenizer class from Tensorflow Text. If False, will use the BertTokenizer
|
| 53 |
+
class instead. BertTokenizer supports some additional options, but is slower and cannot be exported to
|
| 54 |
+
TFLite.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
vocab_list: List,
|
| 60 |
+
do_lower_case: bool,
|
| 61 |
+
cls_token_id: int = None,
|
| 62 |
+
sep_token_id: int = None,
|
| 63 |
+
pad_token_id: int = None,
|
| 64 |
+
padding: str = "longest",
|
| 65 |
+
truncation: bool = True,
|
| 66 |
+
max_length: int = 512,
|
| 67 |
+
pad_to_multiple_of: int = None,
|
| 68 |
+
return_token_type_ids: bool = True,
|
| 69 |
+
return_attention_mask: bool = True,
|
| 70 |
+
use_fast_bert_tokenizer: bool = True,
|
| 71 |
+
**tokenizer_kwargs,
|
| 72 |
+
):
|
| 73 |
+
super().__init__()
|
| 74 |
+
if use_fast_bert_tokenizer:
|
| 75 |
+
self.tf_tokenizer = FastBertTokenizer(
|
| 76 |
+
vocab_list, token_out_type=tf.int64, lower_case_nfd_strip_accents=do_lower_case, **tokenizer_kwargs
|
| 77 |
+
)
|
| 78 |
+
else:
|
| 79 |
+
lookup_table = tf.lookup.StaticVocabularyTable(
|
| 80 |
+
tf.lookup.KeyValueTensorInitializer(
|
| 81 |
+
keys=vocab_list,
|
| 82 |
+
key_dtype=tf.string,
|
| 83 |
+
values=tf.range(tf.size(vocab_list, out_type=tf.int64), dtype=tf.int64),
|
| 84 |
+
value_dtype=tf.int64,
|
| 85 |
+
),
|
| 86 |
+
num_oov_buckets=1,
|
| 87 |
+
)
|
| 88 |
+
self.tf_tokenizer = BertTokenizerLayer(
|
| 89 |
+
lookup_table, token_out_type=tf.int64, lower_case=do_lower_case, **tokenizer_kwargs
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
self.vocab_list = vocab_list
|
| 93 |
+
self.do_lower_case = do_lower_case
|
| 94 |
+
self.cls_token_id = vocab_list.index("[CLS]") if cls_token_id is None else cls_token_id
|
| 95 |
+
self.sep_token_id = vocab_list.index("[SEP]") if sep_token_id is None else sep_token_id
|
| 96 |
+
self.pad_token_id = vocab_list.index("[PAD]") if pad_token_id is None else pad_token_id
|
| 97 |
+
self.paired_trimmer = ShrinkLongestTrimmer(max_length - 3, axis=1) # Allow room for special tokens
|
| 98 |
+
self.max_length = max_length
|
| 99 |
+
self.padding = padding
|
| 100 |
+
self.truncation = truncation
|
| 101 |
+
self.pad_to_multiple_of = pad_to_multiple_of
|
| 102 |
+
self.return_token_type_ids = return_token_type_ids
|
| 103 |
+
self.return_attention_mask = return_attention_mask
|
| 104 |
+
|
| 105 |
+
@classmethod
|
| 106 |
+
def from_tokenizer(cls, tokenizer: "PreTrainedTokenizerBase", **kwargs): # noqa: F821
|
| 107 |
+
"""
|
| 108 |
+
Initialize a `TFBertTokenizer` from an existing `Tokenizer`.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
tokenizer (`PreTrainedTokenizerBase`):
|
| 112 |
+
The tokenizer to use to initialize the `TFBertTokenizer`.
|
| 113 |
+
|
| 114 |
+
Examples:
|
| 115 |
+
|
| 116 |
+
```python
|
| 117 |
+
from transformers import AutoTokenizer, TFBertTokenizer
|
| 118 |
+
|
| 119 |
+
tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 120 |
+
tf_tokenizer = TFBertTokenizer.from_tokenizer(tokenizer)
|
| 121 |
+
```
|
| 122 |
+
"""
|
| 123 |
+
do_lower_case = kwargs.pop("do_lower_case", None)
|
| 124 |
+
do_lower_case = tokenizer.do_lower_case if do_lower_case is None else do_lower_case
|
| 125 |
+
cls_token_id = kwargs.pop("cls_token_id", None)
|
| 126 |
+
cls_token_id = tokenizer.cls_token_id if cls_token_id is None else cls_token_id
|
| 127 |
+
sep_token_id = kwargs.pop("sep_token_id", None)
|
| 128 |
+
sep_token_id = tokenizer.sep_token_id if sep_token_id is None else sep_token_id
|
| 129 |
+
pad_token_id = kwargs.pop("pad_token_id", None)
|
| 130 |
+
pad_token_id = tokenizer.pad_token_id if pad_token_id is None else pad_token_id
|
| 131 |
+
|
| 132 |
+
vocab = tokenizer.get_vocab()
|
| 133 |
+
vocab = sorted(vocab.items(), key=lambda x: x[1])
|
| 134 |
+
vocab_list = [entry[0] for entry in vocab]
|
| 135 |
+
return cls(
|
| 136 |
+
vocab_list=vocab_list,
|
| 137 |
+
do_lower_case=do_lower_case,
|
| 138 |
+
cls_token_id=cls_token_id,
|
| 139 |
+
sep_token_id=sep_token_id,
|
| 140 |
+
pad_token_id=pad_token_id,
|
| 141 |
+
**kwargs,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
@classmethod
|
| 145 |
+
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], *init_inputs, **kwargs):
|
| 146 |
+
"""
|
| 147 |
+
Instantiate a `TFBertTokenizer` from a pre-trained tokenizer.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`):
|
| 151 |
+
The name or path to the pre-trained tokenizer.
|
| 152 |
+
|
| 153 |
+
Examples:
|
| 154 |
+
|
| 155 |
+
```python
|
| 156 |
+
from transformers import TFBertTokenizer
|
| 157 |
+
|
| 158 |
+
tf_tokenizer = TFBertTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 159 |
+
```
|
| 160 |
+
"""
|
| 161 |
+
try:
|
| 162 |
+
tokenizer = BertTokenizer.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
|
| 163 |
+
except: # noqa: E722
|
| 164 |
+
from .tokenization_bert_fast import BertTokenizerFast
|
| 165 |
+
|
| 166 |
+
tokenizer = BertTokenizerFast.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
|
| 167 |
+
return cls.from_tokenizer(tokenizer, **kwargs)
|
| 168 |
+
|
| 169 |
+
def unpaired_tokenize(self, texts):
|
| 170 |
+
if self.do_lower_case:
|
| 171 |
+
texts = case_fold_utf8(texts)
|
| 172 |
+
tokens = self.tf_tokenizer.tokenize(texts)
|
| 173 |
+
return tokens.merge_dims(1, -1)
|
| 174 |
+
|
| 175 |
+
def call(
|
| 176 |
+
self,
|
| 177 |
+
text,
|
| 178 |
+
text_pair=None,
|
| 179 |
+
padding=None,
|
| 180 |
+
truncation=None,
|
| 181 |
+
max_length=None,
|
| 182 |
+
pad_to_multiple_of=None,
|
| 183 |
+
return_token_type_ids=None,
|
| 184 |
+
return_attention_mask=None,
|
| 185 |
+
):
|
| 186 |
+
if padding is None:
|
| 187 |
+
padding = self.padding
|
| 188 |
+
if padding not in ("longest", "max_length"):
|
| 189 |
+
raise ValueError("Padding must be either 'longest' or 'max_length'!")
|
| 190 |
+
if max_length is not None and text_pair is not None:
|
| 191 |
+
# Because we have to instantiate a Trimmer to do it properly
|
| 192 |
+
raise ValueError("max_length cannot be overridden at call time when truncating paired texts!")
|
| 193 |
+
if max_length is None:
|
| 194 |
+
max_length = self.max_length
|
| 195 |
+
if truncation is None:
|
| 196 |
+
truncation = self.truncation
|
| 197 |
+
if pad_to_multiple_of is None:
|
| 198 |
+
pad_to_multiple_of = self.pad_to_multiple_of
|
| 199 |
+
if return_token_type_ids is None:
|
| 200 |
+
return_token_type_ids = self.return_token_type_ids
|
| 201 |
+
if return_attention_mask is None:
|
| 202 |
+
return_attention_mask = self.return_attention_mask
|
| 203 |
+
if not isinstance(text, tf.Tensor):
|
| 204 |
+
text = tf.convert_to_tensor(text)
|
| 205 |
+
if text_pair is not None and not isinstance(text_pair, tf.Tensor):
|
| 206 |
+
text_pair = tf.convert_to_tensor(text_pair)
|
| 207 |
+
if text_pair is not None:
|
| 208 |
+
if text.shape.rank > 1:
|
| 209 |
+
raise ValueError("text argument should not be multidimensional when a text pair is supplied!")
|
| 210 |
+
if text_pair.shape.rank > 1:
|
| 211 |
+
raise ValueError("text_pair should not be multidimensional!")
|
| 212 |
+
if text.shape.rank == 2:
|
| 213 |
+
text, text_pair = text[:, 0], text[:, 1]
|
| 214 |
+
text = self.unpaired_tokenize(text)
|
| 215 |
+
if text_pair is None: # Unpaired text
|
| 216 |
+
if truncation:
|
| 217 |
+
text = text[:, : max_length - 2] # Allow room for special tokens
|
| 218 |
+
input_ids, token_type_ids = combine_segments(
|
| 219 |
+
(text,), start_of_sequence_id=self.cls_token_id, end_of_segment_id=self.sep_token_id
|
| 220 |
+
)
|
| 221 |
+
else: # Paired text
|
| 222 |
+
text_pair = self.unpaired_tokenize(text_pair)
|
| 223 |
+
if truncation:
|
| 224 |
+
text, text_pair = self.paired_trimmer.trim([text, text_pair])
|
| 225 |
+
input_ids, token_type_ids = combine_segments(
|
| 226 |
+
(text, text_pair), start_of_sequence_id=self.cls_token_id, end_of_segment_id=self.sep_token_id
|
| 227 |
+
)
|
| 228 |
+
if padding == "longest":
|
| 229 |
+
pad_length = input_ids.bounding_shape(axis=1)
|
| 230 |
+
if pad_to_multiple_of is not None:
|
| 231 |
+
# No ceiling division in tensorflow, so we negate floordiv instead
|
| 232 |
+
pad_length = pad_to_multiple_of * (-tf.math.floordiv(-pad_length, pad_to_multiple_of))
|
| 233 |
+
else:
|
| 234 |
+
pad_length = max_length
|
| 235 |
+
|
| 236 |
+
input_ids, attention_mask = pad_model_inputs(input_ids, max_seq_length=pad_length, pad_value=self.pad_token_id)
|
| 237 |
+
output = {"input_ids": input_ids}
|
| 238 |
+
if return_attention_mask:
|
| 239 |
+
output["attention_mask"] = attention_mask
|
| 240 |
+
if return_token_type_ids:
|
| 241 |
+
token_type_ids, _ = pad_model_inputs(
|
| 242 |
+
token_type_ids, max_seq_length=pad_length, pad_value=self.pad_token_id
|
| 243 |
+
)
|
| 244 |
+
output["token_type_ids"] = token_type_ids
|
| 245 |
+
return output
|
| 246 |
+
|
| 247 |
+
def get_config(self):
|
| 248 |
+
return {
|
| 249 |
+
"vocab_list": self.vocab_list,
|
| 250 |
+
"do_lower_case": self.do_lower_case,
|
| 251 |
+
"cls_token_id": self.cls_token_id,
|
| 252 |
+
"sep_token_id": self.sep_token_id,
|
| 253 |
+
"pad_token_id": self.pad_token_id,
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
__all__ = ["TFBertTokenizer"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__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_blip import *
|
| 22 |
+
from .image_processing_blip import *
|
| 23 |
+
from .modeling_blip import *
|
| 24 |
+
from .modeling_tf_blip import *
|
| 25 |
+
from .processing_blip 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__)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (622 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/configuration_blip.cpython-310.pyc
ADDED
|
Binary file (13.4 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/convert_blip_original_pytorch_to_hf.cpython-310.pyc
ADDED
|
Binary file (4.68 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/image_processing_blip.cpython-310.pyc
ADDED
|
Binary file (13 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_blip.cpython-310.pyc
ADDED
|
Binary file (53.4 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-310.pyc
ADDED
|
Binary file (28 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-310.pyc
ADDED
|
Binary file (54.5 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-310.pyc
ADDED
|
Binary file (32.3 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/__pycache__/processing_blip.cpython-310.pyc
ADDED
|
Binary file (5.21 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/configuration_blip.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"""Blip 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 BlipTextConfig(PretrainedConfig):
|
| 25 |
+
r"""
|
| 26 |
+
This is the configuration class to store the configuration of a [`BlipTextModel`]. It is used to instantiate a BLIP
|
| 27 |
+
text model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 28 |
+
with the defaults will yield a similar configuration to that of the `BlipText` used by the [base
|
| 29 |
+
architectures](https://huggingface.co/Salesforce/blip-vqa-base).
|
| 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 30524):
|
| 37 |
+
Vocabulary size of the `Blip` text model. Defines the number of different tokens that can be represented by
|
| 38 |
+
the `inputs_ids` passed when calling [`BlipModel`].
|
| 39 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 40 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 41 |
+
encoder_hidden_size (`int`, *optional*, defaults to 768):
|
| 42 |
+
Dimensionality of the encoder layers from the vision model.
|
| 43 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 44 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 45 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 46 |
+
Number of hidden layers in the Transformer encoder.
|
| 47 |
+
num_attention_heads (`int`, *optional*, defaults to 8):
|
| 48 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 49 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
| 50 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 51 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 52 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 53 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 54 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
|
| 55 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 56 |
+
The epsilon used by the layer normalization layers.
|
| 57 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
| 58 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
| 59 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 60 |
+
The dropout ratio for the attention probabilities.
|
| 61 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 62 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 63 |
+
bos_token_id (`int`, *optional*, defaults to 30522):
|
| 64 |
+
The id of the `beginning-of-sequence` token.
|
| 65 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 66 |
+
The id of the `end-of-sequence` token.
|
| 67 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 68 |
+
The id of the `padding` token.
|
| 69 |
+
sep_token_id (`int`, *optional*, defaults to 102):
|
| 70 |
+
The id of the `separator` token.
|
| 71 |
+
is_decoder (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Whether the model is used as a decoder.
|
| 73 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 74 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
| 75 |
+
label_smoothing (float, *optional*):
|
| 76 |
+
A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
|
| 77 |
+
become a mixture of the original ground truth and a uniform distribution as described in
|
| 78 |
+
`Rethinking the Inception Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`__. Default: :math:`0.0`.
|
| 79 |
+
|
| 80 |
+
Example:
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
>>> from transformers import BlipTextConfig, BlipTextModel
|
| 84 |
+
|
| 85 |
+
>>> # Initializing a BlipTextConfig with Salesforce/blip-vqa-base style configuration
|
| 86 |
+
>>> configuration = BlipTextConfig()
|
| 87 |
+
|
| 88 |
+
>>> # Initializing a BlipTextModel (with random weights) from the Salesforce/blip-vqa-base style configuration
|
| 89 |
+
>>> model = BlipTextModel(configuration)
|
| 90 |
+
|
| 91 |
+
>>> # Accessing the model configuration
|
| 92 |
+
>>> configuration = model.config
|
| 93 |
+
```"""
|
| 94 |
+
|
| 95 |
+
model_type = "blip_text_model"
|
| 96 |
+
base_config_key = "text_config"
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
vocab_size=30524,
|
| 101 |
+
hidden_size=768,
|
| 102 |
+
encoder_hidden_size=768,
|
| 103 |
+
intermediate_size=3072,
|
| 104 |
+
projection_dim=768,
|
| 105 |
+
num_hidden_layers=12,
|
| 106 |
+
num_attention_heads=8,
|
| 107 |
+
max_position_embeddings=512,
|
| 108 |
+
hidden_act="gelu",
|
| 109 |
+
layer_norm_eps=1e-12,
|
| 110 |
+
hidden_dropout_prob=0.0,
|
| 111 |
+
attention_probs_dropout_prob=0.0,
|
| 112 |
+
initializer_range=0.02,
|
| 113 |
+
bos_token_id=30522,
|
| 114 |
+
eos_token_id=2,
|
| 115 |
+
pad_token_id=0,
|
| 116 |
+
sep_token_id=102,
|
| 117 |
+
is_decoder=True,
|
| 118 |
+
use_cache=True,
|
| 119 |
+
label_smoothing=0.0,
|
| 120 |
+
**kwargs,
|
| 121 |
+
):
|
| 122 |
+
super().__init__(
|
| 123 |
+
pad_token_id=pad_token_id,
|
| 124 |
+
bos_token_id=bos_token_id,
|
| 125 |
+
eos_token_id=eos_token_id,
|
| 126 |
+
sep_token_id=sep_token_id,
|
| 127 |
+
**kwargs,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
self.vocab_size = vocab_size
|
| 131 |
+
self.hidden_size = hidden_size
|
| 132 |
+
self.encoder_hidden_size = encoder_hidden_size
|
| 133 |
+
self.intermediate_size = intermediate_size
|
| 134 |
+
self.projection_dim = projection_dim
|
| 135 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 136 |
+
self.num_hidden_layers = num_hidden_layers
|
| 137 |
+
self.num_attention_heads = num_attention_heads
|
| 138 |
+
self.max_position_embeddings = max_position_embeddings
|
| 139 |
+
self.layer_norm_eps = layer_norm_eps
|
| 140 |
+
self.hidden_act = hidden_act
|
| 141 |
+
self.initializer_range = initializer_range
|
| 142 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 143 |
+
self.is_decoder = is_decoder
|
| 144 |
+
self.use_cache = use_cache
|
| 145 |
+
self.label_smoothing = label_smoothing
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class BlipVisionConfig(PretrainedConfig):
|
| 149 |
+
r"""
|
| 150 |
+
This is the configuration class to store the configuration of a [`BlipVisionModel`]. It is used to instantiate a
|
| 151 |
+
BLIP vision model according to the specified arguments, defining the model architecture. Instantiating a
|
| 152 |
+
configuration defaults will yield a similar configuration to that of the Blip-base
|
| 153 |
+
[Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
|
| 154 |
+
|
| 155 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 156 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
| 161 |
+
Dimensionality of the encoder layers and the pooler layer.
|
| 162 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
| 163 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
| 164 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
| 165 |
+
Number of hidden layers in the Transformer encoder.
|
| 166 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
| 167 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 168 |
+
image_size (`int`, *optional*, defaults to 384):
|
| 169 |
+
The size (resolution) of each image.
|
| 170 |
+
patch_size (`int`, *optional*, defaults to 16):
|
| 171 |
+
The size (resolution) of each patch.
|
| 172 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
| 173 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
| 174 |
+
`"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
|
| 175 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
|
| 176 |
+
The epsilon used by the layer normalization layers.
|
| 177 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 178 |
+
The dropout ratio for the attention probabilities.
|
| 179 |
+
initializer_range (`float`, *optional*, defaults to 1e-10):
|
| 180 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 181 |
+
|
| 182 |
+
Example:
|
| 183 |
+
|
| 184 |
+
```python
|
| 185 |
+
>>> from transformers import BlipVisionConfig, BlipVisionModel
|
| 186 |
+
|
| 187 |
+
>>> # Initializing a BlipVisionConfig with Salesforce/blip-vqa-base style configuration
|
| 188 |
+
>>> configuration = BlipVisionConfig()
|
| 189 |
+
|
| 190 |
+
>>> # Initializing a BlipVisionModel (with random weights) from the Salesforce/blip-vqa-base style configuration
|
| 191 |
+
>>> model = BlipVisionModel(configuration)
|
| 192 |
+
|
| 193 |
+
>>> # Accessing the model configuration
|
| 194 |
+
>>> configuration = model.config
|
| 195 |
+
```"""
|
| 196 |
+
|
| 197 |
+
model_type = "blip_vision_model"
|
| 198 |
+
base_config_key = "vision_config"
|
| 199 |
+
|
| 200 |
+
def __init__(
|
| 201 |
+
self,
|
| 202 |
+
hidden_size=768,
|
| 203 |
+
intermediate_size=3072,
|
| 204 |
+
projection_dim=512,
|
| 205 |
+
num_hidden_layers=12,
|
| 206 |
+
num_attention_heads=12,
|
| 207 |
+
image_size=384,
|
| 208 |
+
patch_size=16,
|
| 209 |
+
hidden_act="gelu",
|
| 210 |
+
layer_norm_eps=1e-5,
|
| 211 |
+
attention_dropout=0.0,
|
| 212 |
+
initializer_range=1e-10,
|
| 213 |
+
**kwargs,
|
| 214 |
+
):
|
| 215 |
+
super().__init__(**kwargs)
|
| 216 |
+
|
| 217 |
+
self.hidden_size = hidden_size
|
| 218 |
+
self.intermediate_size = intermediate_size
|
| 219 |
+
self.projection_dim = projection_dim
|
| 220 |
+
self.num_hidden_layers = num_hidden_layers
|
| 221 |
+
self.num_attention_heads = num_attention_heads
|
| 222 |
+
self.patch_size = patch_size
|
| 223 |
+
self.image_size = image_size
|
| 224 |
+
self.initializer_range = initializer_range
|
| 225 |
+
self.attention_dropout = attention_dropout
|
| 226 |
+
self.layer_norm_eps = layer_norm_eps
|
| 227 |
+
self.hidden_act = hidden_act
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class BlipConfig(PretrainedConfig):
|
| 231 |
+
r"""
|
| 232 |
+
[`BlipConfig`] is the configuration class to store the configuration of a [`BlipModel`]. It is used to instantiate
|
| 233 |
+
a BLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
|
| 234 |
+
a configuration with the defaults will yield a similar configuration to that of the BLIP-base
|
| 235 |
+
[Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
|
| 236 |
+
|
| 237 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 238 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
text_config (`dict`, *optional*):
|
| 242 |
+
Dictionary of configuration options used to initialize [`BlipTextConfig`].
|
| 243 |
+
vision_config (`dict`, *optional*):
|
| 244 |
+
Dictionary of configuration options used to initialize [`BlipVisionConfig`].
|
| 245 |
+
projection_dim (`int`, *optional*, defaults to 512):
|
| 246 |
+
Dimensionality of text and vision projection layers.
|
| 247 |
+
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
|
| 248 |
+
The initial value of the *logit_scale* parameter. Default is used as per the original BLIP implementation.
|
| 249 |
+
image_text_hidden_size (`int`, *optional*, defaults to 256):
|
| 250 |
+
Dimensionality of the hidden state of the image-text fusion layer.
|
| 251 |
+
label_smoothing (float, optional, *optional*, defaults to 0.0):
|
| 252 |
+
A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
|
| 253 |
+
become a mixture of the original ground truth and a uniform distribution as described in
|
| 254 |
+
`Rethinking the Inception Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`__. Default: :math:`0.0`.
|
| 255 |
+
kwargs (*optional*):
|
| 256 |
+
Dictionary of keyword arguments.
|
| 257 |
+
|
| 258 |
+
Example:
|
| 259 |
+
|
| 260 |
+
```python
|
| 261 |
+
>>> from transformers import BlipConfig, BlipModel
|
| 262 |
+
|
| 263 |
+
>>> # Initializing a BlipConfig with Salesforce/blip-vqa-base style configuration
|
| 264 |
+
>>> configuration = BlipConfig()
|
| 265 |
+
|
| 266 |
+
>>> # Initializing a BlipPModel (with random weights) from the Salesforce/blip-vqa-base style configuration
|
| 267 |
+
>>> model = BlipModel(configuration)
|
| 268 |
+
|
| 269 |
+
>>> # Accessing the model configuration
|
| 270 |
+
>>> configuration = model.config
|
| 271 |
+
|
| 272 |
+
>>> # We can also initialize a BlipConfig from a BlipTextConfig and a BlipVisionConfig
|
| 273 |
+
|
| 274 |
+
>>> # Initializing a BLIPText and BLIPVision configuration
|
| 275 |
+
>>> config_text = BlipTextConfig()
|
| 276 |
+
>>> config_vision = BlipVisionConfig()
|
| 277 |
+
|
| 278 |
+
>>> config = BlipConfig.from_text_vision_configs(config_text, config_vision)
|
| 279 |
+
```"""
|
| 280 |
+
|
| 281 |
+
model_type = "blip"
|
| 282 |
+
sub_configs = {"text_config": BlipTextConfig, "vision_config": BlipVisionConfig}
|
| 283 |
+
|
| 284 |
+
def __init__(
|
| 285 |
+
self,
|
| 286 |
+
text_config=None,
|
| 287 |
+
vision_config=None,
|
| 288 |
+
projection_dim=512,
|
| 289 |
+
logit_scale_init_value=2.6592,
|
| 290 |
+
image_text_hidden_size=256,
|
| 291 |
+
label_smoothing=0.0,
|
| 292 |
+
**kwargs,
|
| 293 |
+
):
|
| 294 |
+
super().__init__(**kwargs)
|
| 295 |
+
|
| 296 |
+
if text_config is None:
|
| 297 |
+
text_config = {}
|
| 298 |
+
logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values.")
|
| 299 |
+
|
| 300 |
+
if vision_config is None:
|
| 301 |
+
vision_config = {}
|
| 302 |
+
logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.")
|
| 303 |
+
|
| 304 |
+
self.text_config = BlipTextConfig(**text_config)
|
| 305 |
+
self.vision_config = BlipVisionConfig(**vision_config)
|
| 306 |
+
|
| 307 |
+
self.text_config.encoder_hidden_size = self.vision_config.hidden_size
|
| 308 |
+
|
| 309 |
+
self.projection_dim = projection_dim
|
| 310 |
+
self.logit_scale_init_value = logit_scale_init_value
|
| 311 |
+
self.initializer_factor = 1.0
|
| 312 |
+
self.initializer_range = 0.02
|
| 313 |
+
self.image_text_hidden_size = image_text_hidden_size
|
| 314 |
+
self.label_smoothing = label_smoothing
|
| 315 |
+
|
| 316 |
+
@classmethod
|
| 317 |
+
def from_text_vision_configs(cls, text_config: BlipTextConfig, vision_config: BlipVisionConfig, **kwargs):
|
| 318 |
+
r"""
|
| 319 |
+
Instantiate a [`BlipConfig`] (or a derived class) from blip text model configuration and blip vision model
|
| 320 |
+
configuration.
|
| 321 |
+
|
| 322 |
+
Returns:
|
| 323 |
+
[`BlipConfig`]: An instance of a configuration object
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
__all__ = ["BlipConfig", "BlipTextConfig", "BlipVisionConfig"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/convert_blip_original_pytorch_to_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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 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
import requests
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
# git clone https://github.com/salesforce/BLIP.git
|
| 23 |
+
from models.blip import blip_decoder
|
| 24 |
+
from models.blip_itm import blip_itm
|
| 25 |
+
from models.blip_vqa import blip_vqa
|
| 26 |
+
from PIL import Image
|
| 27 |
+
from torchvision import transforms
|
| 28 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 29 |
+
|
| 30 |
+
from transformers import (
|
| 31 |
+
BertTokenizer,
|
| 32 |
+
BlipConfig,
|
| 33 |
+
BlipForConditionalGeneration,
|
| 34 |
+
BlipForImageTextRetrieval,
|
| 35 |
+
BlipForQuestionAnswering,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_demo_image(image_size, device):
|
| 40 |
+
img_url = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg"
|
| 41 |
+
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
|
| 42 |
+
|
| 43 |
+
transform = transforms.Compose(
|
| 44 |
+
[
|
| 45 |
+
transforms.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC),
|
| 46 |
+
transforms.ToTensor(),
|
| 47 |
+
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
|
| 48 |
+
]
|
| 49 |
+
)
|
| 50 |
+
image = transform(raw_image).unsqueeze(0).to(device)
|
| 51 |
+
return image
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def rename_key(key):
|
| 55 |
+
if "visual_encoder" in key:
|
| 56 |
+
key = re.sub("visual_encoder*", "vision_model.encoder", key)
|
| 57 |
+
if "blocks" in key:
|
| 58 |
+
key = re.sub(r"blocks", "layers", key)
|
| 59 |
+
if "attn" in key:
|
| 60 |
+
key = re.sub(r"attn", "self_attn", key)
|
| 61 |
+
if "norm1" in key:
|
| 62 |
+
key = re.sub(r"norm1", "layer_norm1", key)
|
| 63 |
+
if "norm2" in key:
|
| 64 |
+
key = re.sub(r"norm2", "layer_norm2", key)
|
| 65 |
+
if "encoder.norm" in key:
|
| 66 |
+
key = re.sub(r"encoder.norm", "post_layernorm", key)
|
| 67 |
+
if "encoder.patch_embed.proj" in key:
|
| 68 |
+
key = re.sub(r"encoder.patch_embed.proj", "embeddings.patch_embedding", key)
|
| 69 |
+
|
| 70 |
+
if "encoder.pos_embed" in key:
|
| 71 |
+
key = re.sub(r"encoder.pos_embed", "embeddings.position_embedding", key)
|
| 72 |
+
if "encoder.cls_token" in key:
|
| 73 |
+
key = re.sub(r"encoder.cls_token", "embeddings.class_embedding", key)
|
| 74 |
+
|
| 75 |
+
if "self_attn" in key:
|
| 76 |
+
key = re.sub(r"self_attn.proj", "self_attn.projection", key)
|
| 77 |
+
|
| 78 |
+
return key
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@torch.no_grad()
|
| 82 |
+
def convert_blip_checkpoint(pytorch_dump_folder_path, config_path=None):
|
| 83 |
+
"""
|
| 84 |
+
Copy/paste/tweak model's weights to transformers design.
|
| 85 |
+
"""
|
| 86 |
+
if config_path is not None:
|
| 87 |
+
config = BlipConfig.from_pretrained(config_path)
|
| 88 |
+
else:
|
| 89 |
+
config = BlipConfig(projection_dim=512, text_config={}, vision_config={})
|
| 90 |
+
|
| 91 |
+
hf_model = BlipForConditionalGeneration(config).eval()
|
| 92 |
+
|
| 93 |
+
model_url = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth"
|
| 94 |
+
|
| 95 |
+
pt_model = blip_decoder(pretrained=model_url, image_size=384, vit="base")
|
| 96 |
+
pt_model = pt_model.eval()
|
| 97 |
+
|
| 98 |
+
modified_state_dict = pt_model.state_dict()
|
| 99 |
+
for key in modified_state_dict.copy():
|
| 100 |
+
value = modified_state_dict.pop(key)
|
| 101 |
+
renamed_key = rename_key(key)
|
| 102 |
+
modified_state_dict[renamed_key] = value
|
| 103 |
+
|
| 104 |
+
hf_model.load_state_dict(modified_state_dict)
|
| 105 |
+
|
| 106 |
+
image_size = 384
|
| 107 |
+
image = load_demo_image(image_size=image_size, device="cpu")
|
| 108 |
+
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
|
| 109 |
+
input_ids = tokenizer(["a picture of"]).input_ids
|
| 110 |
+
|
| 111 |
+
out = hf_model.generate(image, input_ids)
|
| 112 |
+
|
| 113 |
+
assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]
|
| 114 |
+
|
| 115 |
+
out = hf_model.generate(image)
|
| 116 |
+
|
| 117 |
+
assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]
|
| 118 |
+
|
| 119 |
+
if pytorch_dump_folder_path is not None:
|
| 120 |
+
hf_model.save_pretrained(pytorch_dump_folder_path)
|
| 121 |
+
|
| 122 |
+
# model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'
|
| 123 |
+
model_url = (
|
| 124 |
+
"https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
vqa_model = blip_vqa(pretrained=model_url, image_size=image_size, vit="base")
|
| 128 |
+
vqa_model.eval()
|
| 129 |
+
|
| 130 |
+
modified_state_dict = vqa_model.state_dict()
|
| 131 |
+
for key in modified_state_dict.copy():
|
| 132 |
+
value = modified_state_dict.pop(key)
|
| 133 |
+
renamed_key = rename_key(key)
|
| 134 |
+
modified_state_dict[renamed_key] = value
|
| 135 |
+
|
| 136 |
+
hf_vqa_model = BlipForQuestionAnswering(config)
|
| 137 |
+
|
| 138 |
+
hf_vqa_model.load_state_dict(modified_state_dict)
|
| 139 |
+
|
| 140 |
+
question = ["How many dogs are in this image?"]
|
| 141 |
+
question_input_ids = tokenizer(question, return_tensors="pt").input_ids
|
| 142 |
+
|
| 143 |
+
answer = hf_vqa_model.generate(question_input_ids, image)
|
| 144 |
+
print(tokenizer.decode(answer[0]))
|
| 145 |
+
|
| 146 |
+
assert tokenizer.decode(answer[0]) == "[UNK] 1 [SEP]"
|
| 147 |
+
if pytorch_dump_folder_path is not None:
|
| 148 |
+
hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa")
|
| 149 |
+
|
| 150 |
+
model_url = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth"
|
| 151 |
+
|
| 152 |
+
itm_model = blip_itm(pretrained=model_url, image_size=image_size, vit="base")
|
| 153 |
+
itm_model.eval()
|
| 154 |
+
|
| 155 |
+
modified_state_dict = itm_model.state_dict()
|
| 156 |
+
for key in modified_state_dict.copy():
|
| 157 |
+
value = modified_state_dict.pop(key)
|
| 158 |
+
renamed_key = rename_key(key)
|
| 159 |
+
modified_state_dict[renamed_key] = value
|
| 160 |
+
|
| 161 |
+
hf_itm_model = BlipForImageTextRetrieval(config)
|
| 162 |
+
|
| 163 |
+
question = ["A picture of a woman with a dog sitting in a beach"]
|
| 164 |
+
question_input_ids = tokenizer(
|
| 165 |
+
question,
|
| 166 |
+
return_tensors="pt",
|
| 167 |
+
padding="max_length",
|
| 168 |
+
truncation=True,
|
| 169 |
+
max_length=35,
|
| 170 |
+
).input_ids
|
| 171 |
+
|
| 172 |
+
hf_itm_model.load_state_dict(modified_state_dict)
|
| 173 |
+
hf_itm_model.eval()
|
| 174 |
+
|
| 175 |
+
out_itm = hf_itm_model(question_input_ids, image, use_itm_head=True)
|
| 176 |
+
out = hf_itm_model(question_input_ids, image, use_itm_head=False)
|
| 177 |
+
|
| 178 |
+
assert out[0].item() == 0.2110687494277954
|
| 179 |
+
assert torch.nn.functional.softmax(out_itm[0], dim=1)[:, 1].item() == 0.45698845386505127
|
| 180 |
+
|
| 181 |
+
if pytorch_dump_folder_path is not None:
|
| 182 |
+
hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
parser = argparse.ArgumentParser()
|
| 187 |
+
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
|
| 188 |
+
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
|
| 189 |
+
args = parser.parse_args()
|
| 190 |
+
|
| 191 |
+
convert_blip_checkpoint(args.pytorch_dump_folder_path, args.config_path)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/image_processing_blip.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 BLIP."""
|
| 16 |
+
|
| 17 |
+
from typing import Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
|
| 22 |
+
from ...image_transforms import convert_to_rgb, resize, to_channel_dimension_format
|
| 23 |
+
from ...image_utils import (
|
| 24 |
+
OPENAI_CLIP_MEAN,
|
| 25 |
+
OPENAI_CLIP_STD,
|
| 26 |
+
ChannelDimension,
|
| 27 |
+
ImageInput,
|
| 28 |
+
PILImageResampling,
|
| 29 |
+
infer_channel_dimension_format,
|
| 30 |
+
is_scaled_image,
|
| 31 |
+
make_list_of_images,
|
| 32 |
+
to_numpy_array,
|
| 33 |
+
valid_images,
|
| 34 |
+
validate_preprocess_arguments,
|
| 35 |
+
)
|
| 36 |
+
from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if is_vision_available():
|
| 40 |
+
import PIL
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
logger = logging.get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class BlipImageProcessor(BaseImageProcessor):
|
| 47 |
+
r"""
|
| 48 |
+
Constructs a BLIP image processor.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
|
| 53 |
+
`do_resize` parameter in the `preprocess` method.
|
| 54 |
+
size (`dict`, *optional*, defaults to `{"height": 384, "width": 384}`):
|
| 55 |
+
Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
|
| 56 |
+
method.
|
| 57 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 58 |
+
Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
|
| 59 |
+
overridden by the `resample` parameter in the `preprocess` method.
|
| 60 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 61 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
|
| 62 |
+
`do_rescale` parameter in the `preprocess` method.
|
| 63 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 64 |
+
Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
|
| 65 |
+
overridden by the `rescale_factor` parameter in the `preprocess` method.
|
| 66 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 67 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
| 68 |
+
method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
|
| 69 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
| 70 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
| 71 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
|
| 72 |
+
overridden by the `image_mean` parameter in the `preprocess` method.
|
| 73 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
| 74 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
| 75 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 76 |
+
Can be overridden by the `image_std` parameter in the `preprocess` method.
|
| 77 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to convert the image to RGB.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
model_input_names = ["pixel_values"]
|
| 82 |
+
|
| 83 |
+
def __init__(
|
| 84 |
+
self,
|
| 85 |
+
do_resize: bool = True,
|
| 86 |
+
size: Dict[str, int] = None,
|
| 87 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 88 |
+
do_rescale: bool = True,
|
| 89 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 90 |
+
do_normalize: bool = True,
|
| 91 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 92 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 93 |
+
do_convert_rgb: bool = True,
|
| 94 |
+
**kwargs,
|
| 95 |
+
) -> None:
|
| 96 |
+
super().__init__(**kwargs)
|
| 97 |
+
size = size if size is not None else {"height": 384, "width": 384}
|
| 98 |
+
size = get_size_dict(size, default_to_square=True)
|
| 99 |
+
|
| 100 |
+
self.do_resize = do_resize
|
| 101 |
+
self.size = size
|
| 102 |
+
self.resample = resample
|
| 103 |
+
self.do_rescale = do_rescale
|
| 104 |
+
self.rescale_factor = rescale_factor
|
| 105 |
+
self.do_normalize = do_normalize
|
| 106 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
| 107 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
| 108 |
+
self.do_convert_rgb = do_convert_rgb
|
| 109 |
+
|
| 110 |
+
# Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.BICUBIC
|
| 111 |
+
def resize(
|
| 112 |
+
self,
|
| 113 |
+
image: np.ndarray,
|
| 114 |
+
size: Dict[str, int],
|
| 115 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 116 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 117 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 118 |
+
**kwargs,
|
| 119 |
+
) -> np.ndarray:
|
| 120 |
+
"""
|
| 121 |
+
Resize an image to `(size["height"], size["width"])`.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
image (`np.ndarray`):
|
| 125 |
+
Image to resize.
|
| 126 |
+
size (`Dict[str, int]`):
|
| 127 |
+
Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
|
| 128 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
|
| 129 |
+
`PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.
|
| 130 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
| 131 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
| 132 |
+
image is used. Can be one of:
|
| 133 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 134 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 135 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 136 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 137 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 138 |
+
from the input image. Can be one of:
|
| 139 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 140 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 141 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
`np.ndarray`: The resized image.
|
| 145 |
+
"""
|
| 146 |
+
size = get_size_dict(size)
|
| 147 |
+
if "height" not in size or "width" not in size:
|
| 148 |
+
raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
|
| 149 |
+
output_size = (size["height"], size["width"])
|
| 150 |
+
return resize(
|
| 151 |
+
image,
|
| 152 |
+
size=output_size,
|
| 153 |
+
resample=resample,
|
| 154 |
+
data_format=data_format,
|
| 155 |
+
input_data_format=input_data_format,
|
| 156 |
+
**kwargs,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
@filter_out_non_signature_kwargs()
|
| 160 |
+
def preprocess(
|
| 161 |
+
self,
|
| 162 |
+
images: ImageInput,
|
| 163 |
+
do_resize: Optional[bool] = None,
|
| 164 |
+
size: Optional[Dict[str, int]] = None,
|
| 165 |
+
resample: PILImageResampling = None,
|
| 166 |
+
do_rescale: Optional[bool] = None,
|
| 167 |
+
rescale_factor: Optional[float] = None,
|
| 168 |
+
do_normalize: Optional[bool] = None,
|
| 169 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 170 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 171 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 172 |
+
do_convert_rgb: bool = None,
|
| 173 |
+
data_format: ChannelDimension = ChannelDimension.FIRST,
|
| 174 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 175 |
+
) -> PIL.Image.Image:
|
| 176 |
+
"""
|
| 177 |
+
Preprocess an image or batch of images.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
images (`ImageInput`):
|
| 181 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 182 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 183 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 184 |
+
Whether to resize the image.
|
| 185 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 186 |
+
Controls the size of the image after `resize`. The shortest edge of the image is resized to
|
| 187 |
+
`size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image
|
| 188 |
+
is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest
|
| 189 |
+
edge equal to `int(size["shortest_edge"] * (1333 / 800))`.
|
| 190 |
+
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
|
| 191 |
+
Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.
|
| 192 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 193 |
+
Whether to rescale the image values between [0 - 1].
|
| 194 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 195 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 196 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 197 |
+
Whether to normalize the image.
|
| 198 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 199 |
+
Image mean to normalize the image by if `do_normalize` is set to `True`.
|
| 200 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 201 |
+
Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
|
| 202 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 203 |
+
Whether to convert the image to RGB.
|
| 204 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 205 |
+
The type of tensors to return. Can be one of:
|
| 206 |
+
- Unset: Return a list of `np.ndarray`.
|
| 207 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 208 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 209 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 210 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 211 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 212 |
+
The channel dimension format for the output image. Can be one of:
|
| 213 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 214 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 215 |
+
- Unset: Use the channel dimension format of the input image.
|
| 216 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 217 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 218 |
+
from the input image. Can be one of:
|
| 219 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 220 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 221 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 222 |
+
"""
|
| 223 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 224 |
+
resample = resample if resample is not None else self.resample
|
| 225 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 226 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 227 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 228 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 229 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 230 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 231 |
+
|
| 232 |
+
size = size if size is not None else self.size
|
| 233 |
+
size = get_size_dict(size, default_to_square=False)
|
| 234 |
+
|
| 235 |
+
images = make_list_of_images(images)
|
| 236 |
+
|
| 237 |
+
if not valid_images(images):
|
| 238 |
+
raise ValueError(
|
| 239 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 240 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
validate_preprocess_arguments(
|
| 244 |
+
do_rescale=do_rescale,
|
| 245 |
+
rescale_factor=rescale_factor,
|
| 246 |
+
do_normalize=do_normalize,
|
| 247 |
+
image_mean=image_mean,
|
| 248 |
+
image_std=image_std,
|
| 249 |
+
do_resize=do_resize,
|
| 250 |
+
size=size,
|
| 251 |
+
resample=resample,
|
| 252 |
+
)
|
| 253 |
+
# PIL RGBA images are converted to RGB
|
| 254 |
+
if do_convert_rgb:
|
| 255 |
+
images = [convert_to_rgb(image) for image in images]
|
| 256 |
+
|
| 257 |
+
# All transformations expect numpy arrays.
|
| 258 |
+
images = [to_numpy_array(image) for image in images]
|
| 259 |
+
|
| 260 |
+
if do_rescale and is_scaled_image(images[0]):
|
| 261 |
+
logger.warning_once(
|
| 262 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 263 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
if input_data_format is None:
|
| 267 |
+
# We assume that all images have the same channel dimension format.
|
| 268 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 269 |
+
|
| 270 |
+
if do_resize:
|
| 271 |
+
images = [
|
| 272 |
+
self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
|
| 273 |
+
for image in images
|
| 274 |
+
]
|
| 275 |
+
|
| 276 |
+
if do_rescale:
|
| 277 |
+
images = [
|
| 278 |
+
self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
|
| 279 |
+
for image in images
|
| 280 |
+
]
|
| 281 |
+
|
| 282 |
+
if do_normalize:
|
| 283 |
+
images = [
|
| 284 |
+
self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
|
| 285 |
+
for image in images
|
| 286 |
+
]
|
| 287 |
+
|
| 288 |
+
images = [
|
| 289 |
+
to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
|
| 290 |
+
]
|
| 291 |
+
|
| 292 |
+
encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
|
| 293 |
+
|
| 294 |
+
return encoded_outputs
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
__all__ = ["BlipImageProcessor"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_blip.py
ADDED
|
@@ -0,0 +1,1603 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch BLIP model."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn.functional import normalize
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...generation import GenerationMixin
|
| 28 |
+
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
| 29 |
+
from ...modeling_utils import PreTrainedModel
|
| 30 |
+
from ...utils import (
|
| 31 |
+
ModelOutput,
|
| 32 |
+
add_start_docstrings,
|
| 33 |
+
add_start_docstrings_to_model_forward,
|
| 34 |
+
logging,
|
| 35 |
+
replace_return_docstrings,
|
| 36 |
+
torch_int,
|
| 37 |
+
)
|
| 38 |
+
from .configuration_blip import BlipConfig, BlipTextConfig, BlipVisionConfig
|
| 39 |
+
from .modeling_blip_text import BlipTextLMHeadModel, BlipTextModel
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
_CHECKPOINT_FOR_DOC = "Salesforce/blip-vqa-base"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Copied from transformers.models.clip.modeling_clip.contrastive_loss
|
| 48 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Copied from transformers.models.clip.modeling_clip.clip_loss with clip->blip
|
| 53 |
+
def blip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 54 |
+
caption_loss = contrastive_loss(similarity)
|
| 55 |
+
image_loss = contrastive_loss(similarity.t())
|
| 56 |
+
return (caption_loss + image_loss) / 2.0
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class BlipForConditionalGenerationModelOutput(ModelOutput):
|
| 61 |
+
"""
|
| 62 |
+
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
|
| 63 |
+
last hidden states. This class also adds the loss term from the text decoder.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
| 67 |
+
Languge modeling loss from the text decoder.
|
| 68 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
|
| 69 |
+
Prediction scores of the language modeling head of the text decoder model.
|
| 70 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*):
|
| 71 |
+
The image embeddings obtained after applying the Vision Transformer model to the input image.
|
| 72 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 73 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 74 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
|
| 75 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 76 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 77 |
+
|
| 78 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 79 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed):
|
| 80 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 81 |
+
sequence_length)`.
|
| 82 |
+
|
| 83 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 84 |
+
heads.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
loss: Optional[Tuple[torch.FloatTensor]] = None
|
| 88 |
+
logits: Optional[Tuple[torch.FloatTensor]] = None
|
| 89 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 90 |
+
last_hidden_state: torch.FloatTensor = None
|
| 91 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 92 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def decoder_logits(self):
|
| 96 |
+
warnings.warn(
|
| 97 |
+
"`decoder_logits` attribute is deprecated and will be removed in version 5 of Transformers."
|
| 98 |
+
" Please use the `logits` attribute to retrieve the final output instead.",
|
| 99 |
+
FutureWarning,
|
| 100 |
+
)
|
| 101 |
+
return self.logits
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@dataclass
|
| 105 |
+
class BlipTextVisionModelOutput(ModelOutput):
|
| 106 |
+
"""
|
| 107 |
+
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
|
| 108 |
+
last hidden states. This class also adds the loss term from the text decoder.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 112 |
+
Languge modeling loss from the text decoder.
|
| 113 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 114 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 115 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 116 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 117 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 118 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 119 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 120 |
+
|
| 121 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 122 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 123 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 124 |
+
sequence_length)`.
|
| 125 |
+
|
| 126 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 127 |
+
heads.
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
loss: Optional[torch.FloatTensor] = None
|
| 131 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 132 |
+
last_hidden_state: torch.FloatTensor = None
|
| 133 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 134 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@dataclass
|
| 138 |
+
class BlipImageTextMatchingModelOutput(ModelOutput):
|
| 139 |
+
"""
|
| 140 |
+
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
|
| 141 |
+
last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
|
| 142 |
+
scores.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
itm_score (`torch.FloatTensor`):
|
| 146 |
+
The image-text similarity scores.
|
| 147 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 148 |
+
Languge modeling loss from the text decoder.
|
| 149 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 150 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 151 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 152 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 153 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 154 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 155 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 156 |
+
|
| 157 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 158 |
+
vision_pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
|
| 159 |
+
Last layer hidden-state of the vision of the vision-only branch of the model.
|
| 160 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 161 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 162 |
+
sequence_length)`.
|
| 163 |
+
|
| 164 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 165 |
+
heads.
|
| 166 |
+
question_embeds (`torch.FloatTensor`):
|
| 167 |
+
The question embeddings obtained by the text projection layer.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
itm_score: Optional[torch.FloatTensor] = None
|
| 171 |
+
loss: Optional[torch.FloatTensor] = None
|
| 172 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 173 |
+
last_hidden_state: torch.FloatTensor = None
|
| 174 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 175 |
+
vision_pooler_output: Optional[torch.FloatTensor] = None
|
| 176 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 177 |
+
question_embeds: Optional[Tuple[torch.FloatTensor]] = None
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@dataclass
|
| 181 |
+
class BlipOutput(ModelOutput):
|
| 182 |
+
"""
|
| 183 |
+
Args:
|
| 184 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 185 |
+
Contrastive loss for image-text similarity.
|
| 186 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 187 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 188 |
+
similarity scores.
|
| 189 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 190 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 191 |
+
similarity scores.
|
| 192 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 193 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
|
| 194 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 195 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
|
| 196 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
| 197 |
+
The output of the [`BlipTextModel`].
|
| 198 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
| 199 |
+
The output of the [`BlipVisionModel`].
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
loss: Optional[torch.FloatTensor] = None
|
| 203 |
+
logits_per_image: torch.FloatTensor = None
|
| 204 |
+
logits_per_text: torch.FloatTensor = None
|
| 205 |
+
text_embeds: torch.FloatTensor = None
|
| 206 |
+
image_embeds: torch.FloatTensor = None
|
| 207 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 208 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 209 |
+
|
| 210 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 211 |
+
return tuple(
|
| 212 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 213 |
+
for k in self.keys()
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class BlipVisionEmbeddings(nn.Module):
|
| 218 |
+
def __init__(self, config: BlipVisionConfig):
|
| 219 |
+
super().__init__()
|
| 220 |
+
self.config = config
|
| 221 |
+
self.embed_dim = config.hidden_size
|
| 222 |
+
self.image_size = config.image_size
|
| 223 |
+
self.patch_size = config.patch_size
|
| 224 |
+
|
| 225 |
+
self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))
|
| 226 |
+
|
| 227 |
+
self.patch_embedding = nn.Conv2d(
|
| 228 |
+
in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 232 |
+
self.num_positions = self.num_patches + 1
|
| 233 |
+
|
| 234 |
+
self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
|
| 235 |
+
|
| 236 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 237 |
+
"""
|
| 238 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 239 |
+
images. This method is also adapted to support torch.jit tracing.
|
| 240 |
+
|
| 241 |
+
Adapted from:
|
| 242 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 243 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
num_patches = embeddings.shape[1] - 1
|
| 247 |
+
num_positions = self.position_embedding.shape[1] - 1
|
| 248 |
+
|
| 249 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 250 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 251 |
+
return self.position_embedding
|
| 252 |
+
|
| 253 |
+
class_pos_embed = self.position_embedding[:, :1]
|
| 254 |
+
patch_pos_embed = self.position_embedding[:, 1:]
|
| 255 |
+
|
| 256 |
+
dim = embeddings.shape[-1]
|
| 257 |
+
|
| 258 |
+
new_height = height // self.patch_size
|
| 259 |
+
new_width = width // self.patch_size
|
| 260 |
+
|
| 261 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 262 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 263 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 264 |
+
|
| 265 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 266 |
+
patch_pos_embed,
|
| 267 |
+
size=(new_height, new_width),
|
| 268 |
+
mode="bicubic",
|
| 269 |
+
align_corners=False,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 273 |
+
|
| 274 |
+
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
|
| 275 |
+
|
| 276 |
+
def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
|
| 277 |
+
batch_size, _, height, width = pixel_values.shape
|
| 278 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 279 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 280 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 281 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
|
| 282 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 283 |
+
if interpolate_pos_encoding:
|
| 284 |
+
position_embedding = self.interpolate_pos_encoding(embeddings, height, width)
|
| 285 |
+
else:
|
| 286 |
+
position_embedding = self.position_embedding
|
| 287 |
+
embeddings = embeddings + position_embedding[:, : embeddings.size(1), :].to(target_dtype)
|
| 288 |
+
return embeddings
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Blip
|
| 292 |
+
class BlipTextEmbeddings(nn.Module):
|
| 293 |
+
def __init__(self, config: BlipTextConfig):
|
| 294 |
+
super().__init__()
|
| 295 |
+
embed_dim = config.hidden_size
|
| 296 |
+
|
| 297 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
| 298 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
| 299 |
+
|
| 300 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 301 |
+
self.register_buffer(
|
| 302 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
def forward(
|
| 306 |
+
self,
|
| 307 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 308 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 309 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 310 |
+
) -> torch.Tensor:
|
| 311 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
| 312 |
+
max_position_embedding = self.position_embedding.weight.shape[0]
|
| 313 |
+
|
| 314 |
+
if seq_length > max_position_embedding:
|
| 315 |
+
raise ValueError(
|
| 316 |
+
f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
|
| 317 |
+
f"{seq_length} and max_position_embeddings: {max_position_embedding}"
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
if position_ids is None:
|
| 321 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 322 |
+
|
| 323 |
+
if inputs_embeds is None:
|
| 324 |
+
inputs_embeds = self.token_embedding(input_ids)
|
| 325 |
+
|
| 326 |
+
position_embeddings = self.position_embedding(position_ids)
|
| 327 |
+
embeddings = inputs_embeds + position_embeddings
|
| 328 |
+
|
| 329 |
+
return embeddings
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class BlipAttention(nn.Module):
|
| 333 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 334 |
+
|
| 335 |
+
def __init__(self, config):
|
| 336 |
+
super().__init__()
|
| 337 |
+
self.config = config
|
| 338 |
+
self.embed_dim = config.hidden_size
|
| 339 |
+
self.num_heads = config.num_attention_heads
|
| 340 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 341 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 342 |
+
raise ValueError(
|
| 343 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 344 |
+
f" {self.num_heads})."
|
| 345 |
+
)
|
| 346 |
+
self.scale = self.head_dim**-0.5
|
| 347 |
+
self.dropout = nn.Dropout(config.attention_dropout)
|
| 348 |
+
|
| 349 |
+
self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim)
|
| 350 |
+
|
| 351 |
+
self.projection = nn.Linear(self.embed_dim, self.embed_dim)
|
| 352 |
+
|
| 353 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 354 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 355 |
+
|
| 356 |
+
def forward(
|
| 357 |
+
self,
|
| 358 |
+
hidden_states: torch.Tensor,
|
| 359 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 360 |
+
output_attentions: Optional[bool] = False,
|
| 361 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 362 |
+
"""Input shape: Batch x Time x Channel"""
|
| 363 |
+
|
| 364 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 365 |
+
|
| 366 |
+
mixed_qkv = (
|
| 367 |
+
self.qkv(hidden_states)
|
| 368 |
+
.reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads)
|
| 369 |
+
.permute(2, 0, 3, 1, 4)
|
| 370 |
+
)
|
| 371 |
+
query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
|
| 372 |
+
|
| 373 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 374 |
+
attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
|
| 375 |
+
|
| 376 |
+
attention_scores = attention_scores * self.scale
|
| 377 |
+
|
| 378 |
+
# Normalize the attention scores to probabilities.
|
| 379 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 380 |
+
|
| 381 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 382 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 383 |
+
attention_probs = self.dropout(attention_probs)
|
| 384 |
+
|
| 385 |
+
# Mask heads if we want to
|
| 386 |
+
if head_mask is not None:
|
| 387 |
+
attention_probs = attention_probs * head_mask
|
| 388 |
+
|
| 389 |
+
context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3)
|
| 390 |
+
|
| 391 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
|
| 392 |
+
context_layer = context_layer.reshape(new_context_layer_shape)
|
| 393 |
+
|
| 394 |
+
output = self.projection(context_layer)
|
| 395 |
+
|
| 396 |
+
outputs = (output, attention_probs) if output_attentions else (output, None)
|
| 397 |
+
|
| 398 |
+
return outputs
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Blip
|
| 402 |
+
class BlipMLP(nn.Module):
|
| 403 |
+
def __init__(self, config):
|
| 404 |
+
super().__init__()
|
| 405 |
+
self.config = config
|
| 406 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 407 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 408 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 409 |
+
|
| 410 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 411 |
+
hidden_states = self.fc1(hidden_states)
|
| 412 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 413 |
+
hidden_states = self.fc2(hidden_states)
|
| 414 |
+
return hidden_states
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class BlipEncoderLayer(nn.Module):
|
| 418 |
+
def __init__(self, config: BlipConfig):
|
| 419 |
+
super().__init__()
|
| 420 |
+
self.embed_dim = config.hidden_size
|
| 421 |
+
self.self_attn = BlipAttention(config)
|
| 422 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 423 |
+
self.mlp = BlipMLP(config)
|
| 424 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 425 |
+
|
| 426 |
+
def forward(
|
| 427 |
+
self,
|
| 428 |
+
hidden_states: torch.Tensor,
|
| 429 |
+
attention_mask: torch.Tensor,
|
| 430 |
+
output_attentions: Optional[bool] = False,
|
| 431 |
+
) -> Tuple[torch.FloatTensor]:
|
| 432 |
+
"""
|
| 433 |
+
Args:
|
| 434 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 435 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 436 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 437 |
+
`(config.encoder_attention_heads,)`.
|
| 438 |
+
output_attentions (`bool`, *optional*):
|
| 439 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 440 |
+
returned tensors for more detail.
|
| 441 |
+
"""
|
| 442 |
+
residual = hidden_states
|
| 443 |
+
|
| 444 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 445 |
+
hidden_states, attn_weights = self.self_attn(
|
| 446 |
+
hidden_states=hidden_states,
|
| 447 |
+
head_mask=attention_mask,
|
| 448 |
+
output_attentions=output_attentions,
|
| 449 |
+
)
|
| 450 |
+
hidden_states = hidden_states + residual
|
| 451 |
+
residual = hidden_states
|
| 452 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 453 |
+
hidden_states = self.mlp(hidden_states)
|
| 454 |
+
|
| 455 |
+
hidden_states = hidden_states + residual
|
| 456 |
+
|
| 457 |
+
outputs = (hidden_states,)
|
| 458 |
+
|
| 459 |
+
if output_attentions:
|
| 460 |
+
outputs += (attn_weights,)
|
| 461 |
+
|
| 462 |
+
return outputs
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class BlipPreTrainedModel(PreTrainedModel):
|
| 466 |
+
"""
|
| 467 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 468 |
+
models.
|
| 469 |
+
"""
|
| 470 |
+
|
| 471 |
+
config_class = BlipConfig
|
| 472 |
+
base_model_prefix = "blip"
|
| 473 |
+
supports_gradient_checkpointing = True
|
| 474 |
+
_no_split_modules = ["BlipEncoderLayer", "BlipTextEmbeddings"]
|
| 475 |
+
_skip_keys_device_placement = ["past_key_value"]
|
| 476 |
+
|
| 477 |
+
def _init_weights(self, module):
|
| 478 |
+
"""Initialize the weights"""
|
| 479 |
+
factor = self.config.initializer_range
|
| 480 |
+
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear):
|
| 481 |
+
module.weight.data.normal_(mean=0.0, std=factor)
|
| 482 |
+
if hasattr(module, "bias") and module.bias is not None:
|
| 483 |
+
module.bias.data.zero_()
|
| 484 |
+
|
| 485 |
+
if isinstance(module, BlipVisionEmbeddings):
|
| 486 |
+
if hasattr(self.config, "vision_config"):
|
| 487 |
+
factor = self.config.vision_config.initializer_range
|
| 488 |
+
nn.init.trunc_normal_(
|
| 489 |
+
module.position_embedding,
|
| 490 |
+
mean=0.0,
|
| 491 |
+
std=factor,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
nn.init.trunc_normal_(
|
| 495 |
+
module.class_embedding,
|
| 496 |
+
mean=0.0,
|
| 497 |
+
std=factor,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
elif isinstance(module, nn.LayerNorm):
|
| 501 |
+
module.bias.data.zero_()
|
| 502 |
+
module.weight.data.fill_(1.0)
|
| 503 |
+
elif isinstance(module, nn.Linear) and module.bias is not None:
|
| 504 |
+
module.bias.data.zero_()
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
BLIP_START_DOCSTRING = r"""
|
| 508 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 509 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 510 |
+
etc.)
|
| 511 |
+
|
| 512 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 513 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 514 |
+
and behavior.
|
| 515 |
+
|
| 516 |
+
Parameters:
|
| 517 |
+
config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
|
| 518 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 519 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 520 |
+
"""
|
| 521 |
+
|
| 522 |
+
BLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 523 |
+
Args:
|
| 524 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 525 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 526 |
+
it.
|
| 527 |
+
|
| 528 |
+
Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
|
| 529 |
+
|
| 530 |
+
[What are input IDs?](../glossary#input-ids)
|
| 531 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 532 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 533 |
+
|
| 534 |
+
- 1 for tokens that are **not masked**,
|
| 535 |
+
- 0 for tokens that are **masked**.
|
| 536 |
+
|
| 537 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 538 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 539 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 540 |
+
config.max_position_embeddings - 1]`.
|
| 541 |
+
|
| 542 |
+
[What are position IDs?](../glossary#position-ids)
|
| 543 |
+
output_attentions (`bool`, *optional*):
|
| 544 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 545 |
+
tensors for more detail.
|
| 546 |
+
output_hidden_states (`bool`, *optional*):
|
| 547 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 548 |
+
more detail.
|
| 549 |
+
return_dict (`bool`, *optional*):
|
| 550 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 551 |
+
"""
|
| 552 |
+
|
| 553 |
+
BLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 554 |
+
Args:
|
| 555 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 556 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 557 |
+
[`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
|
| 558 |
+
output_attentions (`bool`, *optional*):
|
| 559 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 560 |
+
tensors for more detail.
|
| 561 |
+
output_hidden_states (`bool`, *optional*):
|
| 562 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 563 |
+
more detail.
|
| 564 |
+
return_dict (`bool`, *optional*):
|
| 565 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 566 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
|
| 567 |
+
Whether to interpolate the pre-trained position encodings.
|
| 568 |
+
"""
|
| 569 |
+
|
| 570 |
+
BLIP_INPUTS_DOCSTRING = r"""
|
| 571 |
+
Args:
|
| 572 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 573 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 574 |
+
it.
|
| 575 |
+
|
| 576 |
+
Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
|
| 577 |
+
|
| 578 |
+
[What are input IDs?](../glossary#input-ids)
|
| 579 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 580 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 581 |
+
|
| 582 |
+
- 1 for tokens that are **not masked**,
|
| 583 |
+
- 0 for tokens that are **masked**.
|
| 584 |
+
|
| 585 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 586 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 587 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 588 |
+
config.max_position_embeddings - 1]`.
|
| 589 |
+
|
| 590 |
+
[What are position IDs?](../glossary#position-ids)
|
| 591 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 592 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 593 |
+
[`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
|
| 594 |
+
return_loss (`bool`, *optional*):
|
| 595 |
+
Whether or not to return the contrastive loss.
|
| 596 |
+
output_attentions (`bool`, *optional*):
|
| 597 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 598 |
+
tensors for more detail.
|
| 599 |
+
output_hidden_states (`bool`, *optional*):
|
| 600 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 601 |
+
more detail.
|
| 602 |
+
return_dict (`bool`, *optional*):
|
| 603 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 604 |
+
interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
|
| 605 |
+
Whether to interpolate the pre-trained position encodings.
|
| 606 |
+
"""
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
class BlipEncoder(nn.Module):
|
| 610 |
+
"""
|
| 611 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 612 |
+
[`BlipEncoderLayer`].
|
| 613 |
+
|
| 614 |
+
Args:
|
| 615 |
+
config (`BlipConfig`):
|
| 616 |
+
The corresponding vision configuration for the `BlipEncoder`.
|
| 617 |
+
"""
|
| 618 |
+
|
| 619 |
+
def __init__(self, config: BlipConfig):
|
| 620 |
+
super().__init__()
|
| 621 |
+
self.config = config
|
| 622 |
+
self.layers = nn.ModuleList([BlipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 623 |
+
self.gradient_checkpointing = False
|
| 624 |
+
|
| 625 |
+
def forward(
|
| 626 |
+
self,
|
| 627 |
+
inputs_embeds,
|
| 628 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 629 |
+
output_attentions: Optional[bool] = None,
|
| 630 |
+
output_hidden_states: Optional[bool] = None,
|
| 631 |
+
return_dict: Optional[bool] = None,
|
| 632 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 633 |
+
r"""
|
| 634 |
+
Args:
|
| 635 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 636 |
+
Embedded representation of the inputs. Should be float, not int tokens.
|
| 637 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 638 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 639 |
+
|
| 640 |
+
- 1 for tokens that are **not masked**,
|
| 641 |
+
- 0 for tokens that are **masked**.
|
| 642 |
+
|
| 643 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 644 |
+
output_attentions (`bool`, *optional*):
|
| 645 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 646 |
+
returned tensors for more detail.
|
| 647 |
+
output_hidden_states (`bool`, *optional*):
|
| 648 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 649 |
+
for more detail.
|
| 650 |
+
return_dict (`bool`, *optional*):
|
| 651 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 652 |
+
"""
|
| 653 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 654 |
+
output_hidden_states = (
|
| 655 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 656 |
+
)
|
| 657 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 658 |
+
|
| 659 |
+
encoder_states = () if output_hidden_states else None
|
| 660 |
+
all_attentions = () if output_attentions else None
|
| 661 |
+
|
| 662 |
+
hidden_states = inputs_embeds
|
| 663 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 664 |
+
if output_hidden_states:
|
| 665 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 666 |
+
if self.gradient_checkpointing and self.training:
|
| 667 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 668 |
+
encoder_layer.__call__,
|
| 669 |
+
hidden_states,
|
| 670 |
+
attention_mask,
|
| 671 |
+
output_attentions,
|
| 672 |
+
)
|
| 673 |
+
else:
|
| 674 |
+
layer_outputs = encoder_layer(
|
| 675 |
+
hidden_states,
|
| 676 |
+
attention_mask,
|
| 677 |
+
output_attentions=output_attentions,
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
hidden_states = layer_outputs[0]
|
| 681 |
+
|
| 682 |
+
if output_attentions:
|
| 683 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 684 |
+
|
| 685 |
+
if output_hidden_states:
|
| 686 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 687 |
+
|
| 688 |
+
if not return_dict:
|
| 689 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 690 |
+
return BaseModelOutput(
|
| 691 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
class BlipVisionModel(BlipPreTrainedModel):
|
| 696 |
+
main_input_name = "pixel_values"
|
| 697 |
+
config_class = BlipVisionConfig
|
| 698 |
+
|
| 699 |
+
def __init__(self, config: BlipVisionConfig):
|
| 700 |
+
super().__init__(config)
|
| 701 |
+
self.config = config
|
| 702 |
+
embed_dim = config.hidden_size
|
| 703 |
+
|
| 704 |
+
self.embeddings = BlipVisionEmbeddings(config)
|
| 705 |
+
self.encoder = BlipEncoder(config)
|
| 706 |
+
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 707 |
+
|
| 708 |
+
self.post_init()
|
| 709 |
+
|
| 710 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 711 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=BlipVisionConfig)
|
| 712 |
+
def forward(
|
| 713 |
+
self,
|
| 714 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 715 |
+
output_attentions: Optional[bool] = None,
|
| 716 |
+
output_hidden_states: Optional[bool] = None,
|
| 717 |
+
return_dict: Optional[bool] = None,
|
| 718 |
+
interpolate_pos_encoding: bool = False,
|
| 719 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 720 |
+
r"""
|
| 721 |
+
Returns:
|
| 722 |
+
|
| 723 |
+
"""
|
| 724 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 725 |
+
output_hidden_states = (
|
| 726 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 727 |
+
)
|
| 728 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 729 |
+
|
| 730 |
+
if pixel_values is None:
|
| 731 |
+
raise ValueError("You have to specify pixel_values")
|
| 732 |
+
|
| 733 |
+
hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
| 734 |
+
|
| 735 |
+
encoder_outputs = self.encoder(
|
| 736 |
+
inputs_embeds=hidden_states,
|
| 737 |
+
output_attentions=output_attentions,
|
| 738 |
+
output_hidden_states=output_hidden_states,
|
| 739 |
+
return_dict=return_dict,
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
last_hidden_state = encoder_outputs[0]
|
| 743 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 744 |
+
|
| 745 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 746 |
+
pooled_output = self.post_layernorm(pooled_output)
|
| 747 |
+
|
| 748 |
+
if not return_dict:
|
| 749 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 750 |
+
|
| 751 |
+
return BaseModelOutputWithPooling(
|
| 752 |
+
last_hidden_state=last_hidden_state,
|
| 753 |
+
pooler_output=pooled_output,
|
| 754 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 755 |
+
attentions=encoder_outputs.attentions,
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
def get_input_embeddings(self):
|
| 759 |
+
return self.embeddings
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
@add_start_docstrings(
|
| 763 |
+
"""
|
| 764 |
+
This model is going to be deprecated in future versions. Please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase.
|
| 765 |
+
""",
|
| 766 |
+
BLIP_START_DOCSTRING,
|
| 767 |
+
)
|
| 768 |
+
class BlipModel(BlipPreTrainedModel):
|
| 769 |
+
config_class = BlipConfig
|
| 770 |
+
|
| 771 |
+
def __init__(self, config: BlipConfig):
|
| 772 |
+
super().__init__(config)
|
| 773 |
+
|
| 774 |
+
if not isinstance(config.text_config, BlipTextConfig):
|
| 775 |
+
raise TypeError(
|
| 776 |
+
"config.text_config is expected to be of type BlipTextConfig but is of type"
|
| 777 |
+
f" {type(config.text_config)}."
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
if not isinstance(config.vision_config, BlipVisionConfig):
|
| 781 |
+
raise TypeError(
|
| 782 |
+
"config.vision_config is expected to be of type BlipVisionConfig but is of type"
|
| 783 |
+
f" {type(config.vision_config)}."
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
text_config = config.text_config
|
| 787 |
+
vision_config = config.vision_config
|
| 788 |
+
|
| 789 |
+
self.projection_dim = config.projection_dim
|
| 790 |
+
self.text_embed_dim = text_config.hidden_size
|
| 791 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 792 |
+
|
| 793 |
+
self.text_model = BlipTextModel(text_config)
|
| 794 |
+
self.vision_model = BlipVisionModel(vision_config)
|
| 795 |
+
|
| 796 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
| 797 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
| 798 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
| 799 |
+
|
| 800 |
+
logger.warning(
|
| 801 |
+
"`BlipModel` is going to be deprecated in future release, please use `BlipForConditionalGeneration`, `BlipForQuestionAnswering` or `BlipForImageTextRetrieval` depending on your usecase."
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
# Initialize weights and apply final processing
|
| 805 |
+
self.post_init()
|
| 806 |
+
|
| 807 |
+
def get_input_embeddings(self):
|
| 808 |
+
return self.text_model.get_input_embeddings()
|
| 809 |
+
|
| 810 |
+
def set_input_embeddings(self, value):
|
| 811 |
+
self.text_model.set_input_embeddings(value)
|
| 812 |
+
|
| 813 |
+
@add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
|
| 814 |
+
def get_text_features(
|
| 815 |
+
self,
|
| 816 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 817 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 818 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 819 |
+
return_dict: Optional[bool] = None,
|
| 820 |
+
) -> torch.FloatTensor:
|
| 821 |
+
r"""
|
| 822 |
+
Returns:
|
| 823 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 824 |
+
applying the projection layer to the pooled output of [`BlipTextModel`].
|
| 825 |
+
|
| 826 |
+
Examples:
|
| 827 |
+
|
| 828 |
+
```python
|
| 829 |
+
>>> from transformers import AutoProcessor, BlipModel
|
| 830 |
+
|
| 831 |
+
>>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 832 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 833 |
+
|
| 834 |
+
>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 835 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 836 |
+
```"""
|
| 837 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 838 |
+
|
| 839 |
+
text_outputs = self.text_model(
|
| 840 |
+
input_ids=input_ids,
|
| 841 |
+
attention_mask=attention_mask,
|
| 842 |
+
position_ids=position_ids,
|
| 843 |
+
return_dict=return_dict,
|
| 844 |
+
)
|
| 845 |
+
|
| 846 |
+
pooled_output = text_outputs[1]
|
| 847 |
+
text_features = self.text_projection(pooled_output)
|
| 848 |
+
|
| 849 |
+
return text_features
|
| 850 |
+
|
| 851 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 852 |
+
def get_image_features(
|
| 853 |
+
self,
|
| 854 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 855 |
+
return_dict: Optional[bool] = None,
|
| 856 |
+
interpolate_pos_encoding: bool = False,
|
| 857 |
+
) -> torch.FloatTensor:
|
| 858 |
+
r"""
|
| 859 |
+
Returns:
|
| 860 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 861 |
+
applying the projection layer to the pooled output of [`BlipVisionModel`].
|
| 862 |
+
|
| 863 |
+
Examples:
|
| 864 |
+
|
| 865 |
+
```python
|
| 866 |
+
>>> from PIL import Image
|
| 867 |
+
>>> import requests
|
| 868 |
+
>>> from transformers import AutoProcessor, BlipModel
|
| 869 |
+
|
| 870 |
+
>>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 871 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 872 |
+
|
| 873 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 874 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 875 |
+
|
| 876 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 877 |
+
|
| 878 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 879 |
+
```"""
|
| 880 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 881 |
+
|
| 882 |
+
vision_outputs = self.vision_model(
|
| 883 |
+
pixel_values=pixel_values,
|
| 884 |
+
return_dict=return_dict,
|
| 885 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 889 |
+
image_features = self.visual_projection(pooled_output)
|
| 890 |
+
|
| 891 |
+
return image_features
|
| 892 |
+
|
| 893 |
+
@add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
|
| 894 |
+
def get_multimodal_features(
|
| 895 |
+
self,
|
| 896 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 897 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 898 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 899 |
+
return_dict: Optional[bool] = None,
|
| 900 |
+
interpolate_pos_encoding: bool = False,
|
| 901 |
+
) -> torch.FloatTensor:
|
| 902 |
+
r"""
|
| 903 |
+
Returns:
|
| 904 |
+
multimodal_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The multimodal embeddings
|
| 905 |
+
obtained by applying the image embeddings to the text encoder using the cross-attention mechanism.
|
| 906 |
+
|
| 907 |
+
Examples:
|
| 908 |
+
```python
|
| 909 |
+
>>> from PIL import Image
|
| 910 |
+
>>> import requests
|
| 911 |
+
>>> from transformers import AutoProcessor, BlipModel
|
| 912 |
+
|
| 913 |
+
>>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 914 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 915 |
+
|
| 916 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 917 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 918 |
+
>>> texts = ["a photo of a cat", "a photo of a dog"]
|
| 919 |
+
>>> inputs = processor(images=image, text=texts, padding=True, return_tensors="pt")
|
| 920 |
+
|
| 921 |
+
>>> multimodal_features = model.get_multimodal_features(**inputs)
|
| 922 |
+
```"""
|
| 923 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 924 |
+
vision_outputs = self.vision_model(
|
| 925 |
+
pixel_values=pixel_values,
|
| 926 |
+
output_attentions=True,
|
| 927 |
+
output_hidden_states=True,
|
| 928 |
+
return_dict=return_dict,
|
| 929 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 930 |
+
)
|
| 931 |
+
|
| 932 |
+
image_embeds = vision_outputs[0]
|
| 933 |
+
image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
|
| 934 |
+
|
| 935 |
+
text_outputs = self.text_model(
|
| 936 |
+
input_ids=input_ids,
|
| 937 |
+
attention_mask=attention_mask,
|
| 938 |
+
encoder_hidden_states=image_embeds,
|
| 939 |
+
encoder_attention_mask=image_atts,
|
| 940 |
+
return_dict=return_dict,
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
pooled_output = text_outputs[1] # pooled_output
|
| 944 |
+
multimodal_features = self.text_projection(pooled_output)
|
| 945 |
+
|
| 946 |
+
return multimodal_features
|
| 947 |
+
|
| 948 |
+
@add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
|
| 949 |
+
@replace_return_docstrings(output_type=BlipOutput, config_class=BlipConfig)
|
| 950 |
+
def forward(
|
| 951 |
+
self,
|
| 952 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 953 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 954 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 955 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 956 |
+
return_loss: Optional[bool] = None,
|
| 957 |
+
output_attentions: Optional[bool] = None,
|
| 958 |
+
output_hidden_states: Optional[bool] = None,
|
| 959 |
+
return_dict: Optional[bool] = None,
|
| 960 |
+
interpolate_pos_encoding: bool = False,
|
| 961 |
+
) -> Union[Tuple, BlipOutput]:
|
| 962 |
+
r"""
|
| 963 |
+
Returns:
|
| 964 |
+
|
| 965 |
+
Examples:
|
| 966 |
+
|
| 967 |
+
```python
|
| 968 |
+
>>> from PIL import Image
|
| 969 |
+
>>> import requests
|
| 970 |
+
>>> from transformers import AutoProcessor, BlipModel
|
| 971 |
+
|
| 972 |
+
>>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 973 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 974 |
+
|
| 975 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 976 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 977 |
+
|
| 978 |
+
>>> inputs = processor(
|
| 979 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
| 980 |
+
... )
|
| 981 |
+
|
| 982 |
+
>>> outputs = model(**inputs)
|
| 983 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 984 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 985 |
+
```"""
|
| 986 |
+
# Use BLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 987 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 988 |
+
output_hidden_states = (
|
| 989 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 990 |
+
)
|
| 991 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 992 |
+
|
| 993 |
+
vision_outputs = self.vision_model(
|
| 994 |
+
pixel_values=pixel_values,
|
| 995 |
+
output_attentions=output_attentions,
|
| 996 |
+
output_hidden_states=output_hidden_states,
|
| 997 |
+
return_dict=return_dict,
|
| 998 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 999 |
+
)
|
| 1000 |
+
|
| 1001 |
+
text_outputs = self.text_model(
|
| 1002 |
+
input_ids=input_ids,
|
| 1003 |
+
attention_mask=attention_mask,
|
| 1004 |
+
position_ids=position_ids,
|
| 1005 |
+
output_attentions=output_attentions,
|
| 1006 |
+
output_hidden_states=output_hidden_states,
|
| 1007 |
+
return_dict=return_dict,
|
| 1008 |
+
)
|
| 1009 |
+
|
| 1010 |
+
image_embeds = vision_outputs[1]
|
| 1011 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 1012 |
+
|
| 1013 |
+
text_embeds = text_outputs[1]
|
| 1014 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1015 |
+
|
| 1016 |
+
# normalized features
|
| 1017 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1018 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1019 |
+
|
| 1020 |
+
# cosine similarity as logits
|
| 1021 |
+
logit_scale = self.logit_scale.exp().to(device=text_embeds.device)
|
| 1022 |
+
image_embeds = image_embeds.to(device=text_embeds.device, dtype=text_embeds.dtype)
|
| 1023 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
| 1024 |
+
logits_per_image = logits_per_text.t()
|
| 1025 |
+
|
| 1026 |
+
loss = None
|
| 1027 |
+
if return_loss:
|
| 1028 |
+
loss = blip_loss(logits_per_text)
|
| 1029 |
+
|
| 1030 |
+
if not return_dict:
|
| 1031 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1032 |
+
return ((loss,) + output) if loss is not None else output
|
| 1033 |
+
|
| 1034 |
+
return BlipOutput(
|
| 1035 |
+
loss=loss,
|
| 1036 |
+
logits_per_image=logits_per_image,
|
| 1037 |
+
logits_per_text=logits_per_text,
|
| 1038 |
+
text_embeds=text_embeds,
|
| 1039 |
+
image_embeds=image_embeds,
|
| 1040 |
+
text_model_output=text_outputs,
|
| 1041 |
+
vision_model_output=vision_outputs,
|
| 1042 |
+
)
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
@add_start_docstrings(
|
| 1046 |
+
"""
|
| 1047 |
+
BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
|
| 1048 |
+
`input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
|
| 1049 |
+
the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
|
| 1050 |
+
from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
|
| 1051 |
+
""",
|
| 1052 |
+
BLIP_START_DOCSTRING,
|
| 1053 |
+
)
|
| 1054 |
+
class BlipForConditionalGeneration(BlipPreTrainedModel, GenerationMixin):
|
| 1055 |
+
config_class = BlipConfig
|
| 1056 |
+
_tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
|
| 1057 |
+
main_input_name = "pixel_values"
|
| 1058 |
+
|
| 1059 |
+
def __init__(self, config: BlipConfig):
|
| 1060 |
+
super().__init__(config)
|
| 1061 |
+
|
| 1062 |
+
self.vision_model = BlipVisionModel(config.vision_config)
|
| 1063 |
+
|
| 1064 |
+
self.text_decoder = BlipTextLMHeadModel(config.text_config)
|
| 1065 |
+
|
| 1066 |
+
self.decoder_input_ids = config.text_config.bos_token_id
|
| 1067 |
+
self.decoder_pad_token_id = config.text_config.pad_token_id
|
| 1068 |
+
|
| 1069 |
+
# Initialize weights and apply final processing
|
| 1070 |
+
self.post_init()
|
| 1071 |
+
|
| 1072 |
+
def get_input_embeddings(self):
|
| 1073 |
+
return self.text_decoder.get_input_embeddings()
|
| 1074 |
+
|
| 1075 |
+
def set_input_embeddings(self, value):
|
| 1076 |
+
self.text_decoder.set_input_embeddings(value)
|
| 1077 |
+
|
| 1078 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 1079 |
+
@replace_return_docstrings(output_type=BlipForConditionalGenerationModelOutput, config_class=BlipVisionConfig)
|
| 1080 |
+
def forward(
|
| 1081 |
+
self,
|
| 1082 |
+
pixel_values: torch.FloatTensor,
|
| 1083 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1084 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 1085 |
+
output_attentions: Optional[bool] = None,
|
| 1086 |
+
output_hidden_states: Optional[bool] = None,
|
| 1087 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1088 |
+
return_dict: Optional[bool] = None,
|
| 1089 |
+
interpolate_pos_encoding: bool = False,
|
| 1090 |
+
) -> Union[Tuple, BlipForConditionalGenerationModelOutput]:
|
| 1091 |
+
r"""
|
| 1092 |
+
Returns:
|
| 1093 |
+
|
| 1094 |
+
Examples:
|
| 1095 |
+
|
| 1096 |
+
```python
|
| 1097 |
+
>>> from PIL import Image
|
| 1098 |
+
>>> import requests
|
| 1099 |
+
>>> from transformers import AutoProcessor, BlipForConditionalGeneration
|
| 1100 |
+
|
| 1101 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1102 |
+
>>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1103 |
+
|
| 1104 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1105 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1106 |
+
>>> text = "A picture of"
|
| 1107 |
+
|
| 1108 |
+
>>> inputs = processor(images=image, text=text, return_tensors="pt")
|
| 1109 |
+
|
| 1110 |
+
>>> outputs = model(**inputs)
|
| 1111 |
+
```"""
|
| 1112 |
+
|
| 1113 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1114 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1115 |
+
output_hidden_states = (
|
| 1116 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
vision_outputs = self.vision_model(
|
| 1120 |
+
pixel_values=pixel_values,
|
| 1121 |
+
output_attentions=output_attentions,
|
| 1122 |
+
output_hidden_states=output_hidden_states,
|
| 1123 |
+
return_dict=return_dict,
|
| 1124 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1125 |
+
)
|
| 1126 |
+
|
| 1127 |
+
image_embeds = vision_outputs[0]
|
| 1128 |
+
|
| 1129 |
+
outputs = self.text_decoder(
|
| 1130 |
+
input_ids=input_ids,
|
| 1131 |
+
attention_mask=attention_mask,
|
| 1132 |
+
encoder_hidden_states=image_embeds,
|
| 1133 |
+
labels=labels,
|
| 1134 |
+
return_dict=return_dict,
|
| 1135 |
+
reduction="mean",
|
| 1136 |
+
)
|
| 1137 |
+
|
| 1138 |
+
if not return_dict:
|
| 1139 |
+
outputs = (outputs[0], outputs[1]) if labels is not None else (outputs[0],)
|
| 1140 |
+
outputs += (image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
| 1141 |
+
return tuple(output for output in outputs if output is not None)
|
| 1142 |
+
|
| 1143 |
+
return BlipForConditionalGenerationModelOutput(
|
| 1144 |
+
loss=outputs.loss,
|
| 1145 |
+
logits=outputs.logits,
|
| 1146 |
+
image_embeds=image_embeds,
|
| 1147 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1148 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1149 |
+
attentions=vision_outputs.attentions,
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
@torch.no_grad()
|
| 1153 |
+
def generate(
|
| 1154 |
+
self,
|
| 1155 |
+
pixel_values: torch.FloatTensor,
|
| 1156 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1157 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 1158 |
+
interpolate_pos_encoding: bool = False,
|
| 1159 |
+
**generate_kwargs,
|
| 1160 |
+
) -> torch.LongTensor:
|
| 1161 |
+
r"""
|
| 1162 |
+
Overrides *generate* function to be able to use the model as a conditional generator
|
| 1163 |
+
|
| 1164 |
+
Parameters:
|
| 1165 |
+
pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
|
| 1166 |
+
Input image to be processed
|
| 1167 |
+
input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
|
| 1168 |
+
The sequence used as a prompt for the generation.
|
| 1169 |
+
attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
|
| 1170 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
Examples:
|
| 1174 |
+
```python
|
| 1175 |
+
>>> from PIL import Image
|
| 1176 |
+
>>> import requests
|
| 1177 |
+
>>> from transformers import AutoProcessor, BlipForConditionalGeneration
|
| 1178 |
+
|
| 1179 |
+
>>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1180 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1181 |
+
|
| 1182 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1183 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1184 |
+
|
| 1185 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1186 |
+
|
| 1187 |
+
>>> outputs = model.generate(**inputs)
|
| 1188 |
+
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
|
| 1189 |
+
two cats sleeping on a couch
|
| 1190 |
+
```
|
| 1191 |
+
"""
|
| 1192 |
+
|
| 1193 |
+
batch_size = pixel_values.shape[0]
|
| 1194 |
+
vision_outputs = self.vision_model(
|
| 1195 |
+
pixel_values=pixel_values,
|
| 1196 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1197 |
+
)
|
| 1198 |
+
|
| 1199 |
+
image_embeds = vision_outputs[0]
|
| 1200 |
+
|
| 1201 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(image_embeds.device)
|
| 1202 |
+
|
| 1203 |
+
if isinstance(input_ids, list):
|
| 1204 |
+
input_ids = torch.LongTensor(input_ids)
|
| 1205 |
+
elif input_ids is None:
|
| 1206 |
+
input_ids = (
|
| 1207 |
+
torch.LongTensor([[self.decoder_input_ids, self.config.text_config.eos_token_id]])
|
| 1208 |
+
.repeat(batch_size, 1)
|
| 1209 |
+
.to(image_embeds.device)
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
input_ids[:, 0] = self.config.text_config.bos_token_id
|
| 1213 |
+
attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
|
| 1214 |
+
|
| 1215 |
+
outputs = self.text_decoder.generate(
|
| 1216 |
+
input_ids=input_ids[:, :-1],
|
| 1217 |
+
eos_token_id=self.config.text_config.sep_token_id,
|
| 1218 |
+
pad_token_id=self.config.text_config.pad_token_id,
|
| 1219 |
+
attention_mask=attention_mask,
|
| 1220 |
+
encoder_hidden_states=image_embeds,
|
| 1221 |
+
encoder_attention_mask=image_attention_mask,
|
| 1222 |
+
**generate_kwargs,
|
| 1223 |
+
)
|
| 1224 |
+
|
| 1225 |
+
return outputs
|
| 1226 |
+
|
| 1227 |
+
|
| 1228 |
+
@add_start_docstrings(
|
| 1229 |
+
"""
|
| 1230 |
+
BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
|
| 1231 |
+
decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
|
| 1232 |
+
with the encoding of the image, and the text decoder will output the answer to the question.
|
| 1233 |
+
""",
|
| 1234 |
+
BLIP_START_DOCSTRING,
|
| 1235 |
+
)
|
| 1236 |
+
class BlipForQuestionAnswering(BlipPreTrainedModel):
|
| 1237 |
+
config_class = BlipConfig
|
| 1238 |
+
_tied_weights_keys = ["text_decoder.cls.predictions.decoder.bias"]
|
| 1239 |
+
|
| 1240 |
+
def __init__(self, config: BlipConfig):
|
| 1241 |
+
super().__init__(config)
|
| 1242 |
+
|
| 1243 |
+
self.vision_model = BlipVisionModel(config.vision_config)
|
| 1244 |
+
|
| 1245 |
+
self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
|
| 1246 |
+
|
| 1247 |
+
self.text_decoder = BlipTextLMHeadModel(config.text_config)
|
| 1248 |
+
|
| 1249 |
+
self.decoder_pad_token_id = config.text_config.pad_token_id
|
| 1250 |
+
self.decoder_start_token_id = config.text_config.bos_token_id
|
| 1251 |
+
|
| 1252 |
+
# Initialize weights and apply final processing
|
| 1253 |
+
self.post_init()
|
| 1254 |
+
|
| 1255 |
+
def set_input_embeddings(self, value):
|
| 1256 |
+
self.text_encoder.set_input_embeddings(value)
|
| 1257 |
+
|
| 1258 |
+
def get_input_embeddings(self):
|
| 1259 |
+
# This will return shared embeddings if they are shared else specific to encoder.
|
| 1260 |
+
return self.text_encoder.get_input_embeddings()
|
| 1261 |
+
|
| 1262 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 1263 |
+
@replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
|
| 1264 |
+
def forward(
|
| 1265 |
+
self,
|
| 1266 |
+
input_ids: torch.LongTensor,
|
| 1267 |
+
pixel_values: torch.FloatTensor,
|
| 1268 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
| 1269 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
| 1270 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 1271 |
+
output_attentions: Optional[bool] = None,
|
| 1272 |
+
output_hidden_states: Optional[bool] = None,
|
| 1273 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1274 |
+
return_dict: Optional[bool] = None,
|
| 1275 |
+
interpolate_pos_encoding: bool = False,
|
| 1276 |
+
) -> Union[Tuple, BlipTextVisionModelOutput]:
|
| 1277 |
+
r"""
|
| 1278 |
+
Returns:
|
| 1279 |
+
|
| 1280 |
+
Examples:
|
| 1281 |
+
|
| 1282 |
+
```python
|
| 1283 |
+
>>> from PIL import Image
|
| 1284 |
+
>>> import requests
|
| 1285 |
+
>>> from transformers import AutoProcessor, BlipForQuestionAnswering
|
| 1286 |
+
|
| 1287 |
+
>>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
|
| 1288 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
| 1289 |
+
|
| 1290 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1291 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1292 |
+
|
| 1293 |
+
>>> # training
|
| 1294 |
+
>>> text = "How many cats are in the picture?"
|
| 1295 |
+
>>> label = "2"
|
| 1296 |
+
>>> inputs = processor(images=image, text=text, return_tensors="pt")
|
| 1297 |
+
>>> labels = processor(text=label, return_tensors="pt").input_ids
|
| 1298 |
+
|
| 1299 |
+
>>> inputs["labels"] = labels
|
| 1300 |
+
>>> outputs = model(**inputs)
|
| 1301 |
+
>>> loss = outputs.loss
|
| 1302 |
+
>>> loss.backward()
|
| 1303 |
+
|
| 1304 |
+
>>> # inference
|
| 1305 |
+
>>> text = "How many cats are in the picture?"
|
| 1306 |
+
>>> inputs = processor(images=image, text=text, return_tensors="pt")
|
| 1307 |
+
>>> outputs = model.generate(**inputs)
|
| 1308 |
+
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
|
| 1309 |
+
2
|
| 1310 |
+
```"""
|
| 1311 |
+
if labels is None and decoder_input_ids is None:
|
| 1312 |
+
raise ValueError(
|
| 1313 |
+
"Either `decoder_input_ids` or `labels` should be passed when calling `forward` with"
|
| 1314 |
+
" `BlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
|
| 1315 |
+
" are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
|
| 1316 |
+
)
|
| 1317 |
+
|
| 1318 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1319 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1320 |
+
output_hidden_states = (
|
| 1321 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1322 |
+
)
|
| 1323 |
+
|
| 1324 |
+
vision_outputs = self.vision_model(
|
| 1325 |
+
pixel_values=pixel_values,
|
| 1326 |
+
output_attentions=output_attentions,
|
| 1327 |
+
output_hidden_states=output_hidden_states,
|
| 1328 |
+
return_dict=return_dict,
|
| 1329 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1330 |
+
)
|
| 1331 |
+
|
| 1332 |
+
image_embeds = vision_outputs[0]
|
| 1333 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
|
| 1334 |
+
|
| 1335 |
+
question_embeds = self.text_encoder(
|
| 1336 |
+
input_ids=input_ids,
|
| 1337 |
+
attention_mask=attention_mask,
|
| 1338 |
+
encoder_hidden_states=image_embeds,
|
| 1339 |
+
encoder_attention_mask=image_attention_mask,
|
| 1340 |
+
return_dict=return_dict,
|
| 1341 |
+
)
|
| 1342 |
+
|
| 1343 |
+
if labels is not None and decoder_input_ids is None:
|
| 1344 |
+
# labels are already shifted right, see: https://github.com/huggingface/transformers/pull/23153
|
| 1345 |
+
decoder_input_ids = labels
|
| 1346 |
+
|
| 1347 |
+
question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
|
| 1348 |
+
|
| 1349 |
+
answer_output = self.text_decoder(
|
| 1350 |
+
input_ids=decoder_input_ids,
|
| 1351 |
+
attention_mask=decoder_attention_mask,
|
| 1352 |
+
encoder_hidden_states=question_embeds,
|
| 1353 |
+
encoder_attention_mask=attention_mask,
|
| 1354 |
+
labels=labels,
|
| 1355 |
+
return_dict=return_dict,
|
| 1356 |
+
reduction="mean",
|
| 1357 |
+
)
|
| 1358 |
+
|
| 1359 |
+
if labels is not None:
|
| 1360 |
+
decoder_loss = answer_output.loss.mean() if return_dict else answer_output[0].mean()
|
| 1361 |
+
else:
|
| 1362 |
+
decoder_loss = None
|
| 1363 |
+
|
| 1364 |
+
if not return_dict:
|
| 1365 |
+
outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
| 1366 |
+
return tuple(output for output in outputs if output is not None)
|
| 1367 |
+
|
| 1368 |
+
return BlipTextVisionModelOutput(
|
| 1369 |
+
loss=decoder_loss,
|
| 1370 |
+
image_embeds=image_embeds,
|
| 1371 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1372 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1373 |
+
attentions=vision_outputs.attentions,
|
| 1374 |
+
)
|
| 1375 |
+
|
| 1376 |
+
@torch.no_grad()
|
| 1377 |
+
def generate(
|
| 1378 |
+
self,
|
| 1379 |
+
input_ids: torch.LongTensor,
|
| 1380 |
+
pixel_values: torch.FloatTensor,
|
| 1381 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 1382 |
+
interpolate_pos_encoding: bool = False,
|
| 1383 |
+
**generate_kwargs,
|
| 1384 |
+
) -> torch.LongTensor:
|
| 1385 |
+
r"""
|
| 1386 |
+
Overrides *generate* function to be able to use the model as a conditional generator
|
| 1387 |
+
|
| 1388 |
+
Parameters:
|
| 1389 |
+
input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*):
|
| 1390 |
+
The sequence used as a prompt for the generation.
|
| 1391 |
+
pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
|
| 1392 |
+
Input image to be processed
|
| 1393 |
+
attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
|
| 1394 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
|
| 1395 |
+
tokens that are NOT MASKED, `0` for MASKED tokens.
|
| 1396 |
+
**generate_kwargs:
|
| 1397 |
+
Additional arguments passed to the *generate* function of the decoder
|
| 1398 |
+
|
| 1399 |
+
|
| 1400 |
+
Examples:
|
| 1401 |
+
```python
|
| 1402 |
+
>>> from PIL import Image
|
| 1403 |
+
>>> import requests
|
| 1404 |
+
>>> from transformers import AutoProcessor, BlipForQuestionAnswering
|
| 1405 |
+
|
| 1406 |
+
>>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
|
| 1407 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
| 1408 |
+
|
| 1409 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1410 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1411 |
+
>>> text = "How many cats are in the picture?"
|
| 1412 |
+
|
| 1413 |
+
>>> inputs = processor(images=image, text=text, return_tensors="pt")
|
| 1414 |
+
|
| 1415 |
+
>>> outputs = model.generate(**inputs)
|
| 1416 |
+
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
|
| 1417 |
+
2
|
| 1418 |
+
```
|
| 1419 |
+
"""
|
| 1420 |
+
vision_outputs = self.vision_model(
|
| 1421 |
+
pixel_values=pixel_values,
|
| 1422 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1423 |
+
)
|
| 1424 |
+
|
| 1425 |
+
image_embeds = vision_outputs[0]
|
| 1426 |
+
|
| 1427 |
+
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(image_embeds.device)
|
| 1428 |
+
|
| 1429 |
+
if isinstance(input_ids, list):
|
| 1430 |
+
input_ids = torch.LongTensor(input_ids)
|
| 1431 |
+
|
| 1432 |
+
question_outputs = self.text_encoder(
|
| 1433 |
+
input_ids=input_ids,
|
| 1434 |
+
attention_mask=attention_mask,
|
| 1435 |
+
encoder_hidden_states=image_embeds,
|
| 1436 |
+
encoder_attention_mask=image_attention_mask,
|
| 1437 |
+
return_dict=False,
|
| 1438 |
+
)
|
| 1439 |
+
|
| 1440 |
+
question_embeds = question_outputs[0]
|
| 1441 |
+
|
| 1442 |
+
question_attention_mask = torch.ones(question_embeds.size()[:-1], dtype=torch.long).to(question_embeds.device)
|
| 1443 |
+
|
| 1444 |
+
bos_ids = torch.full(
|
| 1445 |
+
(question_embeds.size(0), 1), fill_value=self.decoder_start_token_id, device=question_embeds.device
|
| 1446 |
+
)
|
| 1447 |
+
|
| 1448 |
+
outputs = self.text_decoder.generate(
|
| 1449 |
+
input_ids=bos_ids,
|
| 1450 |
+
eos_token_id=self.config.text_config.sep_token_id,
|
| 1451 |
+
pad_token_id=self.config.text_config.pad_token_id,
|
| 1452 |
+
encoder_hidden_states=question_embeds,
|
| 1453 |
+
encoder_attention_mask=question_attention_mask,
|
| 1454 |
+
**generate_kwargs,
|
| 1455 |
+
)
|
| 1456 |
+
|
| 1457 |
+
return outputs
|
| 1458 |
+
|
| 1459 |
+
|
| 1460 |
+
@add_start_docstrings(
|
| 1461 |
+
"""
|
| 1462 |
+
BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
|
| 1463 |
+
image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
|
| 1464 |
+
the image.
|
| 1465 |
+
""",
|
| 1466 |
+
BLIP_START_DOCSTRING,
|
| 1467 |
+
)
|
| 1468 |
+
class BlipForImageTextRetrieval(BlipPreTrainedModel):
|
| 1469 |
+
config_class = BlipConfig
|
| 1470 |
+
|
| 1471 |
+
def __init__(self, config: BlipConfig):
|
| 1472 |
+
super().__init__(config)
|
| 1473 |
+
|
| 1474 |
+
self.vision_model = BlipVisionModel(config.vision_config)
|
| 1475 |
+
|
| 1476 |
+
self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
|
| 1477 |
+
|
| 1478 |
+
# vision projection layer
|
| 1479 |
+
self.vision_proj = nn.Linear(config.vision_config.hidden_size, config.image_text_hidden_size)
|
| 1480 |
+
|
| 1481 |
+
# text projection layer
|
| 1482 |
+
self.text_proj = nn.Linear(config.text_config.hidden_size, config.image_text_hidden_size)
|
| 1483 |
+
|
| 1484 |
+
# image text matching head
|
| 1485 |
+
self.itm_head = nn.Linear(config.text_config.hidden_size, 2)
|
| 1486 |
+
|
| 1487 |
+
self.decoder_pad_token_id = (
|
| 1488 |
+
config.text_config.pad_token_id
|
| 1489 |
+
if not hasattr(config, "decoder_pad_token_id")
|
| 1490 |
+
else config.decoder_pad_token_id
|
| 1491 |
+
)
|
| 1492 |
+
self.decoder_start_token_id = (
|
| 1493 |
+
config.text_config.bos_token_id
|
| 1494 |
+
if not hasattr(config, "decoder_start_token_id")
|
| 1495 |
+
else config.decoder_start_token_id
|
| 1496 |
+
)
|
| 1497 |
+
|
| 1498 |
+
# Initialize weights and apply final processing
|
| 1499 |
+
self.post_init()
|
| 1500 |
+
|
| 1501 |
+
def get_input_embeddings(self):
|
| 1502 |
+
return self.text_encoder.get_input_embeddings()
|
| 1503 |
+
|
| 1504 |
+
def set_input_embeddings(self, value):
|
| 1505 |
+
self.text_encoder.set_input_embeddings(value)
|
| 1506 |
+
|
| 1507 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 1508 |
+
@replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
|
| 1509 |
+
def forward(
|
| 1510 |
+
self,
|
| 1511 |
+
input_ids: torch.LongTensor,
|
| 1512 |
+
pixel_values: torch.FloatTensor,
|
| 1513 |
+
use_itm_head: Optional[bool] = True,
|
| 1514 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 1515 |
+
output_attentions: Optional[bool] = None,
|
| 1516 |
+
output_hidden_states: Optional[bool] = None,
|
| 1517 |
+
return_dict: Optional[bool] = None,
|
| 1518 |
+
interpolate_pos_encoding: bool = False,
|
| 1519 |
+
) -> Union[Tuple, BlipTextVisionModelOutput]:
|
| 1520 |
+
r"""
|
| 1521 |
+
Returns:
|
| 1522 |
+
|
| 1523 |
+
Examples:
|
| 1524 |
+
|
| 1525 |
+
```python
|
| 1526 |
+
>>> from PIL import Image
|
| 1527 |
+
>>> import requests
|
| 1528 |
+
>>> from transformers import AutoProcessor, BlipForImageTextRetrieval
|
| 1529 |
+
|
| 1530 |
+
>>> model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
|
| 1531 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
|
| 1532 |
+
|
| 1533 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1534 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1535 |
+
>>> text = "an image of a cat"
|
| 1536 |
+
|
| 1537 |
+
>>> inputs = processor(images=image, text=text, return_tensors="pt")
|
| 1538 |
+
>>> outputs = model(**inputs)
|
| 1539 |
+
```
|
| 1540 |
+
"""
|
| 1541 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1542 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1543 |
+
output_hidden_states = (
|
| 1544 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1545 |
+
)
|
| 1546 |
+
|
| 1547 |
+
vision_outputs = self.vision_model(
|
| 1548 |
+
pixel_values=pixel_values,
|
| 1549 |
+
output_attentions=output_attentions,
|
| 1550 |
+
output_hidden_states=output_hidden_states,
|
| 1551 |
+
return_dict=return_dict,
|
| 1552 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1553 |
+
)
|
| 1554 |
+
|
| 1555 |
+
image_embeds = vision_outputs[0]
|
| 1556 |
+
image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
|
| 1557 |
+
|
| 1558 |
+
if use_itm_head:
|
| 1559 |
+
question_embeds = self.text_encoder(
|
| 1560 |
+
input_ids=input_ids,
|
| 1561 |
+
attention_mask=attention_mask,
|
| 1562 |
+
encoder_hidden_states=image_embeds,
|
| 1563 |
+
encoder_attention_mask=image_atts,
|
| 1564 |
+
return_dict=return_dict,
|
| 1565 |
+
)
|
| 1566 |
+
question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
|
| 1567 |
+
|
| 1568 |
+
output = self.itm_head(question_embeds[:, 0, :])
|
| 1569 |
+
else:
|
| 1570 |
+
question_embeds = self.text_encoder(
|
| 1571 |
+
input_ids=input_ids,
|
| 1572 |
+
attention_mask=attention_mask,
|
| 1573 |
+
return_dict=return_dict,
|
| 1574 |
+
)
|
| 1575 |
+
question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
|
| 1576 |
+
|
| 1577 |
+
image_feat = normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1)
|
| 1578 |
+
text_feat = normalize(self.text_proj(question_embeds[:, 0, :]), dim=-1)
|
| 1579 |
+
|
| 1580 |
+
output = image_feat @ text_feat.t()
|
| 1581 |
+
|
| 1582 |
+
if not return_dict:
|
| 1583 |
+
outputs = (output, vision_outputs[0]) + vision_outputs[2:] + (question_embeds,)
|
| 1584 |
+
return tuple(output for output in outputs if output is not None)
|
| 1585 |
+
|
| 1586 |
+
return BlipImageTextMatchingModelOutput(
|
| 1587 |
+
itm_score=output,
|
| 1588 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1589 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1590 |
+
attentions=vision_outputs.attentions,
|
| 1591 |
+
question_embeds=question_embeds,
|
| 1592 |
+
)
|
| 1593 |
+
|
| 1594 |
+
|
| 1595 |
+
__all__ = [
|
| 1596 |
+
"BlipModel",
|
| 1597 |
+
"BlipPreTrainedModel",
|
| 1598 |
+
"BlipForConditionalGeneration",
|
| 1599 |
+
"BlipForQuestionAnswering",
|
| 1600 |
+
"BlipVisionModel",
|
| 1601 |
+
"BlipTextModel",
|
| 1602 |
+
"BlipForImageTextRetrieval",
|
| 1603 |
+
]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_blip_text.py
ADDED
|
@@ -0,0 +1,958 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the BSD-3-clause license (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 |
+
# https://opensource.org/licenses/BSD-3-Clause
|
| 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 |
+
import math
|
| 18 |
+
from typing import List, Optional, Tuple, Union
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.utils.checkpoint
|
| 22 |
+
from torch import Tensor, device, nn
|
| 23 |
+
from torch.nn import CrossEntropyLoss
|
| 24 |
+
|
| 25 |
+
from ...activations import ACT2FN
|
| 26 |
+
from ...generation import GenerationMixin
|
| 27 |
+
from ...modeling_outputs import (
|
| 28 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 29 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
| 30 |
+
CausalLMOutputWithCrossAttentions,
|
| 31 |
+
)
|
| 32 |
+
from ...modeling_utils import (
|
| 33 |
+
PreTrainedModel,
|
| 34 |
+
apply_chunking_to_forward,
|
| 35 |
+
find_pruneable_heads_and_indices,
|
| 36 |
+
prune_linear_layer,
|
| 37 |
+
)
|
| 38 |
+
from ...utils import logging
|
| 39 |
+
from .configuration_blip import BlipTextConfig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
|
| 46 |
+
class BlipTextEmbeddings(nn.Module):
|
| 47 |
+
"""Construct the embeddings from word and position embeddings."""
|
| 48 |
+
|
| 49 |
+
def __init__(self, config):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 52 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 53 |
+
|
| 54 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
| 55 |
+
# any TensorFlow checkpoint file
|
| 56 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 57 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 58 |
+
|
| 59 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 60 |
+
self.register_buffer(
|
| 61 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 62 |
+
)
|
| 63 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 64 |
+
|
| 65 |
+
self.config = config
|
| 66 |
+
|
| 67 |
+
def forward(
|
| 68 |
+
self,
|
| 69 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 70 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 71 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 72 |
+
past_key_values_length: int = 0,
|
| 73 |
+
) -> torch.Tensor:
|
| 74 |
+
if input_ids is not None:
|
| 75 |
+
input_shape = input_ids.size()
|
| 76 |
+
else:
|
| 77 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 78 |
+
|
| 79 |
+
seq_length = input_shape[1]
|
| 80 |
+
|
| 81 |
+
if position_ids is None:
|
| 82 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 83 |
+
|
| 84 |
+
if inputs_embeds is None:
|
| 85 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 86 |
+
|
| 87 |
+
embeddings = inputs_embeds
|
| 88 |
+
|
| 89 |
+
if self.position_embedding_type == "absolute":
|
| 90 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 91 |
+
embeddings += position_embeddings
|
| 92 |
+
embeddings = self.LayerNorm(embeddings)
|
| 93 |
+
embeddings = self.dropout(embeddings)
|
| 94 |
+
return embeddings
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
|
| 98 |
+
class BlipTextSelfAttention(nn.Module):
|
| 99 |
+
def __init__(self, config, is_cross_attention):
|
| 100 |
+
super().__init__()
|
| 101 |
+
self.config = config
|
| 102 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 103 |
+
raise ValueError(
|
| 104 |
+
"The hidden size (%d) is not a multiple of the number of attention heads (%d)"
|
| 105 |
+
% (config.hidden_size, config.num_attention_heads)
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
self.num_attention_heads = config.num_attention_heads
|
| 109 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 110 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 111 |
+
|
| 112 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 113 |
+
if is_cross_attention:
|
| 114 |
+
self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
|
| 115 |
+
self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
|
| 116 |
+
else:
|
| 117 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 118 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 119 |
+
|
| 120 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 121 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 122 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 123 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 124 |
+
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
|
| 125 |
+
|
| 126 |
+
def save_attn_gradients(self, attn_gradients):
|
| 127 |
+
self.attn_gradients = attn_gradients
|
| 128 |
+
|
| 129 |
+
def get_attn_gradients(self):
|
| 130 |
+
return self.attn_gradients
|
| 131 |
+
|
| 132 |
+
def save_attention_map(self, attention_map):
|
| 133 |
+
self.attention_map = attention_map
|
| 134 |
+
|
| 135 |
+
def get_attention_map(self):
|
| 136 |
+
return self.attention_map
|
| 137 |
+
|
| 138 |
+
def transpose_for_scores(self, x):
|
| 139 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 140 |
+
x = x.view(*new_x_shape)
|
| 141 |
+
return x.permute(0, 2, 1, 3)
|
| 142 |
+
|
| 143 |
+
def forward(
|
| 144 |
+
self,
|
| 145 |
+
hidden_states: torch.Tensor,
|
| 146 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 147 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 148 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 149 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 150 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 151 |
+
output_attentions: Optional[bool] = False,
|
| 152 |
+
) -> Tuple[torch.Tensor]:
|
| 153 |
+
mixed_query_layer = self.query(hidden_states)
|
| 154 |
+
|
| 155 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 156 |
+
# and values come from an encoder; the attention mask needs to be
|
| 157 |
+
# such that the encoder's padding tokens are not attended to.
|
| 158 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 159 |
+
|
| 160 |
+
if is_cross_attention:
|
| 161 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 162 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 163 |
+
attention_mask = encoder_attention_mask
|
| 164 |
+
elif past_key_value is not None:
|
| 165 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 166 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 167 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 168 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 169 |
+
else:
|
| 170 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 171 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 172 |
+
|
| 173 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 174 |
+
|
| 175 |
+
past_key_value = (key_layer, value_layer)
|
| 176 |
+
|
| 177 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 178 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 179 |
+
|
| 180 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 181 |
+
seq_length = hidden_states.size()[1]
|
| 182 |
+
position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
|
| 183 |
+
position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
|
| 184 |
+
distance = position_ids_l - position_ids_r
|
| 185 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 186 |
+
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
|
| 187 |
+
|
| 188 |
+
if self.position_embedding_type == "relative_key":
|
| 189 |
+
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 190 |
+
attention_scores = attention_scores + relative_position_scores
|
| 191 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 192 |
+
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 193 |
+
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 194 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 195 |
+
|
| 196 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 197 |
+
if attention_mask is not None:
|
| 198 |
+
# Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
|
| 199 |
+
attention_scores = attention_scores + attention_mask.to(attention_scores.device)
|
| 200 |
+
|
| 201 |
+
# Normalize the attention scores to probabilities.
|
| 202 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 203 |
+
|
| 204 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 205 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 206 |
+
attention_probs_dropped = self.dropout(attention_probs)
|
| 207 |
+
|
| 208 |
+
# Mask heads if we want to
|
| 209 |
+
if head_mask is not None:
|
| 210 |
+
attention_probs_dropped = attention_probs_dropped * head_mask
|
| 211 |
+
|
| 212 |
+
context_layer = torch.matmul(attention_probs_dropped, value_layer)
|
| 213 |
+
|
| 214 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 215 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 216 |
+
context_layer = context_layer.view(*new_context_layer_shape)
|
| 217 |
+
|
| 218 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 219 |
+
|
| 220 |
+
outputs = outputs + (past_key_value,)
|
| 221 |
+
return outputs
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert -> BlipText
|
| 225 |
+
class BlipTextSelfOutput(nn.Module):
|
| 226 |
+
def __init__(self, config):
|
| 227 |
+
super().__init__()
|
| 228 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 229 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 230 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 231 |
+
|
| 232 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 233 |
+
hidden_states = self.dense(hidden_states)
|
| 234 |
+
hidden_states = self.dropout(hidden_states)
|
| 235 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 236 |
+
return hidden_states
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
|
| 240 |
+
class BlipTextAttention(nn.Module):
|
| 241 |
+
def __init__(self, config, is_cross_attention=False):
|
| 242 |
+
super().__init__()
|
| 243 |
+
self.self = BlipTextSelfAttention(config, is_cross_attention)
|
| 244 |
+
self.output = BlipTextSelfOutput(config)
|
| 245 |
+
self.pruned_heads = set()
|
| 246 |
+
|
| 247 |
+
def prune_heads(self, heads):
|
| 248 |
+
if len(heads) == 0:
|
| 249 |
+
return
|
| 250 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 251 |
+
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# Prune linear layers
|
| 255 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
| 256 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
| 257 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
| 258 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 259 |
+
|
| 260 |
+
# Update hyper params and store pruned heads
|
| 261 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
| 262 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
| 263 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 264 |
+
|
| 265 |
+
def forward(
|
| 266 |
+
self,
|
| 267 |
+
hidden_states: torch.Tensor,
|
| 268 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 269 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 270 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 271 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 272 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 273 |
+
output_attentions: Optional[bool] = False,
|
| 274 |
+
) -> Tuple[torch.Tensor]:
|
| 275 |
+
self_outputs = self.self(
|
| 276 |
+
hidden_states,
|
| 277 |
+
attention_mask,
|
| 278 |
+
head_mask,
|
| 279 |
+
encoder_hidden_states,
|
| 280 |
+
encoder_attention_mask,
|
| 281 |
+
past_key_value,
|
| 282 |
+
output_attentions,
|
| 283 |
+
)
|
| 284 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 285 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 286 |
+
return outputs
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert -> BlipText
|
| 290 |
+
class BlipTextIntermediate(nn.Module):
|
| 291 |
+
def __init__(self, config):
|
| 292 |
+
super().__init__()
|
| 293 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 294 |
+
if isinstance(config.hidden_act, str):
|
| 295 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 296 |
+
else:
|
| 297 |
+
self.intermediate_act_fn = config.hidden_act
|
| 298 |
+
|
| 299 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 300 |
+
hidden_states = self.dense(hidden_states)
|
| 301 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 302 |
+
return hidden_states
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert -> BlipText
|
| 306 |
+
class BlipTextOutput(nn.Module):
|
| 307 |
+
def __init__(self, config):
|
| 308 |
+
super().__init__()
|
| 309 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 310 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 311 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 312 |
+
|
| 313 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 314 |
+
hidden_states = self.dense(hidden_states)
|
| 315 |
+
hidden_states = self.dropout(hidden_states)
|
| 316 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
| 317 |
+
return hidden_states
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class BlipTextLayer(nn.Module):
|
| 321 |
+
def __init__(self, config, layer_num):
|
| 322 |
+
super().__init__()
|
| 323 |
+
self.config = config
|
| 324 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
| 325 |
+
self.seq_len_dim = 1
|
| 326 |
+
self.attention = BlipTextAttention(config)
|
| 327 |
+
self.layer_num = layer_num
|
| 328 |
+
if self.config.is_decoder:
|
| 329 |
+
self.crossattention = BlipTextAttention(config, is_cross_attention=self.config.is_decoder)
|
| 330 |
+
self.intermediate = BlipTextIntermediate(config)
|
| 331 |
+
self.output = BlipTextOutput(config)
|
| 332 |
+
|
| 333 |
+
def forward(
|
| 334 |
+
self,
|
| 335 |
+
hidden_states: torch.Tensor,
|
| 336 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 337 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 338 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 339 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 340 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 341 |
+
output_attentions: Optional[bool] = False,
|
| 342 |
+
) -> Tuple[torch.Tensor]:
|
| 343 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 344 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 345 |
+
self_attention_outputs = self.attention(
|
| 346 |
+
hidden_states,
|
| 347 |
+
attention_mask,
|
| 348 |
+
head_mask,
|
| 349 |
+
output_attentions=output_attentions,
|
| 350 |
+
past_key_value=self_attn_past_key_value,
|
| 351 |
+
)
|
| 352 |
+
attention_output = self_attention_outputs[0]
|
| 353 |
+
|
| 354 |
+
outputs = self_attention_outputs[1:-1]
|
| 355 |
+
present_key_value = self_attention_outputs[-1]
|
| 356 |
+
|
| 357 |
+
if encoder_hidden_states is not None:
|
| 358 |
+
cross_attention_outputs = self.crossattention(
|
| 359 |
+
attention_output,
|
| 360 |
+
attention_mask,
|
| 361 |
+
head_mask,
|
| 362 |
+
encoder_hidden_states,
|
| 363 |
+
encoder_attention_mask,
|
| 364 |
+
output_attentions=output_attentions,
|
| 365 |
+
)
|
| 366 |
+
attention_output = cross_attention_outputs[0]
|
| 367 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 368 |
+
layer_output = apply_chunking_to_forward(
|
| 369 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
| 370 |
+
)
|
| 371 |
+
outputs = (layer_output,) + outputs
|
| 372 |
+
|
| 373 |
+
outputs = outputs + (present_key_value,)
|
| 374 |
+
|
| 375 |
+
return outputs
|
| 376 |
+
|
| 377 |
+
def feed_forward_chunk(self, attention_output):
|
| 378 |
+
intermediate_output = self.intermediate(attention_output)
|
| 379 |
+
layer_output = self.output(intermediate_output, attention_output)
|
| 380 |
+
return layer_output
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
|
| 384 |
+
class BlipTextEncoder(nn.Module):
|
| 385 |
+
def __init__(self, config):
|
| 386 |
+
super().__init__()
|
| 387 |
+
self.config = config
|
| 388 |
+
self.layer = nn.ModuleList([BlipTextLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 389 |
+
self.gradient_checkpointing = False
|
| 390 |
+
|
| 391 |
+
def forward(
|
| 392 |
+
self,
|
| 393 |
+
hidden_states: torch.Tensor,
|
| 394 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 395 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 396 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 397 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 398 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 399 |
+
use_cache: Optional[bool] = None,
|
| 400 |
+
output_attentions: Optional[bool] = False,
|
| 401 |
+
output_hidden_states: Optional[bool] = False,
|
| 402 |
+
return_dict: Optional[bool] = True,
|
| 403 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 404 |
+
if self.gradient_checkpointing and self.training:
|
| 405 |
+
if use_cache:
|
| 406 |
+
logger.warning(
|
| 407 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 408 |
+
)
|
| 409 |
+
use_cache = False
|
| 410 |
+
all_hidden_states = () if output_hidden_states else None
|
| 411 |
+
all_self_attentions = () if output_attentions else None
|
| 412 |
+
all_cross_attentions = () if output_attentions and self.config.is_decoder else None
|
| 413 |
+
|
| 414 |
+
next_decoder_cache = () if use_cache else None
|
| 415 |
+
|
| 416 |
+
for i in range(self.config.num_hidden_layers):
|
| 417 |
+
layer_module = self.layer[i]
|
| 418 |
+
if output_hidden_states:
|
| 419 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 420 |
+
|
| 421 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 422 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 423 |
+
|
| 424 |
+
if self.gradient_checkpointing and self.training:
|
| 425 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 426 |
+
layer_module.__call__,
|
| 427 |
+
hidden_states,
|
| 428 |
+
attention_mask,
|
| 429 |
+
layer_head_mask,
|
| 430 |
+
encoder_hidden_states,
|
| 431 |
+
encoder_attention_mask,
|
| 432 |
+
past_key_value,
|
| 433 |
+
output_attentions,
|
| 434 |
+
)
|
| 435 |
+
else:
|
| 436 |
+
layer_outputs = layer_module(
|
| 437 |
+
hidden_states,
|
| 438 |
+
attention_mask,
|
| 439 |
+
layer_head_mask,
|
| 440 |
+
encoder_hidden_states,
|
| 441 |
+
encoder_attention_mask,
|
| 442 |
+
past_key_value,
|
| 443 |
+
output_attentions,
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
hidden_states = layer_outputs[0]
|
| 447 |
+
if use_cache:
|
| 448 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 449 |
+
if output_attentions:
|
| 450 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 451 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 452 |
+
|
| 453 |
+
if output_hidden_states:
|
| 454 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 455 |
+
|
| 456 |
+
if not return_dict:
|
| 457 |
+
return tuple(
|
| 458 |
+
v
|
| 459 |
+
for v in [
|
| 460 |
+
hidden_states,
|
| 461 |
+
next_decoder_cache,
|
| 462 |
+
all_hidden_states,
|
| 463 |
+
all_self_attentions,
|
| 464 |
+
all_cross_attentions,
|
| 465 |
+
]
|
| 466 |
+
if v is not None
|
| 467 |
+
)
|
| 468 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 469 |
+
last_hidden_state=hidden_states,
|
| 470 |
+
past_key_values=next_decoder_cache,
|
| 471 |
+
hidden_states=all_hidden_states,
|
| 472 |
+
attentions=all_self_attentions,
|
| 473 |
+
cross_attentions=all_cross_attentions,
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->BlipText
|
| 478 |
+
class BlipTextPooler(nn.Module):
|
| 479 |
+
def __init__(self, config):
|
| 480 |
+
super().__init__()
|
| 481 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 482 |
+
self.activation = nn.Tanh()
|
| 483 |
+
|
| 484 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 485 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 486 |
+
# to the first token.
|
| 487 |
+
first_token_tensor = hidden_states[:, 0]
|
| 488 |
+
pooled_output = self.dense(first_token_tensor)
|
| 489 |
+
pooled_output = self.activation(pooled_output)
|
| 490 |
+
return pooled_output
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->BlipText
|
| 494 |
+
class BlipTextPredictionHeadTransform(nn.Module):
|
| 495 |
+
def __init__(self, config):
|
| 496 |
+
super().__init__()
|
| 497 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 498 |
+
if isinstance(config.hidden_act, str):
|
| 499 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
| 500 |
+
else:
|
| 501 |
+
self.transform_act_fn = config.hidden_act
|
| 502 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 503 |
+
|
| 504 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 505 |
+
hidden_states = self.dense(hidden_states)
|
| 506 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 507 |
+
hidden_states = self.LayerNorm(hidden_states)
|
| 508 |
+
return hidden_states
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->BlipText
|
| 512 |
+
class BlipTextLMPredictionHead(nn.Module):
|
| 513 |
+
def __init__(self, config):
|
| 514 |
+
super().__init__()
|
| 515 |
+
self.transform = BlipTextPredictionHeadTransform(config)
|
| 516 |
+
|
| 517 |
+
# The output weights are the same as the input embeddings, but there is
|
| 518 |
+
# an output-only bias for each token.
|
| 519 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 520 |
+
|
| 521 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 522 |
+
|
| 523 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
| 524 |
+
self.decoder.bias = self.bias
|
| 525 |
+
|
| 526 |
+
def _tie_weights(self):
|
| 527 |
+
self.decoder.bias = self.bias
|
| 528 |
+
|
| 529 |
+
def forward(self, hidden_states):
|
| 530 |
+
hidden_states = self.transform(hidden_states)
|
| 531 |
+
hidden_states = self.decoder(hidden_states)
|
| 532 |
+
return hidden_states
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->BlipText
|
| 536 |
+
class BlipTextOnlyMLMHead(nn.Module):
|
| 537 |
+
def __init__(self, config):
|
| 538 |
+
super().__init__()
|
| 539 |
+
self.predictions = BlipTextLMPredictionHead(config)
|
| 540 |
+
|
| 541 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
| 542 |
+
prediction_scores = self.predictions(sequence_output)
|
| 543 |
+
return prediction_scores
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
|
| 547 |
+
class BlipTextPreTrainedModel(PreTrainedModel):
|
| 548 |
+
"""
|
| 549 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 550 |
+
models.
|
| 551 |
+
"""
|
| 552 |
+
|
| 553 |
+
config_class = BlipTextConfig
|
| 554 |
+
base_model_prefix = "bert"
|
| 555 |
+
_no_split_modules = []
|
| 556 |
+
|
| 557 |
+
def _init_weights(self, module):
|
| 558 |
+
"""Initialize the weights"""
|
| 559 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 560 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
| 561 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
| 562 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 563 |
+
elif isinstance(module, nn.LayerNorm):
|
| 564 |
+
module.bias.data.zero_()
|
| 565 |
+
module.weight.data.fill_(1.0)
|
| 566 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 567 |
+
module.bias.data.zero_()
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
|
| 571 |
+
class BlipTextModel(BlipTextPreTrainedModel):
|
| 572 |
+
"""
|
| 573 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 574 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 575 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 576 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
|
| 577 |
+
`encoder_hidden_states` is then expected as an input to the forward pass.
|
| 578 |
+
"""
|
| 579 |
+
|
| 580 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 581 |
+
super().__init__(config)
|
| 582 |
+
self.config = config
|
| 583 |
+
|
| 584 |
+
self.embeddings = BlipTextEmbeddings(config)
|
| 585 |
+
self.encoder = BlipTextEncoder(config)
|
| 586 |
+
self.pooler = BlipTextPooler(config) if add_pooling_layer else None
|
| 587 |
+
|
| 588 |
+
self.post_init()
|
| 589 |
+
|
| 590 |
+
def get_input_embeddings(self):
|
| 591 |
+
return self.embeddings.word_embeddings
|
| 592 |
+
|
| 593 |
+
def set_input_embeddings(self, value):
|
| 594 |
+
self.embeddings.word_embeddings = value
|
| 595 |
+
|
| 596 |
+
# Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
|
| 597 |
+
def _prune_heads(self, heads_to_prune):
|
| 598 |
+
"""
|
| 599 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 600 |
+
class PreTrainedModel
|
| 601 |
+
"""
|
| 602 |
+
for layer, heads in heads_to_prune.items():
|
| 603 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 604 |
+
|
| 605 |
+
def get_extended_attention_mask(
|
| 606 |
+
self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool
|
| 607 |
+
) -> Tensor:
|
| 608 |
+
"""
|
| 609 |
+
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
|
| 610 |
+
|
| 611 |
+
Arguments:
|
| 612 |
+
attention_mask (`torch.Tensor`):
|
| 613 |
+
Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
|
| 614 |
+
input_shape (`Tuple[int]`):
|
| 615 |
+
The shape of the input to the model.
|
| 616 |
+
device (`torch.device`):
|
| 617 |
+
The device of the input to the model.
|
| 618 |
+
|
| 619 |
+
Returns:
|
| 620 |
+
`torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
|
| 621 |
+
"""
|
| 622 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 623 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 624 |
+
if attention_mask.dim() == 3:
|
| 625 |
+
extended_attention_mask = attention_mask[:, None, :, :]
|
| 626 |
+
elif attention_mask.dim() == 2:
|
| 627 |
+
# Provided a padding mask of dimensions [batch_size, seq_length]
|
| 628 |
+
# - if the model is a decoder, apply a causal mask in addition to the padding mask
|
| 629 |
+
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 630 |
+
if is_decoder:
|
| 631 |
+
batch_size, seq_length = input_shape
|
| 632 |
+
|
| 633 |
+
seq_ids = torch.arange(seq_length, device=device)
|
| 634 |
+
causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
|
| 635 |
+
# in case past_key_values are used we need to add a prefix ones mask to the causal mask
|
| 636 |
+
# causal and attention masks must have same type with pytorch version < 1.3
|
| 637 |
+
causal_mask = causal_mask.to(attention_mask.dtype)
|
| 638 |
+
|
| 639 |
+
if causal_mask.shape[1] < attention_mask.shape[1]:
|
| 640 |
+
prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
|
| 641 |
+
causal_mask = torch.cat(
|
| 642 |
+
[
|
| 643 |
+
torch.ones(
|
| 644 |
+
(batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype
|
| 645 |
+
),
|
| 646 |
+
causal_mask,
|
| 647 |
+
],
|
| 648 |
+
axis=-1,
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
|
| 652 |
+
else:
|
| 653 |
+
extended_attention_mask = attention_mask[:, None, None, :]
|
| 654 |
+
else:
|
| 655 |
+
raise ValueError(
|
| 656 |
+
"Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
|
| 657 |
+
input_shape, attention_mask.shape
|
| 658 |
+
)
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 662 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 663 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 664 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 665 |
+
# effectively the same as removing these entirely.
|
| 666 |
+
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
| 667 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
| 668 |
+
return extended_attention_mask
|
| 669 |
+
|
| 670 |
+
def forward(
|
| 671 |
+
self,
|
| 672 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 673 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 674 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 675 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 676 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 677 |
+
encoder_embeds: Optional[torch.Tensor] = None,
|
| 678 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 679 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 680 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 681 |
+
use_cache: Optional[bool] = None,
|
| 682 |
+
output_attentions: Optional[bool] = None,
|
| 683 |
+
output_hidden_states: Optional[bool] = None,
|
| 684 |
+
return_dict: Optional[bool] = None,
|
| 685 |
+
is_decoder: Optional[bool] = False,
|
| 686 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
| 687 |
+
r"""
|
| 688 |
+
encoder_hidden_states (`torch.FloatTensor`, *optional*):
|
| 689 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 690 |
+
the model is configured as a decoder.
|
| 691 |
+
encoder_attention_mask (`torch.FloatTensor`, *optional*):
|
| 692 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 693 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 694 |
+
- 1 for tokens that are **not masked**,
|
| 695 |
+
- 0 for tokens that are **masked**.
|
| 696 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 697 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 698 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 699 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 700 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 701 |
+
use_cache (`bool`, *optional*):
|
| 702 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 703 |
+
`past_key_values`).
|
| 704 |
+
"""
|
| 705 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 706 |
+
output_hidden_states = (
|
| 707 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 708 |
+
)
|
| 709 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 710 |
+
|
| 711 |
+
if is_decoder:
|
| 712 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 713 |
+
else:
|
| 714 |
+
use_cache = False
|
| 715 |
+
|
| 716 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 717 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 718 |
+
elif input_ids is not None:
|
| 719 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
| 720 |
+
input_shape = input_ids.size()
|
| 721 |
+
batch_size, seq_length = input_shape
|
| 722 |
+
device = input_ids.device
|
| 723 |
+
elif inputs_embeds is not None:
|
| 724 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 725 |
+
batch_size, seq_length = input_shape
|
| 726 |
+
device = inputs_embeds.device
|
| 727 |
+
elif encoder_embeds is not None:
|
| 728 |
+
input_shape = encoder_embeds.size()[:-1]
|
| 729 |
+
batch_size, seq_length = input_shape
|
| 730 |
+
device = encoder_embeds.device
|
| 731 |
+
else:
|
| 732 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
|
| 733 |
+
|
| 734 |
+
# past_key_values_length
|
| 735 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 736 |
+
|
| 737 |
+
if attention_mask is None:
|
| 738 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length))).to(device)
|
| 739 |
+
|
| 740 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 741 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 742 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
|
| 743 |
+
attention_mask, input_shape, device, is_decoder
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 747 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 748 |
+
if encoder_hidden_states is not None:
|
| 749 |
+
if isinstance(encoder_hidden_states, list):
|
| 750 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
|
| 751 |
+
else:
|
| 752 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
| 753 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 754 |
+
|
| 755 |
+
if isinstance(encoder_attention_mask, list):
|
| 756 |
+
encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
|
| 757 |
+
elif encoder_attention_mask is None:
|
| 758 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
| 759 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 760 |
+
else:
|
| 761 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
| 762 |
+
else:
|
| 763 |
+
encoder_extended_attention_mask = None
|
| 764 |
+
|
| 765 |
+
# Prepare head mask if needed
|
| 766 |
+
# 1.0 in head_mask indicate we keep the head
|
| 767 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 768 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 769 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 770 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 771 |
+
|
| 772 |
+
if encoder_embeds is None:
|
| 773 |
+
embedding_output = self.embeddings(
|
| 774 |
+
input_ids=input_ids,
|
| 775 |
+
position_ids=position_ids,
|
| 776 |
+
inputs_embeds=inputs_embeds,
|
| 777 |
+
past_key_values_length=past_key_values_length,
|
| 778 |
+
)
|
| 779 |
+
else:
|
| 780 |
+
embedding_output = encoder_embeds
|
| 781 |
+
|
| 782 |
+
encoder_outputs = self.encoder(
|
| 783 |
+
embedding_output,
|
| 784 |
+
attention_mask=extended_attention_mask,
|
| 785 |
+
head_mask=head_mask,
|
| 786 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 787 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 788 |
+
past_key_values=past_key_values,
|
| 789 |
+
use_cache=use_cache,
|
| 790 |
+
output_attentions=output_attentions,
|
| 791 |
+
output_hidden_states=output_hidden_states,
|
| 792 |
+
return_dict=return_dict,
|
| 793 |
+
)
|
| 794 |
+
sequence_output = encoder_outputs[0]
|
| 795 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 796 |
+
|
| 797 |
+
if not return_dict:
|
| 798 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 799 |
+
|
| 800 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
| 801 |
+
last_hidden_state=sequence_output,
|
| 802 |
+
pooler_output=pooled_output,
|
| 803 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 804 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 805 |
+
attentions=encoder_outputs.attentions,
|
| 806 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
|
| 811 |
+
class BlipTextLMHeadModel(BlipTextPreTrainedModel, GenerationMixin):
|
| 812 |
+
def __init__(self, config):
|
| 813 |
+
super().__init__(config)
|
| 814 |
+
|
| 815 |
+
self.bert = BlipTextModel(config, add_pooling_layer=False)
|
| 816 |
+
self.cls = BlipTextOnlyMLMHead(config)
|
| 817 |
+
self.label_smoothing = config.label_smoothing
|
| 818 |
+
|
| 819 |
+
def get_input_embeddings(self):
|
| 820 |
+
return self.bert.get_input_embeddings()
|
| 821 |
+
|
| 822 |
+
def set_input_embeddings(self, new_embeddings):
|
| 823 |
+
self.bert.set_input_embeddings(new_embeddings)
|
| 824 |
+
|
| 825 |
+
def get_output_embeddings(self):
|
| 826 |
+
return self.cls.predictions.decoder
|
| 827 |
+
|
| 828 |
+
def set_output_embeddings(self, new_embeddings):
|
| 829 |
+
self.cls.predictions.decoder = new_embeddings
|
| 830 |
+
self.cls.predictions.bias = new_embeddings.bias
|
| 831 |
+
|
| 832 |
+
def forward(
|
| 833 |
+
self,
|
| 834 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 835 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 836 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 837 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 838 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 839 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 840 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
| 841 |
+
labels: Optional[torch.Tensor] = None,
|
| 842 |
+
past_key_values: Optional[List[torch.Tensor]] = None,
|
| 843 |
+
use_cache: Optional[bool] = None,
|
| 844 |
+
output_attentions: Optional[bool] = None,
|
| 845 |
+
output_hidden_states: Optional[bool] = None,
|
| 846 |
+
return_dict: Optional[bool] = None,
|
| 847 |
+
return_logits: Optional[bool] = False,
|
| 848 |
+
is_decoder: Optional[bool] = True,
|
| 849 |
+
reduction: Optional[str] = "mean",
|
| 850 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
| 851 |
+
r"""
|
| 852 |
+
encoder_hidden_states (`torch.FloatTensor`, *optional*): Sequence of
|
| 853 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
|
| 854 |
+
configured as a decoder.
|
| 855 |
+
encoder_attention_mask (`torch.FloatTensor`, *optional*):
|
| 856 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 857 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 858 |
+
- 1 for tokens that are **not masked**,
|
| 859 |
+
- 0 for tokens that are **masked**.
|
| 860 |
+
labels (`torch.LongTensor`, *optional*):
|
| 861 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 862 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 863 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
|
| 864 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*):
|
| 865 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 866 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 867 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 868 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 869 |
+
use_cache (`bool`, *optional*):
|
| 870 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 871 |
+
`past_key_values`).
|
| 872 |
+
"""
|
| 873 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 874 |
+
if labels is not None:
|
| 875 |
+
use_cache = False
|
| 876 |
+
|
| 877 |
+
outputs = self.bert(
|
| 878 |
+
input_ids,
|
| 879 |
+
attention_mask=attention_mask,
|
| 880 |
+
position_ids=position_ids,
|
| 881 |
+
head_mask=head_mask,
|
| 882 |
+
inputs_embeds=inputs_embeds,
|
| 883 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 884 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 885 |
+
past_key_values=past_key_values,
|
| 886 |
+
use_cache=use_cache,
|
| 887 |
+
output_attentions=output_attentions,
|
| 888 |
+
output_hidden_states=output_hidden_states,
|
| 889 |
+
return_dict=return_dict,
|
| 890 |
+
is_decoder=is_decoder,
|
| 891 |
+
)
|
| 892 |
+
|
| 893 |
+
sequence_output = outputs[0]
|
| 894 |
+
prediction_scores = self.cls(sequence_output)
|
| 895 |
+
|
| 896 |
+
if return_logits:
|
| 897 |
+
return prediction_scores[:, :-1, :].contiguous()
|
| 898 |
+
|
| 899 |
+
lm_loss = None
|
| 900 |
+
if labels is not None:
|
| 901 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
| 902 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
| 903 |
+
labels = labels[:, 1:].contiguous().to(shifted_prediction_scores.device)
|
| 904 |
+
loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=self.label_smoothing)
|
| 905 |
+
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
| 906 |
+
if reduction == "none":
|
| 907 |
+
lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
|
| 908 |
+
|
| 909 |
+
if not return_dict:
|
| 910 |
+
output = (prediction_scores,) + outputs[2:]
|
| 911 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
| 912 |
+
|
| 913 |
+
return CausalLMOutputWithCrossAttentions(
|
| 914 |
+
loss=lm_loss,
|
| 915 |
+
logits=prediction_scores,
|
| 916 |
+
past_key_values=outputs.past_key_values,
|
| 917 |
+
hidden_states=outputs.hidden_states,
|
| 918 |
+
attentions=outputs.attentions,
|
| 919 |
+
cross_attentions=outputs.cross_attentions,
|
| 920 |
+
)
|
| 921 |
+
|
| 922 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
| 923 |
+
# Overwrite -- hardcoded key return (`is_decoder=True`)
|
| 924 |
+
|
| 925 |
+
input_shape = input_ids.shape
|
| 926 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 927 |
+
if attention_mask is None:
|
| 928 |
+
attention_mask = input_ids.new_ones(input_shape)
|
| 929 |
+
|
| 930 |
+
# cut decoder_input_ids if past_key_values is used
|
| 931 |
+
if past_key_values is not None:
|
| 932 |
+
past_length = past_key_values[0][0].shape[2]
|
| 933 |
+
|
| 934 |
+
# Some generation methods already pass only the last input ID
|
| 935 |
+
if input_ids.shape[1] > past_length:
|
| 936 |
+
remove_prefix_length = past_length
|
| 937 |
+
else:
|
| 938 |
+
# Default to old behavior: keep only final ID
|
| 939 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
| 940 |
+
|
| 941 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
| 942 |
+
|
| 943 |
+
return {
|
| 944 |
+
"input_ids": input_ids,
|
| 945 |
+
"attention_mask": attention_mask,
|
| 946 |
+
"past_key_values": past_key_values,
|
| 947 |
+
"encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
|
| 948 |
+
"encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
|
| 949 |
+
"is_decoder": True,
|
| 950 |
+
}
|
| 951 |
+
|
| 952 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 953 |
+
reordered_past = ()
|
| 954 |
+
for layer_past in past_key_values:
|
| 955 |
+
reordered_past += (
|
| 956 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 957 |
+
)
|
| 958 |
+
return reordered_past
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip.py
ADDED
|
@@ -0,0 +1,1709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""TensorFlow BLIP model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import warnings
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Any, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import tensorflow as tf
|
| 24 |
+
|
| 25 |
+
from ...modeling_tf_outputs import TFBaseModelOutput, TFBaseModelOutputWithPooling
|
| 26 |
+
from ...modeling_tf_utils import (
|
| 27 |
+
TFPreTrainedModel,
|
| 28 |
+
get_initializer,
|
| 29 |
+
get_tf_activation,
|
| 30 |
+
keras,
|
| 31 |
+
keras_serializable,
|
| 32 |
+
shape_list,
|
| 33 |
+
unpack_inputs,
|
| 34 |
+
)
|
| 35 |
+
from ...tf_utils import check_embeddings_within_bounds, 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_blip import BlipConfig, BlipTextConfig, BlipVisionConfig
|
| 44 |
+
from .modeling_tf_blip_text import BLIP_TEXT_INPUTS_DOCSTRING, TFBlipTextLMHeadModel, TFBlipTextModel
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
_CHECKPOINT_FOR_DOC = "Salesforce/blip-vqa-base"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Copied from transformers.models.clip.modeling_tf_clip.contrastive_loss
|
| 53 |
+
def contrastive_loss(logits: tf.Tensor) -> tf.Tensor:
|
| 54 |
+
return tf.math.reduce_mean(
|
| 55 |
+
keras.metrics.sparse_categorical_crossentropy(
|
| 56 |
+
y_true=tf.range(shape_list(logits)[0]), y_pred=logits, from_logits=True
|
| 57 |
+
)
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Copied from transformers.models.clip.modeling_tf_clip.clip_loss with clip->blip
|
| 62 |
+
def blip_loss(similarity: tf.Tensor) -> tf.Tensor:
|
| 63 |
+
caption_loss = contrastive_loss(similarity)
|
| 64 |
+
image_loss = contrastive_loss(tf.transpose(similarity))
|
| 65 |
+
return (caption_loss + image_loss) / 2.0
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass
|
| 69 |
+
class TFBlipForConditionalGenerationModelOutput(ModelOutput):
|
| 70 |
+
"""
|
| 71 |
+
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
|
| 72 |
+
last hidden states. This class also adds the loss term from the text decoder.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
loss (`tf.Tensor`, *optional*, returned when `labels` is provided, `tf.Tensor` of shape `(1,)`):
|
| 76 |
+
Languge modeling loss from the text decoder.
|
| 77 |
+
logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
|
| 78 |
+
Prediction scores of the language modeling head of the text decoder model.
|
| 79 |
+
image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)`, *optional*):
|
| 80 |
+
The image embeddings obtained after applying the Vision Transformer model to the input image.
|
| 81 |
+
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 82 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 83 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True`):
|
| 84 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
|
| 85 |
+
the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 86 |
+
|
| 87 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 88 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed):
|
| 89 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 90 |
+
sequence_length)`.
|
| 91 |
+
|
| 92 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 93 |
+
heads.`
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
loss: Tuple[tf.Tensor] | None = None
|
| 97 |
+
logits: Tuple[tf.Tensor] | None = None
|
| 98 |
+
image_embeds: tf.Tensor | None = None
|
| 99 |
+
last_hidden_state: tf.Tensor = None
|
| 100 |
+
hidden_states: Tuple[tf.Tensor, ...] | None = None
|
| 101 |
+
attentions: Tuple[tf.Tensor, ...] | None = None
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def decoder_logits(self):
|
| 105 |
+
warnings.warn(
|
| 106 |
+
"`decoder_logits` attribute is deprecated and will be removed in version 5 of Transformers."
|
| 107 |
+
" Please use the `logits` attribute to retrieve the final output instead.",
|
| 108 |
+
FutureWarning,
|
| 109 |
+
)
|
| 110 |
+
return self.logits
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@dataclass
|
| 114 |
+
class TFBlipTextVisionModelOutput(ModelOutput):
|
| 115 |
+
"""
|
| 116 |
+
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
|
| 117 |
+
last hidden states. This class also adds the loss term from the text decoder.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 121 |
+
Languge modeling loss from the text decoder.
|
| 122 |
+
image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 123 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 124 |
+
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 125 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 126 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 127 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
|
| 128 |
+
the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 129 |
+
|
| 130 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 131 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 132 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 133 |
+
sequence_length)`.
|
| 134 |
+
|
| 135 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 136 |
+
heads.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
loss: tf.Tensor | None = None
|
| 140 |
+
image_embeds: tf.Tensor | None = None
|
| 141 |
+
last_hidden_state: tf.Tensor = None
|
| 142 |
+
hidden_states: Tuple[tf.Tensor, ...] | None = None
|
| 143 |
+
attentions: Tuple[tf.Tensor, ...] | None = None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
@dataclass
|
| 147 |
+
class TFBlipImageTextMatchingModelOutput(ModelOutput):
|
| 148 |
+
"""
|
| 149 |
+
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
|
| 150 |
+
last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
|
| 151 |
+
scores.
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
itm_score (`tf.Tensor`):
|
| 155 |
+
The image-text similarity scores.
|
| 156 |
+
loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 157 |
+
Languge modeling loss from the text decoder.
|
| 158 |
+
image_embeds (`tf.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 159 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 160 |
+
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 161 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 162 |
+
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 163 |
+
Tuple of `tf.Tensor` (one for the output of the embeddings, if the model has an embedding layer, + one for
|
| 164 |
+
the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 165 |
+
|
| 166 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 167 |
+
vision_pooler_output (`tf.Tensor` of shape `(batch_size, hidden_size)`, *optional*):
|
| 168 |
+
Last layer hidden-state of the vision of the vision-only branch of the model.
|
| 169 |
+
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 170 |
+
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 171 |
+
sequence_length)`.
|
| 172 |
+
|
| 173 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 174 |
+
heads.
|
| 175 |
+
question_embeds (`tf.Tensor`):
|
| 176 |
+
The question embeddings obtained by the text projection layer.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
itm_score: tf.Tensor | None = None
|
| 180 |
+
loss: tf.Tensor | None = None
|
| 181 |
+
image_embeds: tf.Tensor | None = None
|
| 182 |
+
last_hidden_state: tf.Tensor = None
|
| 183 |
+
hidden_states: Tuple[tf.Tensor, ...] | None = None
|
| 184 |
+
vision_pooler_output: tf.Tensor | None = None
|
| 185 |
+
attentions: Tuple[tf.Tensor, ...] | None = None
|
| 186 |
+
question_embeds: Tuple[tf.Tensor] | None = None
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@dataclass
|
| 190 |
+
class TFBlipOutput(ModelOutput):
|
| 191 |
+
"""
|
| 192 |
+
Args:
|
| 193 |
+
loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 194 |
+
Contrastive loss for image-text similarity.
|
| 195 |
+
logits_per_image:(`tf.Tensor` of shape `(image_batch_size, text_batch_size)`):
|
| 196 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 197 |
+
similarity scores.
|
| 198 |
+
logits_per_text:(`tf.Tensor` of shape `(text_batch_size, image_batch_size)`):
|
| 199 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 200 |
+
similarity scores.
|
| 201 |
+
text_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
|
| 202 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
|
| 203 |
+
image_embeds(`tf.Tensor` of shape `(batch_size, output_dim`):
|
| 204 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
|
| 205 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
| 206 |
+
The output of the [`BlipTextModel`].
|
| 207 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
| 208 |
+
The output of the [`BlipVisionModel`].
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
loss: tf.Tensor | None = None
|
| 212 |
+
logits_per_image: tf.Tensor = None
|
| 213 |
+
logits_per_text: tf.Tensor = None
|
| 214 |
+
text_embeds: tf.Tensor = None
|
| 215 |
+
image_embeds: tf.Tensor = None
|
| 216 |
+
text_model_output: TFBaseModelOutputWithPooling = None
|
| 217 |
+
vision_model_output: TFBaseModelOutputWithPooling = None
|
| 218 |
+
|
| 219 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 220 |
+
return tuple(
|
| 221 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 222 |
+
for k in self.keys()
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class TFBlipVisionEmbeddings(keras.layers.Layer):
|
| 227 |
+
def __init__(self, config: BlipVisionConfig, **kwargs):
|
| 228 |
+
super().__init__(**kwargs)
|
| 229 |
+
self.config = config
|
| 230 |
+
self.embed_dim = config.hidden_size
|
| 231 |
+
self.image_size = config.image_size
|
| 232 |
+
self.patch_size = config.patch_size
|
| 233 |
+
|
| 234 |
+
self.patch_embedding = keras.layers.Conv2D(
|
| 235 |
+
filters=self.embed_dim,
|
| 236 |
+
kernel_size=self.patch_size,
|
| 237 |
+
strides=self.patch_size,
|
| 238 |
+
kernel_initializer=get_initializer(self.config.initializer_range),
|
| 239 |
+
data_format="channels_last",
|
| 240 |
+
name="patch_embedding",
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 244 |
+
self.num_positions = self.num_patches + 1
|
| 245 |
+
|
| 246 |
+
def build(self, input_shape=None):
|
| 247 |
+
self.class_embedding = self.add_weight(
|
| 248 |
+
shape=(1, 1, self.embed_dim),
|
| 249 |
+
initializer=get_initializer(self.config.initializer_range),
|
| 250 |
+
trainable=True,
|
| 251 |
+
name="class_embedding",
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
self.position_embedding = self.add_weight(
|
| 255 |
+
shape=(1, self.num_positions, self.embed_dim),
|
| 256 |
+
initializer=get_initializer(self.config.initializer_range),
|
| 257 |
+
trainable=True,
|
| 258 |
+
name="position_embedding",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
if self.built:
|
| 262 |
+
return
|
| 263 |
+
self.built = True
|
| 264 |
+
if getattr(self, "patch_embedding", None) is not None:
|
| 265 |
+
with tf.name_scope(self.patch_embedding.name):
|
| 266 |
+
self.patch_embedding.build([None, None, None, 3])
|
| 267 |
+
|
| 268 |
+
def call(self, pixel_values: tf.Tensor) -> tf.Tensor:
|
| 269 |
+
# Input is channels-first, we transpose. PyTorch transposes after the conv because PyTorch
|
| 270 |
+
# likes channels-first convs.
|
| 271 |
+
batch_size = tf.shape(pixel_values)[0]
|
| 272 |
+
pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
|
| 273 |
+
patch_embeds = self.patch_embedding(pixel_values)
|
| 274 |
+
patch_embeds = tf.reshape(patch_embeds, (batch_size, self.num_patches, -1))
|
| 275 |
+
|
| 276 |
+
class_embeds = tf.broadcast_to(self.class_embedding, (batch_size, 1, self.embed_dim))
|
| 277 |
+
embeddings = tf.concat([class_embeds, patch_embeds], axis=1)
|
| 278 |
+
embeddings = embeddings + self.position_embedding[:, : tf.shape(embeddings)[1], :]
|
| 279 |
+
return embeddings
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
# Copied from transformers.models.clip.modeling_tf_clip.TFCLIPTextEmbeddings with CLIP->Blip
|
| 283 |
+
class TFBlipTextEmbeddings(keras.layers.Layer):
|
| 284 |
+
def __init__(self, config: BlipTextConfig, **kwargs):
|
| 285 |
+
super().__init__(**kwargs)
|
| 286 |
+
|
| 287 |
+
self.embed_dim = config.hidden_size
|
| 288 |
+
|
| 289 |
+
self.config = config
|
| 290 |
+
|
| 291 |
+
def build(self, input_shape: tf.TensorShape = None):
|
| 292 |
+
with tf.name_scope("token_embedding"):
|
| 293 |
+
self.weight = self.add_weight(
|
| 294 |
+
shape=(self.config.vocab_size, self.embed_dim),
|
| 295 |
+
initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
|
| 296 |
+
trainable=True,
|
| 297 |
+
name="weight",
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
with tf.name_scope("position_embedding"):
|
| 301 |
+
self.position_embedding = self.add_weight(
|
| 302 |
+
shape=(self.config.max_position_embeddings, self.embed_dim),
|
| 303 |
+
initializer=get_initializer(self.config.initializer_factor * self.config.initializer_range),
|
| 304 |
+
trainable=True,
|
| 305 |
+
name="embeddings",
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
super().build(input_shape)
|
| 309 |
+
|
| 310 |
+
def call(
|
| 311 |
+
self,
|
| 312 |
+
input_ids: tf.Tensor = None,
|
| 313 |
+
position_ids: tf.Tensor = None,
|
| 314 |
+
inputs_embeds: tf.Tensor = None,
|
| 315 |
+
) -> tf.Tensor:
|
| 316 |
+
"""
|
| 317 |
+
Applies embedding based on inputs tensor.
|
| 318 |
+
|
| 319 |
+
Returns:
|
| 320 |
+
final_embeddings (`tf.Tensor`): output embedding tensor.
|
| 321 |
+
"""
|
| 322 |
+
if input_ids is None and inputs_embeds is None:
|
| 323 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 324 |
+
|
| 325 |
+
if inputs_embeds is None:
|
| 326 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
| 327 |
+
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
|
| 328 |
+
|
| 329 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 330 |
+
|
| 331 |
+
if position_ids is None:
|
| 332 |
+
position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
|
| 333 |
+
|
| 334 |
+
position_embeds = tf.gather(params=self.position_embedding, indices=position_ids)
|
| 335 |
+
position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
|
| 336 |
+
final_embeddings = inputs_embeds + position_embeds
|
| 337 |
+
|
| 338 |
+
return final_embeddings
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class TFBlipAttention(keras.layers.Layer):
|
| 342 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 343 |
+
|
| 344 |
+
def __init__(self, config, **kwargs):
|
| 345 |
+
super().__init__(**kwargs)
|
| 346 |
+
self.config = config
|
| 347 |
+
self.embed_dim = config.hidden_size
|
| 348 |
+
self.num_heads = config.num_attention_heads
|
| 349 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 350 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 351 |
+
raise ValueError(
|
| 352 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 353 |
+
f" {self.num_heads})."
|
| 354 |
+
)
|
| 355 |
+
self.scale = self.head_dim**-0.5
|
| 356 |
+
self.dropout = keras.layers.Dropout(config.attention_dropout, name="dropout")
|
| 357 |
+
|
| 358 |
+
self.qkv = keras.layers.Dense(
|
| 359 |
+
3 * self.embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="qkv"
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
self.projection = keras.layers.Dense(
|
| 363 |
+
self.embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="projection"
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
def call(
|
| 367 |
+
self,
|
| 368 |
+
hidden_states: tf.Tensor,
|
| 369 |
+
head_mask: tf.Tensor | None = None,
|
| 370 |
+
output_attentions: Optional[bool] = False,
|
| 371 |
+
training: Optional[bool] = None,
|
| 372 |
+
) -> Tuple[tf.Tensor, tf.Tensor | None, Tuple[tf.Tensor] | None]:
|
| 373 |
+
"""Input shape: Batch x Time x Channel"""
|
| 374 |
+
|
| 375 |
+
bsz, tgt_len, embed_dim = shape_list(hidden_states)
|
| 376 |
+
|
| 377 |
+
mixed_qkv = self.qkv(hidden_states)
|
| 378 |
+
mixed_qkv = tf.reshape(mixed_qkv, (bsz, tgt_len, 3, self.num_heads, self.head_dim))
|
| 379 |
+
mixed_qkv = tf.transpose(mixed_qkv, perm=(2, 0, 3, 1, 4))
|
| 380 |
+
|
| 381 |
+
query_states, key_states, value_states = mixed_qkv[0], mixed_qkv[1], mixed_qkv[2]
|
| 382 |
+
|
| 383 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 384 |
+
attention_scores = query_states @ tf.transpose(key_states, (0, 1, 3, 2))
|
| 385 |
+
|
| 386 |
+
attention_scores = attention_scores * self.scale
|
| 387 |
+
|
| 388 |
+
# Normalize the attention scores to probabilities.
|
| 389 |
+
attention_probs = stable_softmax(attention_scores, axis=-1)
|
| 390 |
+
|
| 391 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 392 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 393 |
+
attention_probs = self.dropout(attention_probs, training=training)
|
| 394 |
+
|
| 395 |
+
# Mask heads if we want to
|
| 396 |
+
if head_mask is not None:
|
| 397 |
+
attention_probs = attention_probs * head_mask
|
| 398 |
+
|
| 399 |
+
context_layer = tf.transpose(attention_probs @ value_states, perm=(0, 2, 1, 3))
|
| 400 |
+
|
| 401 |
+
new_context_layer_shape = shape_list(context_layer)[:-2] + [self.embed_dim]
|
| 402 |
+
context_layer = tf.reshape(context_layer, new_context_layer_shape)
|
| 403 |
+
|
| 404 |
+
output = self.projection(context_layer)
|
| 405 |
+
|
| 406 |
+
outputs = (output, attention_probs) if output_attentions else (output, None)
|
| 407 |
+
|
| 408 |
+
return outputs
|
| 409 |
+
|
| 410 |
+
def build(self, input_shape=None):
|
| 411 |
+
if self.built:
|
| 412 |
+
return
|
| 413 |
+
self.built = True
|
| 414 |
+
if getattr(self, "dropout", None) is not None:
|
| 415 |
+
with tf.name_scope(self.dropout.name):
|
| 416 |
+
self.dropout.build(None)
|
| 417 |
+
if getattr(self, "qkv", None) is not None:
|
| 418 |
+
with tf.name_scope(self.qkv.name):
|
| 419 |
+
self.qkv.build([None, None, self.embed_dim])
|
| 420 |
+
if getattr(self, "projection", None) is not None:
|
| 421 |
+
with tf.name_scope(self.projection.name):
|
| 422 |
+
self.projection.build([None, None, self.embed_dim])
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
class TFBlipMLP(keras.layers.Layer):
|
| 426 |
+
def __init__(self, config: BlipConfig, **kwargs):
|
| 427 |
+
super().__init__(**kwargs)
|
| 428 |
+
|
| 429 |
+
self.activation_fn = get_tf_activation(config.hidden_act)
|
| 430 |
+
|
| 431 |
+
in_proj_std = (config.hidden_size**-0.5) * ((2 * config.num_hidden_layers) ** -0.5)
|
| 432 |
+
fc_std = (2 * config.hidden_size) ** -0.5
|
| 433 |
+
|
| 434 |
+
self.fc1 = keras.layers.Dense(
|
| 435 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(fc_std), name="fc1"
|
| 436 |
+
)
|
| 437 |
+
self.fc2 = keras.layers.Dense(
|
| 438 |
+
units=config.hidden_size, kernel_initializer=get_initializer(in_proj_std), name="fc2"
|
| 439 |
+
)
|
| 440 |
+
self.config = config
|
| 441 |
+
|
| 442 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 443 |
+
hidden_states = self.fc1(inputs=hidden_states)
|
| 444 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 445 |
+
hidden_states = self.fc2(inputs=hidden_states)
|
| 446 |
+
return hidden_states
|
| 447 |
+
|
| 448 |
+
def build(self, input_shape=None):
|
| 449 |
+
if self.built:
|
| 450 |
+
return
|
| 451 |
+
self.built = True
|
| 452 |
+
if getattr(self, "fc1", None) is not None:
|
| 453 |
+
with tf.name_scope(self.fc1.name):
|
| 454 |
+
self.fc1.build([None, None, self.config.hidden_size])
|
| 455 |
+
if getattr(self, "fc2", None) is not None:
|
| 456 |
+
with tf.name_scope(self.fc2.name):
|
| 457 |
+
self.fc2.build([None, None, self.config.intermediate_size])
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class TFBlipEncoderLayer(keras.layers.Layer):
|
| 461 |
+
def __init__(self, config: BlipConfig, **kwargs):
|
| 462 |
+
super().__init__(**kwargs)
|
| 463 |
+
self.embed_dim = config.hidden_size
|
| 464 |
+
self.self_attn = TFBlipAttention(config, name="self_attn")
|
| 465 |
+
self.layer_norm1 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm1")
|
| 466 |
+
self.mlp = TFBlipMLP(config, name="mlp")
|
| 467 |
+
self.layer_norm2 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm2")
|
| 468 |
+
|
| 469 |
+
def call(
|
| 470 |
+
self,
|
| 471 |
+
hidden_states: tf.Tensor,
|
| 472 |
+
attention_mask: tf.Tensor,
|
| 473 |
+
output_attentions: Optional[bool] = False,
|
| 474 |
+
training: Optional[bool] = None,
|
| 475 |
+
) -> Tuple[tf.Tensor]:
|
| 476 |
+
"""
|
| 477 |
+
Args:
|
| 478 |
+
hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 479 |
+
attention_mask (`tf.Tensor`): attention mask of size
|
| 480 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 481 |
+
`(config.encoder_attention_heads,)`.
|
| 482 |
+
output_attentions (`bool`, *optional*):
|
| 483 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 484 |
+
returned tensors for more detail.
|
| 485 |
+
"""
|
| 486 |
+
residual = hidden_states
|
| 487 |
+
|
| 488 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 489 |
+
hidden_states, attn_weights = self.self_attn(
|
| 490 |
+
hidden_states=hidden_states,
|
| 491 |
+
head_mask=attention_mask,
|
| 492 |
+
output_attentions=output_attentions,
|
| 493 |
+
training=training,
|
| 494 |
+
)
|
| 495 |
+
hidden_states = hidden_states + residual
|
| 496 |
+
residual = hidden_states
|
| 497 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 498 |
+
hidden_states = self.mlp(hidden_states)
|
| 499 |
+
|
| 500 |
+
hidden_states = hidden_states + residual
|
| 501 |
+
|
| 502 |
+
outputs = (hidden_states,)
|
| 503 |
+
|
| 504 |
+
if output_attentions:
|
| 505 |
+
outputs += (attn_weights,)
|
| 506 |
+
|
| 507 |
+
return outputs
|
| 508 |
+
|
| 509 |
+
def build(self, input_shape=None):
|
| 510 |
+
if self.built:
|
| 511 |
+
return
|
| 512 |
+
self.built = True
|
| 513 |
+
if getattr(self, "self_attn", None) is not None:
|
| 514 |
+
with tf.name_scope(self.self_attn.name):
|
| 515 |
+
self.self_attn.build(None)
|
| 516 |
+
if getattr(self, "layer_norm1", None) is not None:
|
| 517 |
+
with tf.name_scope(self.layer_norm1.name):
|
| 518 |
+
self.layer_norm1.build([None, None, self.embed_dim])
|
| 519 |
+
if getattr(self, "mlp", None) is not None:
|
| 520 |
+
with tf.name_scope(self.mlp.name):
|
| 521 |
+
self.mlp.build(None)
|
| 522 |
+
if getattr(self, "layer_norm2", None) is not None:
|
| 523 |
+
with tf.name_scope(self.layer_norm2.name):
|
| 524 |
+
self.layer_norm2.build([None, None, self.embed_dim])
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class TFBlipPreTrainedModel(TFPreTrainedModel):
|
| 528 |
+
"""
|
| 529 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 530 |
+
models.
|
| 531 |
+
"""
|
| 532 |
+
|
| 533 |
+
config_class = BlipConfig
|
| 534 |
+
base_model_prefix = "blip"
|
| 535 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
BLIP_START_DOCSTRING = r"""
|
| 539 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 540 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 541 |
+
etc.)
|
| 542 |
+
|
| 543 |
+
This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 544 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 545 |
+
behavior.
|
| 546 |
+
|
| 547 |
+
Parameters:
|
| 548 |
+
config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
|
| 549 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 550 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 551 |
+
"""
|
| 552 |
+
|
| 553 |
+
BLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 554 |
+
Args:
|
| 555 |
+
pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
|
| 556 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 557 |
+
[`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
|
| 558 |
+
output_attentions (`bool`, *optional*):
|
| 559 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 560 |
+
tensors for more detail.
|
| 561 |
+
output_hidden_states (`bool`, *optional*):
|
| 562 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 563 |
+
more detail.
|
| 564 |
+
return_dict (`bool`, *optional*):
|
| 565 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 566 |
+
"""
|
| 567 |
+
|
| 568 |
+
BLIP_INPUTS_DOCSTRING = r"""
|
| 569 |
+
Args:
|
| 570 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 571 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 572 |
+
it.
|
| 573 |
+
|
| 574 |
+
Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
|
| 575 |
+
|
| 576 |
+
[What are input IDs?](../glossary#input-ids)
|
| 577 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 578 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 579 |
+
|
| 580 |
+
- 1 for tokens that are **not masked**,
|
| 581 |
+
- 0 for tokens that are **masked**.
|
| 582 |
+
|
| 583 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 584 |
+
position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 585 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 586 |
+
config.max_position_embeddings - 1]`.
|
| 587 |
+
|
| 588 |
+
[What are position IDs?](../glossary#position-ids)
|
| 589 |
+
pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
|
| 590 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 591 |
+
[`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
|
| 592 |
+
return_loss (`bool`, *optional*):
|
| 593 |
+
Whether or not to return the contrastive loss.
|
| 594 |
+
output_attentions (`bool`, *optional*):
|
| 595 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 596 |
+
tensors for more detail.
|
| 597 |
+
output_hidden_states (`bool`, *optional*):
|
| 598 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 599 |
+
more detail.
|
| 600 |
+
return_dict (`bool`, *optional*):
|
| 601 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 602 |
+
"""
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
@keras_serializable
|
| 606 |
+
class TFBlipEncoder(keras.layers.Layer):
|
| 607 |
+
config_class = BlipConfig
|
| 608 |
+
"""
|
| 609 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 610 |
+
[`BlipEncoderLayer`].
|
| 611 |
+
|
| 612 |
+
Args:
|
| 613 |
+
config (`BlipConfig`):
|
| 614 |
+
The corresponding vision configuration for the `BlipEncoder`.
|
| 615 |
+
"""
|
| 616 |
+
|
| 617 |
+
def __init__(self, config: BlipConfig, **kwargs):
|
| 618 |
+
super().__init__(**kwargs)
|
| 619 |
+
self.config = config
|
| 620 |
+
self.layers = [TFBlipEncoderLayer(config, name=f"layers_._{i}") for i in range(config.num_hidden_layers)]
|
| 621 |
+
|
| 622 |
+
@unpack_inputs
|
| 623 |
+
def call(
|
| 624 |
+
self,
|
| 625 |
+
inputs_embeds,
|
| 626 |
+
attention_mask: tf.Tensor | None = None,
|
| 627 |
+
output_attentions: Optional[bool] = None,
|
| 628 |
+
output_hidden_states: Optional[bool] = None,
|
| 629 |
+
return_dict: Optional[bool] = None,
|
| 630 |
+
training: Optional[bool] = None,
|
| 631 |
+
) -> Union[Tuple, TFBaseModelOutput]:
|
| 632 |
+
r"""
|
| 633 |
+
Args:
|
| 634 |
+
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 635 |
+
Embedded representation of the inputs. Should be float, not int tokens.
|
| 636 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 637 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 638 |
+
|
| 639 |
+
- 1 for tokens that are **not masked**,
|
| 640 |
+
- 0 for tokens that are **masked**.
|
| 641 |
+
|
| 642 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 643 |
+
output_attentions (`bool`, *optional*):
|
| 644 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 645 |
+
returned tensors for more detail.
|
| 646 |
+
output_hidden_states (`bool`, *optional*):
|
| 647 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 648 |
+
for more detail.
|
| 649 |
+
return_dict (`bool`, *optional*):
|
| 650 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 651 |
+
"""
|
| 652 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 653 |
+
output_hidden_states = (
|
| 654 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 655 |
+
)
|
| 656 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 657 |
+
|
| 658 |
+
encoder_states = () if output_hidden_states else None
|
| 659 |
+
all_attentions = () if output_attentions else None
|
| 660 |
+
|
| 661 |
+
hidden_states = inputs_embeds
|
| 662 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 663 |
+
if output_hidden_states:
|
| 664 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 665 |
+
layer_outputs = encoder_layer(
|
| 666 |
+
hidden_states,
|
| 667 |
+
attention_mask,
|
| 668 |
+
output_attentions=output_attentions,
|
| 669 |
+
training=training,
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
hidden_states = layer_outputs[0]
|
| 673 |
+
|
| 674 |
+
if output_attentions:
|
| 675 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 676 |
+
|
| 677 |
+
if output_hidden_states:
|
| 678 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 679 |
+
|
| 680 |
+
if not return_dict:
|
| 681 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 682 |
+
return TFBaseModelOutput(
|
| 683 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
def build(self, input_shape=None):
|
| 687 |
+
if self.built:
|
| 688 |
+
return
|
| 689 |
+
self.built = True
|
| 690 |
+
if getattr(self, "layers", None) is not None:
|
| 691 |
+
for layer in self.layers:
|
| 692 |
+
with tf.name_scope(layer.name):
|
| 693 |
+
layer.build(None)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class TFBlipVisionModel(TFBlipPreTrainedModel):
|
| 697 |
+
main_input_name = "pixel_values"
|
| 698 |
+
config_class = BlipVisionConfig
|
| 699 |
+
|
| 700 |
+
def __init__(self, config: BlipVisionConfig, *args, **kwargs):
|
| 701 |
+
super().__init__(config, *args, **kwargs)
|
| 702 |
+
self.config = config
|
| 703 |
+
|
| 704 |
+
self.embeddings = TFBlipVisionEmbeddings(config, name="embeddings")
|
| 705 |
+
self.encoder = TFBlipEncoder(config, name="encoder")
|
| 706 |
+
self.post_layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="post_layernorm")
|
| 707 |
+
self.embed_dim = config.hidden_size
|
| 708 |
+
|
| 709 |
+
def serving_output(self, output: TFBaseModelOutputWithPooling) -> TFBaseModelOutputWithPooling:
|
| 710 |
+
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
|
| 711 |
+
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
|
| 712 |
+
|
| 713 |
+
return TFBaseModelOutputWithPooling(
|
| 714 |
+
last_hidden_state=output.last_hidden_state,
|
| 715 |
+
pooler_output=output.pooler_output,
|
| 716 |
+
hidden_states=hs,
|
| 717 |
+
attentions=attns,
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
@unpack_inputs
|
| 721 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 722 |
+
@replace_return_docstrings(output_type=TFBaseModelOutputWithPooling, config_class=BlipVisionConfig)
|
| 723 |
+
def call(
|
| 724 |
+
self,
|
| 725 |
+
pixel_values: tf.Tensor | None = None,
|
| 726 |
+
output_attentions: Optional[bool] = None,
|
| 727 |
+
output_hidden_states: Optional[bool] = None,
|
| 728 |
+
return_dict: Optional[bool] = None,
|
| 729 |
+
training: Optional[bool] = None,
|
| 730 |
+
) -> Union[Tuple, TFBaseModelOutputWithPooling]:
|
| 731 |
+
r"""
|
| 732 |
+
Returns:
|
| 733 |
+
|
| 734 |
+
"""
|
| 735 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 736 |
+
output_hidden_states = (
|
| 737 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 738 |
+
)
|
| 739 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 740 |
+
|
| 741 |
+
if pixel_values is None:
|
| 742 |
+
raise ValueError("You have to specify pixel_values")
|
| 743 |
+
|
| 744 |
+
hidden_states = self.embeddings(pixel_values)
|
| 745 |
+
|
| 746 |
+
encoder_outputs = self.encoder(
|
| 747 |
+
inputs_embeds=hidden_states,
|
| 748 |
+
output_attentions=output_attentions,
|
| 749 |
+
output_hidden_states=output_hidden_states,
|
| 750 |
+
return_dict=return_dict,
|
| 751 |
+
training=training,
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
last_hidden_state = encoder_outputs[0]
|
| 755 |
+
last_hidden_state = self.post_layernorm(last_hidden_state)
|
| 756 |
+
|
| 757 |
+
pooled_output = last_hidden_state[:, 0, :]
|
| 758 |
+
# TF gets confused if we call the layer with inputs of different ranks, so insert a singleton dimension
|
| 759 |
+
pooled_output = self.post_layernorm(tf.expand_dims(pooled_output, 1))
|
| 760 |
+
pooled_output = tf.squeeze(pooled_output, 1)
|
| 761 |
+
|
| 762 |
+
if not return_dict:
|
| 763 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 764 |
+
|
| 765 |
+
return TFBaseModelOutputWithPooling(
|
| 766 |
+
last_hidden_state=last_hidden_state,
|
| 767 |
+
pooler_output=pooled_output,
|
| 768 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 769 |
+
attentions=encoder_outputs.attentions,
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
def get_input_embeddings(self):
|
| 773 |
+
return self.embeddings
|
| 774 |
+
|
| 775 |
+
def build(self, input_shape=None):
|
| 776 |
+
if self.built:
|
| 777 |
+
return
|
| 778 |
+
self.built = True
|
| 779 |
+
if getattr(self, "embeddings", None) is not None:
|
| 780 |
+
with tf.name_scope(self.embeddings.name):
|
| 781 |
+
self.embeddings.build(None)
|
| 782 |
+
if getattr(self, "encoder", None) is not None:
|
| 783 |
+
with tf.name_scope(self.encoder.name):
|
| 784 |
+
self.encoder.build(None)
|
| 785 |
+
if getattr(self, "post_layernorm", None) is not None:
|
| 786 |
+
with tf.name_scope(self.post_layernorm.name):
|
| 787 |
+
self.post_layernorm.build([None, None, self.embed_dim])
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
class TFBlipMainLayer(keras.layers.Layer):
|
| 791 |
+
config_class = BlipConfig
|
| 792 |
+
|
| 793 |
+
def __init__(self, config: BlipConfig, *args, **kwargs):
|
| 794 |
+
super().__init__(*args, **kwargs)
|
| 795 |
+
|
| 796 |
+
if not isinstance(config.text_config, BlipTextConfig):
|
| 797 |
+
raise TypeError(
|
| 798 |
+
"config.text_config is expected to be of type BlipTextConfig but is of type"
|
| 799 |
+
f" {type(config.text_config)}."
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
if not isinstance(config.vision_config, BlipVisionConfig):
|
| 803 |
+
raise TypeError(
|
| 804 |
+
"config.vision_config is expected to be of type BlipVisionConfig but is of type"
|
| 805 |
+
f" {type(config.vision_config)}."
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
text_config = config.text_config
|
| 809 |
+
vision_config = config.vision_config
|
| 810 |
+
|
| 811 |
+
self.projection_dim = config.projection_dim
|
| 812 |
+
self.text_embed_dim = text_config.hidden_size
|
| 813 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 814 |
+
|
| 815 |
+
self.text_model = TFBlipTextModel(text_config, name="text_model")
|
| 816 |
+
self.vision_model = TFBlipVisionModel(vision_config, name="vision_model")
|
| 817 |
+
|
| 818 |
+
self.visual_projection = keras.layers.Dense(
|
| 819 |
+
self.projection_dim,
|
| 820 |
+
use_bias=False,
|
| 821 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 822 |
+
name="visual_projection",
|
| 823 |
+
)
|
| 824 |
+
self.text_projection = keras.layers.Dense(
|
| 825 |
+
self.projection_dim,
|
| 826 |
+
use_bias=False,
|
| 827 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 828 |
+
name="text_projection",
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
self.config = config
|
| 832 |
+
|
| 833 |
+
def build(self, input_shape=None):
|
| 834 |
+
self.logit_scale = self.add_weight(
|
| 835 |
+
name="logit_scale",
|
| 836 |
+
shape=[],
|
| 837 |
+
initializer=keras.initializers.Constant(self.config.logit_scale_init_value),
|
| 838 |
+
trainable=True,
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
if self.built:
|
| 842 |
+
return
|
| 843 |
+
self.built = True
|
| 844 |
+
if getattr(self, "text_model", None) is not None:
|
| 845 |
+
with tf.name_scope(self.text_model.name):
|
| 846 |
+
self.text_model.build(None)
|
| 847 |
+
if getattr(self, "vision_model", None) is not None:
|
| 848 |
+
with tf.name_scope(self.vision_model.name):
|
| 849 |
+
self.vision_model.build(None)
|
| 850 |
+
if getattr(self, "visual_projection", None) is not None:
|
| 851 |
+
with tf.name_scope(self.visual_projection.name):
|
| 852 |
+
self.visual_projection.build([None, None, self.vision_embed_dim])
|
| 853 |
+
if getattr(self, "text_projection", None) is not None:
|
| 854 |
+
with tf.name_scope(self.text_projection.name):
|
| 855 |
+
self.text_projection.build([None, None, self.text_embed_dim])
|
| 856 |
+
|
| 857 |
+
@unpack_inputs
|
| 858 |
+
def call(
|
| 859 |
+
self,
|
| 860 |
+
input_ids: tf.Tensor | None = None,
|
| 861 |
+
pixel_values: tf.Tensor | None = None,
|
| 862 |
+
attention_mask: tf.Tensor | None = None,
|
| 863 |
+
position_ids: tf.Tensor | None = None,
|
| 864 |
+
return_loss: Optional[bool] = None,
|
| 865 |
+
output_attentions: Optional[bool] = None,
|
| 866 |
+
output_hidden_states: Optional[bool] = None,
|
| 867 |
+
return_dict: Optional[bool] = None,
|
| 868 |
+
training: Optional[bool] = None,
|
| 869 |
+
) -> Union[Tuple, TFBlipOutput]:
|
| 870 |
+
# Use BLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 871 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 872 |
+
output_hidden_states = (
|
| 873 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 874 |
+
)
|
| 875 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 876 |
+
|
| 877 |
+
vision_outputs = self.vision_model(
|
| 878 |
+
pixel_values=pixel_values,
|
| 879 |
+
output_attentions=output_attentions,
|
| 880 |
+
output_hidden_states=output_hidden_states,
|
| 881 |
+
return_dict=return_dict,
|
| 882 |
+
training=training,
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
text_outputs = self.text_model(
|
| 886 |
+
input_ids=input_ids,
|
| 887 |
+
attention_mask=attention_mask,
|
| 888 |
+
position_ids=position_ids,
|
| 889 |
+
output_attentions=output_attentions,
|
| 890 |
+
output_hidden_states=output_hidden_states,
|
| 891 |
+
return_dict=return_dict,
|
| 892 |
+
training=training,
|
| 893 |
+
)
|
| 894 |
+
|
| 895 |
+
image_embeds = vision_outputs[1]
|
| 896 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 897 |
+
|
| 898 |
+
text_embeds = text_outputs[1]
|
| 899 |
+
text_embeds = self.text_projection(text_embeds)
|
| 900 |
+
|
| 901 |
+
# normalized features
|
| 902 |
+
image_embeds = image_embeds / tf.norm(image_embeds, ord=2, axis=-1, keepdims=True)
|
| 903 |
+
text_embeds = text_embeds / tf.norm(text_embeds, ord=2, axis=-1, keepdims=True)
|
| 904 |
+
|
| 905 |
+
# cosine similarity as logits
|
| 906 |
+
logit_scale = tf.exp(self.logit_scale)
|
| 907 |
+
logits_per_text = tf.matmul(text_embeds, image_embeds, transpose_b=True) * logit_scale
|
| 908 |
+
logits_per_image = tf.transpose(logits_per_text)
|
| 909 |
+
|
| 910 |
+
loss = None
|
| 911 |
+
if return_loss:
|
| 912 |
+
loss = blip_loss(logits_per_text)
|
| 913 |
+
loss = tf.reshape(loss, (1,))
|
| 914 |
+
|
| 915 |
+
if not return_dict:
|
| 916 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 917 |
+
return ((loss,) + output) if loss is not None else output
|
| 918 |
+
|
| 919 |
+
return TFBlipOutput(
|
| 920 |
+
loss=loss,
|
| 921 |
+
logits_per_image=logits_per_image,
|
| 922 |
+
logits_per_text=logits_per_text,
|
| 923 |
+
text_embeds=text_embeds,
|
| 924 |
+
image_embeds=image_embeds,
|
| 925 |
+
text_model_output=text_outputs,
|
| 926 |
+
vision_model_output=vision_outputs,
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
class TFBlipModel(TFBlipPreTrainedModel):
|
| 931 |
+
config_class = BlipConfig
|
| 932 |
+
_keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
|
| 933 |
+
main_input_name = "input_ids"
|
| 934 |
+
|
| 935 |
+
def __init__(self, config: BlipConfig, *inputs, **kwargs):
|
| 936 |
+
super().__init__(config, *inputs, **kwargs)
|
| 937 |
+
|
| 938 |
+
self.blip = TFBlipMainLayer(config, name="blip")
|
| 939 |
+
|
| 940 |
+
def serving_output(self, output: TFBlipOutput) -> TFBlipOutput:
|
| 941 |
+
return TFBlipOutput(
|
| 942 |
+
logits_per_image=output.logits_per_image,
|
| 943 |
+
logits_per_text=output.logits_per_text,
|
| 944 |
+
text_embeds=output.text_embeds,
|
| 945 |
+
image_embeds=output.image_embeds,
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
@unpack_inputs
|
| 949 |
+
@add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
|
| 950 |
+
@replace_return_docstrings(output_type=TFBlipOutput, config_class=BlipConfig)
|
| 951 |
+
def call(
|
| 952 |
+
self,
|
| 953 |
+
input_ids: tf.Tensor | None = None,
|
| 954 |
+
pixel_values: tf.Tensor | None = None,
|
| 955 |
+
attention_mask: tf.Tensor | None = None,
|
| 956 |
+
position_ids: tf.Tensor | None = None,
|
| 957 |
+
return_loss: Optional[bool] = None,
|
| 958 |
+
output_attentions: Optional[bool] = None,
|
| 959 |
+
output_hidden_states: Optional[bool] = None,
|
| 960 |
+
return_dict: Optional[bool] = None,
|
| 961 |
+
training: Optional[bool] = None,
|
| 962 |
+
) -> Union[Tuple, TFBlipOutput]:
|
| 963 |
+
r"""
|
| 964 |
+
Returns:
|
| 965 |
+
|
| 966 |
+
Examples:
|
| 967 |
+
|
| 968 |
+
```python
|
| 969 |
+
>>> from PIL import Image
|
| 970 |
+
>>> import requests
|
| 971 |
+
>>> from transformers import AutoProcessor, TFBlipModel
|
| 972 |
+
|
| 973 |
+
>>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 974 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 975 |
+
|
| 976 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 977 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 978 |
+
|
| 979 |
+
>>> inputs = processor(
|
| 980 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="tf", padding=True
|
| 981 |
+
... )
|
| 982 |
+
|
| 983 |
+
>>> outputs = model(**inputs)
|
| 984 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 985 |
+
>>> probs = tf.nn.softmax(logits_per_image, axis=1) # we can take the softmax to get the label probabilities
|
| 986 |
+
```"""
|
| 987 |
+
outputs = self.blip(
|
| 988 |
+
input_ids=input_ids,
|
| 989 |
+
pixel_values=pixel_values,
|
| 990 |
+
attention_mask=attention_mask,
|
| 991 |
+
position_ids=position_ids,
|
| 992 |
+
return_loss=return_loss,
|
| 993 |
+
output_attentions=output_attentions,
|
| 994 |
+
output_hidden_states=output_hidden_states,
|
| 995 |
+
return_dict=return_dict,
|
| 996 |
+
training=training,
|
| 997 |
+
)
|
| 998 |
+
return outputs
|
| 999 |
+
|
| 1000 |
+
@add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
|
| 1001 |
+
def get_text_features(
|
| 1002 |
+
self,
|
| 1003 |
+
input_ids: tf.Tensor | None = None,
|
| 1004 |
+
attention_mask: tf.Tensor | None = None,
|
| 1005 |
+
position_ids: tf.Tensor | None = None,
|
| 1006 |
+
return_dict: Optional[bool] = None,
|
| 1007 |
+
) -> tf.Tensor:
|
| 1008 |
+
r"""
|
| 1009 |
+
Returns:
|
| 1010 |
+
text_features (`tf.Tensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying
|
| 1011 |
+
the projection layer to the pooled output of [`TFBlipTextModel`].
|
| 1012 |
+
|
| 1013 |
+
Examples:
|
| 1014 |
+
|
| 1015 |
+
```python
|
| 1016 |
+
>>> from transformers import AutoProcessor, TFBlipModel
|
| 1017 |
+
|
| 1018 |
+
>>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1019 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1020 |
+
|
| 1021 |
+
>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="tf")
|
| 1022 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1023 |
+
```"""
|
| 1024 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1025 |
+
|
| 1026 |
+
text_outputs = self.blip.text_model(
|
| 1027 |
+
input_ids=input_ids,
|
| 1028 |
+
attention_mask=attention_mask,
|
| 1029 |
+
position_ids=position_ids,
|
| 1030 |
+
return_dict=return_dict,
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
pooled_output = text_outputs[1]
|
| 1034 |
+
text_features = self.blip.text_projection(pooled_output)
|
| 1035 |
+
|
| 1036 |
+
return text_features
|
| 1037 |
+
|
| 1038 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 1039 |
+
def get_image_features(
|
| 1040 |
+
self,
|
| 1041 |
+
pixel_values: tf.Tensor | None = None,
|
| 1042 |
+
return_dict: Optional[bool] = None,
|
| 1043 |
+
) -> tf.Tensor:
|
| 1044 |
+
r"""
|
| 1045 |
+
Returns:
|
| 1046 |
+
image_features (`tf.Tensor` of shape `(batch_size, output_dim`): The image embeddings obtained by applying
|
| 1047 |
+
the projection layer to the pooled output of [`TFBlipVisionModel`].
|
| 1048 |
+
|
| 1049 |
+
Examples:
|
| 1050 |
+
|
| 1051 |
+
```python
|
| 1052 |
+
>>> from PIL import Image
|
| 1053 |
+
>>> import requests
|
| 1054 |
+
>>> from transformers import AutoProcessor, TFBlipModel
|
| 1055 |
+
|
| 1056 |
+
>>> model = TFBlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1057 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1058 |
+
|
| 1059 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1060 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1061 |
+
|
| 1062 |
+
>>> inputs = processor(images=image, return_tensors="tf")
|
| 1063 |
+
|
| 1064 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1065 |
+
```"""
|
| 1066 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1067 |
+
|
| 1068 |
+
vision_outputs = self.blip.vision_model(pixel_values=pixel_values, return_dict=return_dict)
|
| 1069 |
+
|
| 1070 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1071 |
+
image_features = self.blip.visual_projection(pooled_output)
|
| 1072 |
+
|
| 1073 |
+
return image_features
|
| 1074 |
+
|
| 1075 |
+
def build(self, input_shape=None):
|
| 1076 |
+
if self.built:
|
| 1077 |
+
return
|
| 1078 |
+
self.built = True
|
| 1079 |
+
if getattr(self, "blip", None) is not None:
|
| 1080 |
+
with tf.name_scope(self.blip.name):
|
| 1081 |
+
self.blip.build(None)
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
@add_start_docstrings(
|
| 1085 |
+
"""
|
| 1086 |
+
BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
|
| 1087 |
+
`input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
|
| 1088 |
+
the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
|
| 1089 |
+
from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
|
| 1090 |
+
""",
|
| 1091 |
+
BLIP_START_DOCSTRING,
|
| 1092 |
+
)
|
| 1093 |
+
class TFBlipForConditionalGeneration(TFBlipPreTrainedModel):
|
| 1094 |
+
config_class = BlipConfig
|
| 1095 |
+
_keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
|
| 1096 |
+
main_input_name = "pixel_values"
|
| 1097 |
+
|
| 1098 |
+
def __init__(self, config: BlipConfig, *args, **kwargs):
|
| 1099 |
+
super().__init__(config, *args, **kwargs)
|
| 1100 |
+
|
| 1101 |
+
self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
|
| 1102 |
+
|
| 1103 |
+
self.text_decoder = TFBlipTextLMHeadModel(config.text_config, name="text_decoder")
|
| 1104 |
+
|
| 1105 |
+
self.decoder_input_ids = config.text_config.bos_token_id
|
| 1106 |
+
self.decoder_pad_token_id = config.text_config.pad_token_id
|
| 1107 |
+
|
| 1108 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
| 1109 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1110 |
+
|
| 1111 |
+
@unpack_inputs
|
| 1112 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 1113 |
+
@replace_return_docstrings(output_type=TFBlipForConditionalGenerationModelOutput, config_class=BlipConfig)
|
| 1114 |
+
def call(
|
| 1115 |
+
self,
|
| 1116 |
+
pixel_values: tf.Tensor,
|
| 1117 |
+
input_ids: tf.Tensor | None = None,
|
| 1118 |
+
attention_mask: tf.Tensor | None = None,
|
| 1119 |
+
output_attentions: Optional[bool] = None,
|
| 1120 |
+
output_hidden_states: Optional[bool] = None,
|
| 1121 |
+
labels: tf.Tensor | None = None,
|
| 1122 |
+
return_dict: Optional[bool] = None,
|
| 1123 |
+
training: Optional[bool] = None,
|
| 1124 |
+
) -> Union[Tuple, TFBlipForConditionalGenerationModelOutput]:
|
| 1125 |
+
r"""
|
| 1126 |
+
Returns:
|
| 1127 |
+
|
| 1128 |
+
Examples:
|
| 1129 |
+
|
| 1130 |
+
```python
|
| 1131 |
+
>>> from PIL import Image
|
| 1132 |
+
>>> import requests
|
| 1133 |
+
>>> from transformers import AutoProcessor, TFBlipForConditionalGeneration
|
| 1134 |
+
|
| 1135 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1136 |
+
>>> model = TFBlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1137 |
+
|
| 1138 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1139 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1140 |
+
>>> text = "A picture of"
|
| 1141 |
+
|
| 1142 |
+
>>> inputs = processor(images=image, text=text, return_tensors="tf")
|
| 1143 |
+
|
| 1144 |
+
>>> outputs = model(**inputs)
|
| 1145 |
+
```"""
|
| 1146 |
+
|
| 1147 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1148 |
+
vision_outputs = self.vision_model(
|
| 1149 |
+
pixel_values=pixel_values,
|
| 1150 |
+
output_attentions=output_attentions,
|
| 1151 |
+
output_hidden_states=output_hidden_states,
|
| 1152 |
+
return_dict=return_dict,
|
| 1153 |
+
training=training,
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
image_embeds = vision_outputs[0]
|
| 1157 |
+
|
| 1158 |
+
outputs = self.text_decoder(
|
| 1159 |
+
input_ids=input_ids,
|
| 1160 |
+
attention_mask=attention_mask,
|
| 1161 |
+
encoder_hidden_states=image_embeds,
|
| 1162 |
+
labels=labels,
|
| 1163 |
+
return_dict=False,
|
| 1164 |
+
training=training,
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
if not return_dict:
|
| 1168 |
+
outputs = (outputs[0], outputs[1], image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
| 1169 |
+
return tuple(output for output in outputs if output is not None)
|
| 1170 |
+
|
| 1171 |
+
if labels is not None:
|
| 1172 |
+
loss = outputs[0]
|
| 1173 |
+
logits = outputs[1]
|
| 1174 |
+
else:
|
| 1175 |
+
loss = None
|
| 1176 |
+
logits = outputs[0]
|
| 1177 |
+
|
| 1178 |
+
if loss is not None and loss.shape.rank == 0:
|
| 1179 |
+
loss = tf.reshape(loss, (1,))
|
| 1180 |
+
|
| 1181 |
+
return TFBlipForConditionalGenerationModelOutput(
|
| 1182 |
+
loss=loss,
|
| 1183 |
+
logits=logits,
|
| 1184 |
+
image_embeds=image_embeds,
|
| 1185 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1186 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1187 |
+
attentions=vision_outputs.attentions,
|
| 1188 |
+
)
|
| 1189 |
+
|
| 1190 |
+
def generate(
|
| 1191 |
+
self,
|
| 1192 |
+
pixel_values: tf.Tensor,
|
| 1193 |
+
input_ids: tf.Tensor | None = None,
|
| 1194 |
+
attention_mask: tf.Tensor | None = None,
|
| 1195 |
+
**generate_kwargs,
|
| 1196 |
+
) -> tf.Tensor:
|
| 1197 |
+
r"""
|
| 1198 |
+
Overrides *generate* function to be able to use the model as a conditional generator
|
| 1199 |
+
|
| 1200 |
+
Parameters:
|
| 1201 |
+
pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
|
| 1202 |
+
Input image to be processed
|
| 1203 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1204 |
+
The sequence used as a prompt for the generation.
|
| 1205 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1206 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
Examples:
|
| 1210 |
+
```python
|
| 1211 |
+
>>> from PIL import Image
|
| 1212 |
+
>>> import requests
|
| 1213 |
+
>>> from transformers import AutoProcessor, TFBlipForConditionalGeneration
|
| 1214 |
+
|
| 1215 |
+
>>> model = TFBlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1216 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 1217 |
+
|
| 1218 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1219 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1220 |
+
|
| 1221 |
+
>>> inputs = processor(images=image, return_tensors="tf")
|
| 1222 |
+
|
| 1223 |
+
>>> outputs = model.generate(**inputs)
|
| 1224 |
+
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
|
| 1225 |
+
two cats sleeping on a couch
|
| 1226 |
+
```
|
| 1227 |
+
"""
|
| 1228 |
+
|
| 1229 |
+
batch_size = pixel_values.shape[0]
|
| 1230 |
+
vision_outputs = self.vision_model(pixel_values=pixel_values)
|
| 1231 |
+
|
| 1232 |
+
image_embeds = vision_outputs[0]
|
| 1233 |
+
|
| 1234 |
+
image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int32)
|
| 1235 |
+
|
| 1236 |
+
if isinstance(input_ids, list):
|
| 1237 |
+
input_ids = tf.convert_to_tensor(input_ids, dtype=tf.int32)
|
| 1238 |
+
elif input_ids is None:
|
| 1239 |
+
input_ids = tf.convert_to_tensor(
|
| 1240 |
+
[[self.decoder_input_ids, self.config.text_config.eos_token_id]], dtype=tf.int32
|
| 1241 |
+
)
|
| 1242 |
+
|
| 1243 |
+
input_ids = tf.tile(input_ids, (batch_size, 1))
|
| 1244 |
+
|
| 1245 |
+
# PyTorch: input_ids[:, 0] = self.config.text_config.bos_token_id
|
| 1246 |
+
input_ids = tf.concat(
|
| 1247 |
+
[tf.ones((batch_size, 1), dtype=tf.int32) * self.config.text_config.bos_token_id, input_ids[:, 1:]], axis=1
|
| 1248 |
+
)
|
| 1249 |
+
attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
|
| 1250 |
+
|
| 1251 |
+
outputs = self.text_decoder.generate(
|
| 1252 |
+
input_ids=input_ids[:, :-1],
|
| 1253 |
+
eos_token_id=self.config.text_config.sep_token_id,
|
| 1254 |
+
pad_token_id=self.config.text_config.pad_token_id,
|
| 1255 |
+
attention_mask=attention_mask,
|
| 1256 |
+
encoder_hidden_states=image_embeds,
|
| 1257 |
+
encoder_attention_mask=image_attention_mask,
|
| 1258 |
+
**generate_kwargs,
|
| 1259 |
+
)
|
| 1260 |
+
|
| 1261 |
+
return outputs
|
| 1262 |
+
|
| 1263 |
+
def build(self, input_shape=None):
|
| 1264 |
+
if self.built:
|
| 1265 |
+
return
|
| 1266 |
+
self.built = True
|
| 1267 |
+
if getattr(self, "vision_model", None) is not None:
|
| 1268 |
+
with tf.name_scope(self.vision_model.name):
|
| 1269 |
+
self.vision_model.build(None)
|
| 1270 |
+
if getattr(self, "text_decoder", None) is not None:
|
| 1271 |
+
with tf.name_scope(self.text_decoder.name):
|
| 1272 |
+
self.text_decoder.build(None)
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
@add_start_docstrings(
|
| 1276 |
+
"""
|
| 1277 |
+
BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
|
| 1278 |
+
decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
|
| 1279 |
+
with the encoding of the image, and the text decoder will output the answer to the question.
|
| 1280 |
+
""",
|
| 1281 |
+
BLIP_START_DOCSTRING,
|
| 1282 |
+
)
|
| 1283 |
+
class TFBlipForQuestionAnswering(TFBlipPreTrainedModel):
|
| 1284 |
+
config_class = BlipConfig
|
| 1285 |
+
_keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
|
| 1286 |
+
|
| 1287 |
+
def __init__(self, config: BlipConfig, *args, **kwargs):
|
| 1288 |
+
super().__init__(config, *args, **kwargs)
|
| 1289 |
+
|
| 1290 |
+
self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
|
| 1291 |
+
|
| 1292 |
+
self.text_encoder = TFBlipTextModel(config.text_config, name="text_encoder", add_pooling_layer=False)
|
| 1293 |
+
|
| 1294 |
+
self.text_decoder = TFBlipTextLMHeadModel(config.text_config, name="text_decoder")
|
| 1295 |
+
|
| 1296 |
+
self.decoder_pad_token_id = config.text_config.pad_token_id
|
| 1297 |
+
self.decoder_start_token_id = config.text_config.bos_token_id
|
| 1298 |
+
|
| 1299 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
| 1300 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1301 |
+
|
| 1302 |
+
# Adapted from transformers.models.t5.modeling_tf_t5.TFT5PreTrainedModel._shift_right
|
| 1303 |
+
def _shift_right(self, input_ids):
|
| 1304 |
+
decoder_start_token_id = self.decoder_start_token_id
|
| 1305 |
+
pad_token_id = self.decoder_pad_token_id
|
| 1306 |
+
|
| 1307 |
+
if decoder_start_token_id is None or pad_token_id is None:
|
| 1308 |
+
raise ValueError("decoder_start_token_id and pad_token_id must be defined!")
|
| 1309 |
+
|
| 1310 |
+
start_tokens = tf.fill((shape_list(input_ids)[0], 1), decoder_start_token_id)
|
| 1311 |
+
start_tokens = tf.cast(start_tokens, input_ids.dtype) # Ensure compatible dtypes for concatenation
|
| 1312 |
+
shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
|
| 1313 |
+
|
| 1314 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 1315 |
+
shifted_input_ids = tf.where(
|
| 1316 |
+
shifted_input_ids == -100,
|
| 1317 |
+
tf.cast(tf.fill(shape_list(shifted_input_ids), pad_token_id), shifted_input_ids.dtype),
|
| 1318 |
+
shifted_input_ids,
|
| 1319 |
+
)
|
| 1320 |
+
|
| 1321 |
+
# "Verify that `labels` has only positive values and -100"
|
| 1322 |
+
tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=shifted_input_ids.dtype))
|
| 1323 |
+
|
| 1324 |
+
return shifted_input_ids
|
| 1325 |
+
|
| 1326 |
+
@unpack_inputs
|
| 1327 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 1328 |
+
@replace_return_docstrings(output_type=TFBlipTextVisionModelOutput, config_class=BlipVisionConfig)
|
| 1329 |
+
def call(
|
| 1330 |
+
self,
|
| 1331 |
+
input_ids: tf.Tensor,
|
| 1332 |
+
pixel_values: tf.Tensor | None = None,
|
| 1333 |
+
decoder_input_ids: tf.Tensor | None = None,
|
| 1334 |
+
decoder_attention_mask: tf.Tensor | None = None,
|
| 1335 |
+
attention_mask: tf.Tensor | None = None,
|
| 1336 |
+
output_attentions: Optional[bool] = None,
|
| 1337 |
+
output_hidden_states: Optional[bool] = None,
|
| 1338 |
+
labels: tf.Tensor | None = None,
|
| 1339 |
+
return_dict: Optional[bool] = None,
|
| 1340 |
+
training: Optional[bool] = None,
|
| 1341 |
+
) -> Union[Tuple, TFBlipTextVisionModelOutput]:
|
| 1342 |
+
r"""
|
| 1343 |
+
Returns:
|
| 1344 |
+
|
| 1345 |
+
Examples:
|
| 1346 |
+
|
| 1347 |
+
```python
|
| 1348 |
+
>>> from PIL import Image
|
| 1349 |
+
>>> import requests
|
| 1350 |
+
>>> from transformers import AutoProcessor, TFBlipForQuestionAnswering
|
| 1351 |
+
|
| 1352 |
+
>>> model = TFBlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
|
| 1353 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
| 1354 |
+
|
| 1355 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1356 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1357 |
+
|
| 1358 |
+
>>> # training
|
| 1359 |
+
>>> text = "How many cats are in the picture?"
|
| 1360 |
+
>>> label = "2"
|
| 1361 |
+
>>> inputs = processor(images=image, text=text, return_tensors="tf")
|
| 1362 |
+
>>> labels = processor(text=label, return_tensors="tf").input_ids
|
| 1363 |
+
|
| 1364 |
+
>>> inputs["labels"] = labels
|
| 1365 |
+
>>> outputs = model(**inputs)
|
| 1366 |
+
>>> loss = outputs.loss
|
| 1367 |
+
|
| 1368 |
+
>>> # inference
|
| 1369 |
+
>>> text = "How many cats are in the picture?"
|
| 1370 |
+
>>> inputs = processor(images=image, text=text, return_tensors="tf")
|
| 1371 |
+
>>> outputs = model.generate(**inputs)
|
| 1372 |
+
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
|
| 1373 |
+
2
|
| 1374 |
+
```"""
|
| 1375 |
+
if labels is None and decoder_input_ids is None:
|
| 1376 |
+
raise ValueError(
|
| 1377 |
+
"Either `decoder_input_ids` or `labels` should be passed when calling"
|
| 1378 |
+
" `TFBlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
|
| 1379 |
+
" are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
|
| 1380 |
+
)
|
| 1381 |
+
|
| 1382 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1383 |
+
|
| 1384 |
+
vision_outputs = self.vision_model(
|
| 1385 |
+
pixel_values=pixel_values,
|
| 1386 |
+
output_attentions=output_attentions,
|
| 1387 |
+
output_hidden_states=output_hidden_states,
|
| 1388 |
+
return_dict=return_dict,
|
| 1389 |
+
training=training,
|
| 1390 |
+
)
|
| 1391 |
+
|
| 1392 |
+
image_embeds = vision_outputs[0]
|
| 1393 |
+
image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int64)
|
| 1394 |
+
|
| 1395 |
+
question_embeds = self.text_encoder(
|
| 1396 |
+
input_ids=input_ids,
|
| 1397 |
+
attention_mask=attention_mask,
|
| 1398 |
+
encoder_hidden_states=image_embeds,
|
| 1399 |
+
encoder_attention_mask=image_attention_mask,
|
| 1400 |
+
return_dict=return_dict,
|
| 1401 |
+
training=training,
|
| 1402 |
+
)
|
| 1403 |
+
|
| 1404 |
+
question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
|
| 1405 |
+
|
| 1406 |
+
if labels is not None and decoder_input_ids is None:
|
| 1407 |
+
# labels are already shifted right, see: https://github.com/huggingface/transformers/pull/23153
|
| 1408 |
+
decoder_input_ids = labels
|
| 1409 |
+
|
| 1410 |
+
answer_output = self.text_decoder(
|
| 1411 |
+
input_ids=decoder_input_ids,
|
| 1412 |
+
attention_mask=decoder_attention_mask,
|
| 1413 |
+
encoder_hidden_states=question_embeds,
|
| 1414 |
+
encoder_attention_mask=attention_mask,
|
| 1415 |
+
labels=labels,
|
| 1416 |
+
return_dict=return_dict,
|
| 1417 |
+
training=training,
|
| 1418 |
+
)
|
| 1419 |
+
|
| 1420 |
+
if labels is not None:
|
| 1421 |
+
decoder_loss = tf.reduce_mean(answer_output.loss) if return_dict else tf.reduce_mean(answer_output[0])
|
| 1422 |
+
else:
|
| 1423 |
+
decoder_loss = None
|
| 1424 |
+
|
| 1425 |
+
if not return_dict:
|
| 1426 |
+
outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
| 1427 |
+
return tuple(output for output in outputs if output is not None)
|
| 1428 |
+
|
| 1429 |
+
return TFBlipTextVisionModelOutput(
|
| 1430 |
+
loss=decoder_loss,
|
| 1431 |
+
image_embeds=image_embeds,
|
| 1432 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1433 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1434 |
+
attentions=vision_outputs.attentions,
|
| 1435 |
+
)
|
| 1436 |
+
|
| 1437 |
+
def generate(
|
| 1438 |
+
self,
|
| 1439 |
+
input_ids: tf.Tensor,
|
| 1440 |
+
pixel_values: tf.Tensor,
|
| 1441 |
+
attention_mask: tf.Tensor | None = None,
|
| 1442 |
+
**generate_kwargs,
|
| 1443 |
+
) -> tf.Tensor:
|
| 1444 |
+
r"""
|
| 1445 |
+
Overrides *generate* function to be able to use the model as a conditional generator
|
| 1446 |
+
|
| 1447 |
+
Parameters:
|
| 1448 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 1449 |
+
The sequence used as a prompt for the generation.
|
| 1450 |
+
pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, image_height, image_width)`:
|
| 1451 |
+
Input image to be processed
|
| 1452 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1453 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
|
| 1454 |
+
tokens that are NOT MASKED, `0` for MASKED tokens.
|
| 1455 |
+
generate_kwargs (dict, *optional*):
|
| 1456 |
+
Additional arguments passed to the `generate` function of the decoder
|
| 1457 |
+
|
| 1458 |
+
|
| 1459 |
+
Examples:
|
| 1460 |
+
```python
|
| 1461 |
+
>>> from PIL import Image
|
| 1462 |
+
>>> import requests
|
| 1463 |
+
>>> from transformers import AutoProcessor, TFBlipForQuestionAnswering
|
| 1464 |
+
|
| 1465 |
+
>>> model = TFBlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
|
| 1466 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
| 1467 |
+
|
| 1468 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1469 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1470 |
+
>>> text = "How many cats are in the picture?"
|
| 1471 |
+
|
| 1472 |
+
>>> inputs = processor(images=image, text=text, return_tensors="tf")
|
| 1473 |
+
|
| 1474 |
+
>>> outputs = model.generate(**inputs)
|
| 1475 |
+
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
|
| 1476 |
+
2
|
| 1477 |
+
```
|
| 1478 |
+
"""
|
| 1479 |
+
vision_outputs = self.vision_model(pixel_values=pixel_values)
|
| 1480 |
+
|
| 1481 |
+
image_embeds = vision_outputs[0]
|
| 1482 |
+
|
| 1483 |
+
image_attention_mask = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int32)
|
| 1484 |
+
|
| 1485 |
+
if isinstance(input_ids, list):
|
| 1486 |
+
input_ids = tf.Tensor(input_ids)
|
| 1487 |
+
|
| 1488 |
+
question_outputs = self.text_encoder(
|
| 1489 |
+
input_ids=input_ids,
|
| 1490 |
+
attention_mask=attention_mask,
|
| 1491 |
+
encoder_hidden_states=image_embeds,
|
| 1492 |
+
encoder_attention_mask=image_attention_mask,
|
| 1493 |
+
return_dict=False,
|
| 1494 |
+
)
|
| 1495 |
+
|
| 1496 |
+
question_embeds = question_outputs[0]
|
| 1497 |
+
|
| 1498 |
+
question_attention_mask = tf.ones(shape_list(question_embeds)[:-1], dtype=tf.int32)
|
| 1499 |
+
|
| 1500 |
+
bos_ids = tf.fill(
|
| 1501 |
+
(tf.shape(question_embeds)[0], 1), value=tf.cast(self.decoder_start_token_id, input_ids.dtype)
|
| 1502 |
+
)
|
| 1503 |
+
|
| 1504 |
+
outputs = self.text_decoder.generate(
|
| 1505 |
+
input_ids=bos_ids,
|
| 1506 |
+
eos_token_id=self.config.text_config.sep_token_id,
|
| 1507 |
+
pad_token_id=self.config.text_config.pad_token_id,
|
| 1508 |
+
encoder_hidden_states=question_embeds,
|
| 1509 |
+
encoder_attention_mask=question_attention_mask,
|
| 1510 |
+
**generate_kwargs,
|
| 1511 |
+
)
|
| 1512 |
+
|
| 1513 |
+
return outputs
|
| 1514 |
+
|
| 1515 |
+
def build(self, input_shape=None):
|
| 1516 |
+
if self.built:
|
| 1517 |
+
return
|
| 1518 |
+
self.built = True
|
| 1519 |
+
if getattr(self, "vision_model", None) is not None:
|
| 1520 |
+
with tf.name_scope(self.vision_model.name):
|
| 1521 |
+
self.vision_model.build(None)
|
| 1522 |
+
if getattr(self, "text_encoder", None) is not None:
|
| 1523 |
+
with tf.name_scope(self.text_encoder.name):
|
| 1524 |
+
self.text_encoder.build(None)
|
| 1525 |
+
if getattr(self, "text_decoder", None) is not None:
|
| 1526 |
+
with tf.name_scope(self.text_decoder.name):
|
| 1527 |
+
self.text_decoder.build(None)
|
| 1528 |
+
|
| 1529 |
+
|
| 1530 |
+
@add_start_docstrings(
|
| 1531 |
+
"""
|
| 1532 |
+
BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
|
| 1533 |
+
image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
|
| 1534 |
+
the image.
|
| 1535 |
+
""",
|
| 1536 |
+
BLIP_START_DOCSTRING,
|
| 1537 |
+
)
|
| 1538 |
+
class TFBlipForImageTextRetrieval(TFBlipPreTrainedModel):
|
| 1539 |
+
config_class = BlipConfig
|
| 1540 |
+
|
| 1541 |
+
def __init__(self, config: BlipConfig, *args, **kwargs):
|
| 1542 |
+
super().__init__(config, *args, **kwargs)
|
| 1543 |
+
|
| 1544 |
+
self.vision_model = TFBlipVisionModel(config.vision_config, name="vision_model")
|
| 1545 |
+
|
| 1546 |
+
self.text_encoder = TFBlipTextModel(config.text_config, name="text_encoder", add_pooling_layer=False)
|
| 1547 |
+
|
| 1548 |
+
# vision projection layer
|
| 1549 |
+
self.vision_proj = keras.layers.Dense(
|
| 1550 |
+
config.image_text_hidden_size,
|
| 1551 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1552 |
+
name="vision_proj",
|
| 1553 |
+
)
|
| 1554 |
+
|
| 1555 |
+
# text projection layer
|
| 1556 |
+
self.text_proj = keras.layers.Dense(
|
| 1557 |
+
config.image_text_hidden_size,
|
| 1558 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 1559 |
+
name="text_proj",
|
| 1560 |
+
)
|
| 1561 |
+
|
| 1562 |
+
# image text matching head
|
| 1563 |
+
self.itm_head = keras.layers.Dense(
|
| 1564 |
+
2, kernel_initializer=get_initializer(config.initializer_range), name="itm_head"
|
| 1565 |
+
)
|
| 1566 |
+
|
| 1567 |
+
self.decoder_pad_token_id = (
|
| 1568 |
+
config.text_config.pad_token_id
|
| 1569 |
+
if not hasattr(config, "decoder_pad_token_id")
|
| 1570 |
+
else config.decoder_pad_token_id
|
| 1571 |
+
)
|
| 1572 |
+
self.decoder_start_token_id = (
|
| 1573 |
+
config.text_config.bos_token_id
|
| 1574 |
+
if not hasattr(config, "decoder_start_token_id")
|
| 1575 |
+
else config.decoder_start_token_id
|
| 1576 |
+
)
|
| 1577 |
+
self.config = config
|
| 1578 |
+
|
| 1579 |
+
def get_input_embeddings(self) -> keras.layers.Layer:
|
| 1580 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1581 |
+
|
| 1582 |
+
@unpack_inputs
|
| 1583 |
+
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
|
| 1584 |
+
@replace_return_docstrings(output_type=TFBlipImageTextMatchingModelOutput, config_class=BlipVisionConfig)
|
| 1585 |
+
def call(
|
| 1586 |
+
self,
|
| 1587 |
+
input_ids: tf.Tensor,
|
| 1588 |
+
pixel_values: tf.Tensor | None = None,
|
| 1589 |
+
use_itm_head: Optional[bool] = True,
|
| 1590 |
+
attention_mask: tf.Tensor | None = None,
|
| 1591 |
+
output_attentions: Optional[bool] = None,
|
| 1592 |
+
output_hidden_states: Optional[bool] = None,
|
| 1593 |
+
return_dict: Optional[bool] = None,
|
| 1594 |
+
training: Optional[bool] = None,
|
| 1595 |
+
) -> Union[Tuple, TFBlipImageTextMatchingModelOutput]:
|
| 1596 |
+
r"""
|
| 1597 |
+
Returns:
|
| 1598 |
+
|
| 1599 |
+
Examples:
|
| 1600 |
+
|
| 1601 |
+
```python
|
| 1602 |
+
>>> from PIL import Image
|
| 1603 |
+
>>> import requests
|
| 1604 |
+
>>> from transformers import AutoProcessor, TFBlipForImageTextRetrieval
|
| 1605 |
+
|
| 1606 |
+
>>> model = TFBlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
|
| 1607 |
+
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
|
| 1608 |
+
|
| 1609 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1610 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1611 |
+
>>> text = "an image of a cat"
|
| 1612 |
+
|
| 1613 |
+
>>> inputs = processor(images=image, text=text, return_tensors="tf")
|
| 1614 |
+
>>> outputs = model(**inputs)
|
| 1615 |
+
```
|
| 1616 |
+
"""
|
| 1617 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1618 |
+
|
| 1619 |
+
vision_outputs = self.vision_model(
|
| 1620 |
+
pixel_values=pixel_values,
|
| 1621 |
+
output_attentions=output_attentions,
|
| 1622 |
+
output_hidden_states=output_hidden_states,
|
| 1623 |
+
return_dict=return_dict,
|
| 1624 |
+
training=training,
|
| 1625 |
+
)
|
| 1626 |
+
|
| 1627 |
+
image_embeds = vision_outputs[0]
|
| 1628 |
+
image_atts = tf.ones(shape_list(image_embeds)[:-1], dtype=tf.int64)
|
| 1629 |
+
|
| 1630 |
+
# Matt: In PyTorch, only one path (itm/non-itm) is taken. However, in TensorFlow this can result in
|
| 1631 |
+
# some layers not being built! To avoid this, we always call both paths, then use an if statement to select
|
| 1632 |
+
# which output to pass to the final output. The unnecessary nodes will be pruned from the final graph, but
|
| 1633 |
+
# not before the layers have all been built correctly.
|
| 1634 |
+
itm_question_embeds = self.text_encoder(
|
| 1635 |
+
input_ids=input_ids,
|
| 1636 |
+
attention_mask=attention_mask,
|
| 1637 |
+
encoder_hidden_states=image_embeds,
|
| 1638 |
+
encoder_attention_mask=image_atts,
|
| 1639 |
+
return_dict=return_dict,
|
| 1640 |
+
training=training,
|
| 1641 |
+
)
|
| 1642 |
+
itm_question_embeds = itm_question_embeds[0] if not return_dict else itm_question_embeds.last_hidden_state
|
| 1643 |
+
|
| 1644 |
+
itm_output = self.itm_head(itm_question_embeds[:, 0, :])
|
| 1645 |
+
|
| 1646 |
+
no_itm_question_embeds = self.text_encoder(
|
| 1647 |
+
input_ids=input_ids,
|
| 1648 |
+
attention_mask=attention_mask,
|
| 1649 |
+
return_dict=return_dict,
|
| 1650 |
+
training=training,
|
| 1651 |
+
)
|
| 1652 |
+
no_itm_question_embeds = (
|
| 1653 |
+
no_itm_question_embeds[0] if not return_dict else no_itm_question_embeds.last_hidden_state
|
| 1654 |
+
)
|
| 1655 |
+
|
| 1656 |
+
image_feat, _ = tf.linalg.normalize(self.vision_proj(image_embeds[:, 0, :]), ord=2, axis=-1)
|
| 1657 |
+
text_feat, _ = tf.linalg.normalize(self.text_proj(no_itm_question_embeds[:, 0, :]), ord=2, axis=-1)
|
| 1658 |
+
|
| 1659 |
+
no_itm_output = tf.matmul(image_feat, text_feat, transpose_b=True)
|
| 1660 |
+
|
| 1661 |
+
if use_itm_head:
|
| 1662 |
+
output = itm_output
|
| 1663 |
+
question_embeds = itm_question_embeds
|
| 1664 |
+
else:
|
| 1665 |
+
output = no_itm_output
|
| 1666 |
+
question_embeds = no_itm_question_embeds
|
| 1667 |
+
|
| 1668 |
+
if not return_dict:
|
| 1669 |
+
outputs = (output, vision_outputs[0]) + vision_outputs[2:] + (question_embeds,)
|
| 1670 |
+
return tuple(output for output in outputs if output is not None)
|
| 1671 |
+
|
| 1672 |
+
return TFBlipImageTextMatchingModelOutput(
|
| 1673 |
+
itm_score=output,
|
| 1674 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1675 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1676 |
+
attentions=vision_outputs.attentions,
|
| 1677 |
+
question_embeds=question_embeds,
|
| 1678 |
+
)
|
| 1679 |
+
|
| 1680 |
+
def build(self, input_shape=None):
|
| 1681 |
+
if self.built:
|
| 1682 |
+
return
|
| 1683 |
+
self.built = True
|
| 1684 |
+
if getattr(self, "vision_model", None) is not None:
|
| 1685 |
+
with tf.name_scope(self.vision_model.name):
|
| 1686 |
+
self.vision_model.build(None)
|
| 1687 |
+
if getattr(self, "text_encoder", None) is not None:
|
| 1688 |
+
with tf.name_scope(self.text_encoder.name):
|
| 1689 |
+
self.text_encoder.build(None)
|
| 1690 |
+
if getattr(self, "vision_proj", None) is not None:
|
| 1691 |
+
with tf.name_scope(self.vision_proj.name):
|
| 1692 |
+
self.vision_proj.build([None, None, self.config.vision_config.hidden_size])
|
| 1693 |
+
if getattr(self, "text_proj", None) is not None:
|
| 1694 |
+
with tf.name_scope(self.text_proj.name):
|
| 1695 |
+
self.text_proj.build([None, None, self.config.text_config.hidden_size])
|
| 1696 |
+
if getattr(self, "itm_head", None) is not None:
|
| 1697 |
+
with tf.name_scope(self.itm_head.name):
|
| 1698 |
+
self.itm_head.build([None, None, self.config.text_config.hidden_size])
|
| 1699 |
+
|
| 1700 |
+
|
| 1701 |
+
__all__ = [
|
| 1702 |
+
"TFBlipModel",
|
| 1703 |
+
"TFBlipPreTrainedModel",
|
| 1704 |
+
"TFBlipForConditionalGeneration",
|
| 1705 |
+
"TFBlipForQuestionAnswering",
|
| 1706 |
+
"TFBlipVisionModel",
|
| 1707 |
+
"TFBlipTextModel",
|
| 1708 |
+
"TFBlipForImageTextRetrieval",
|
| 1709 |
+
]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/modeling_tf_blip_text.py
ADDED
|
@@ -0,0 +1,1122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the BSD-3-clause license (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 |
+
# https://opensource.org/licenses/BSD-3-Clause
|
| 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 __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from typing import Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...modeling_tf_outputs import (
|
| 25 |
+
TFBaseModelOutputWithPastAndCrossAttentions,
|
| 26 |
+
TFBaseModelOutputWithPoolingAndCrossAttentions,
|
| 27 |
+
TFCausalLMOutputWithCrossAttentions,
|
| 28 |
+
)
|
| 29 |
+
from ...modeling_tf_utils import (
|
| 30 |
+
TFModelInputType,
|
| 31 |
+
TFPreTrainedModel,
|
| 32 |
+
get_initializer,
|
| 33 |
+
get_tf_activation,
|
| 34 |
+
keras,
|
| 35 |
+
keras_serializable,
|
| 36 |
+
shape_list,
|
| 37 |
+
unpack_inputs,
|
| 38 |
+
)
|
| 39 |
+
from ...tf_utils import check_embeddings_within_bounds, invert_attention_mask, stable_softmax
|
| 40 |
+
from ...utils import add_start_docstrings_to_model_forward, logging
|
| 41 |
+
from .configuration_blip import BlipTextConfig
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
BLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 47 |
+
Args:
|
| 48 |
+
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
|
| 49 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 50 |
+
it.
|
| 51 |
+
|
| 52 |
+
Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
|
| 53 |
+
|
| 54 |
+
[What are input IDs?](../glossary#input-ids)
|
| 55 |
+
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 56 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 57 |
+
|
| 58 |
+
- 1 for tokens that are **not masked**,
|
| 59 |
+
- 0 for tokens that are **masked**.
|
| 60 |
+
|
| 61 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 62 |
+
position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 63 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 64 |
+
config.max_position_embeddings - 1]`.
|
| 65 |
+
|
| 66 |
+
[What are position IDs?](../glossary#position-ids)
|
| 67 |
+
output_attentions (`bool`, *optional*):
|
| 68 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 69 |
+
tensors for more detail.
|
| 70 |
+
output_hidden_states (`bool`, *optional*):
|
| 71 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 72 |
+
more detail.
|
| 73 |
+
return_dict (`bool`, *optional*):
|
| 74 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
|
| 79 |
+
class TFBlipTextEmbeddings(keras.layers.Layer):
|
| 80 |
+
"""Construct the embeddings from word and position embeddings."""
|
| 81 |
+
|
| 82 |
+
def __init__(self, config, **kwargs):
|
| 83 |
+
super().__init__(**kwargs)
|
| 84 |
+
self.word_embeddings = keras.layers.Embedding(
|
| 85 |
+
config.vocab_size,
|
| 86 |
+
config.hidden_size,
|
| 87 |
+
embeddings_initializer=get_initializer(config.initializer_range),
|
| 88 |
+
name="word_embeddings",
|
| 89 |
+
)
|
| 90 |
+
self.position_embeddings = keras.layers.Embedding(
|
| 91 |
+
config.max_position_embeddings,
|
| 92 |
+
config.hidden_size,
|
| 93 |
+
embeddings_initializer=get_initializer(config.initializer_range),
|
| 94 |
+
name="position_embeddings",
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# self.LayerNorm is not snake-cased to stick with PyTorch model variable name and be able to load
|
| 98 |
+
# any TensorFlow checkpoint file
|
| 99 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 100 |
+
self.dropout = keras.layers.Dropout(config.hidden_dropout_prob, name="dropout")
|
| 101 |
+
|
| 102 |
+
self.position_ids = tf.expand_dims(tf.range(config.max_position_embeddings), 0)
|
| 103 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 104 |
+
|
| 105 |
+
self.config = config
|
| 106 |
+
|
| 107 |
+
def call(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0, training=None):
|
| 108 |
+
if input_ids is not None:
|
| 109 |
+
input_shape = tf.shape(input_ids)
|
| 110 |
+
else:
|
| 111 |
+
input_shape = tf.shape(inputs_embeds)[:-1]
|
| 112 |
+
|
| 113 |
+
seq_length = input_shape[1]
|
| 114 |
+
|
| 115 |
+
if position_ids is None:
|
| 116 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 117 |
+
|
| 118 |
+
if inputs_embeds is None:
|
| 119 |
+
check_embeddings_within_bounds(input_ids, self.config.vocab_size)
|
| 120 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 121 |
+
|
| 122 |
+
embeddings = inputs_embeds
|
| 123 |
+
|
| 124 |
+
if self.position_embedding_type == "absolute":
|
| 125 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 126 |
+
embeddings += position_embeddings
|
| 127 |
+
embeddings = self.LayerNorm(embeddings)
|
| 128 |
+
embeddings = self.dropout(embeddings, training=training)
|
| 129 |
+
return embeddings
|
| 130 |
+
|
| 131 |
+
def build(self, input_shape=None):
|
| 132 |
+
if self.built:
|
| 133 |
+
return
|
| 134 |
+
self.built = True
|
| 135 |
+
if getattr(self, "word_embeddings", None) is not None:
|
| 136 |
+
with tf.name_scope(self.word_embeddings.name):
|
| 137 |
+
self.word_embeddings.build(None)
|
| 138 |
+
if getattr(self, "position_embeddings", None) is not None:
|
| 139 |
+
with tf.name_scope(self.position_embeddings.name):
|
| 140 |
+
self.position_embeddings.build(None)
|
| 141 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 142 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 143 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 144 |
+
if getattr(self, "dropout", None) is not None:
|
| 145 |
+
with tf.name_scope(self.dropout.name):
|
| 146 |
+
self.dropout.build(None)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
|
| 150 |
+
class TFBlipTextSelfAttention(keras.layers.Layer):
|
| 151 |
+
def __init__(self, config, is_cross_attention, **kwargs):
|
| 152 |
+
super().__init__(**kwargs)
|
| 153 |
+
self.config = config
|
| 154 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 155 |
+
raise ValueError(
|
| 156 |
+
"The hidden size (%d) is not a multiple of the number of attention heads (%d)"
|
| 157 |
+
% (config.hidden_size, config.num_attention_heads)
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
self.num_attention_heads = config.num_attention_heads
|
| 161 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 162 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 163 |
+
|
| 164 |
+
self.query = keras.layers.Dense(
|
| 165 |
+
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
|
| 166 |
+
)
|
| 167 |
+
self.key = keras.layers.Dense(
|
| 168 |
+
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
|
| 169 |
+
)
|
| 170 |
+
self.value = keras.layers.Dense(
|
| 171 |
+
self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
self.dropout = keras.layers.Dropout(config.attention_probs_dropout_prob)
|
| 175 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
| 176 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 177 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 178 |
+
self.distance_embedding = keras.layers.Embedding(
|
| 179 |
+
2 * config.max_position_embeddings - 1, self.attention_head_size
|
| 180 |
+
)
|
| 181 |
+
self.is_cross_attention = is_cross_attention
|
| 182 |
+
|
| 183 |
+
def transpose_for_scores(self, x):
|
| 184 |
+
new_x_shape = tf.concat(
|
| 185 |
+
[tf.shape(x)[:-1], tf.constant([self.num_attention_heads, self.attention_head_size], dtype=tf.int32)],
|
| 186 |
+
axis=0,
|
| 187 |
+
)
|
| 188 |
+
x = tf.reshape(x, new_x_shape)
|
| 189 |
+
return tf.transpose(x, perm=(0, 2, 1, 3))
|
| 190 |
+
|
| 191 |
+
def call(
|
| 192 |
+
self,
|
| 193 |
+
hidden_states,
|
| 194 |
+
attention_mask=None,
|
| 195 |
+
head_mask=None,
|
| 196 |
+
encoder_hidden_states=None,
|
| 197 |
+
encoder_attention_mask=None,
|
| 198 |
+
past_key_value=None,
|
| 199 |
+
output_attentions=False,
|
| 200 |
+
training=None,
|
| 201 |
+
):
|
| 202 |
+
mixed_query_layer = self.query(hidden_states)
|
| 203 |
+
|
| 204 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 205 |
+
# and values come from an encoder; the attention mask needs to be
|
| 206 |
+
# such that the encoder's padding tokens are not attended to.
|
| 207 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 208 |
+
|
| 209 |
+
if is_cross_attention:
|
| 210 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 211 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 212 |
+
attention_mask = encoder_attention_mask
|
| 213 |
+
elif past_key_value is not None:
|
| 214 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 215 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 216 |
+
key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
|
| 217 |
+
value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
|
| 218 |
+
else:
|
| 219 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 220 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 221 |
+
|
| 222 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 223 |
+
|
| 224 |
+
past_key_value = (key_layer, value_layer)
|
| 225 |
+
|
| 226 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 227 |
+
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
|
| 228 |
+
|
| 229 |
+
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
|
| 230 |
+
seq_length = shape_list(hidden_states)[1]
|
| 231 |
+
position_ids_l = tf.expand_dims(tf.range(seq_length, dtype=tf.int64, device=hidden_states.device), 1)
|
| 232 |
+
position_ids_r = tf.expand_dims(tf.range(seq_length, dtype=tf.int64, device=hidden_states.device), 0)
|
| 233 |
+
distance = position_ids_l - position_ids_r
|
| 234 |
+
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
|
| 235 |
+
positional_embedding = tf.cast(positional_embedding, query_layer.dtype) # fp16 compatibility
|
| 236 |
+
|
| 237 |
+
if self.position_embedding_type == "relative_key":
|
| 238 |
+
relative_position_scores = tf.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 239 |
+
attention_scores = attention_scores + relative_position_scores
|
| 240 |
+
elif self.position_embedding_type == "relative_key_query":
|
| 241 |
+
relative_position_scores_query = tf.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
|
| 242 |
+
relative_position_scores_key = tf.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
|
| 243 |
+
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
|
| 244 |
+
|
| 245 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 246 |
+
if attention_mask is not None:
|
| 247 |
+
# Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
|
| 248 |
+
attention_scores = attention_scores + tf.cast(attention_mask, attention_scores.dtype)
|
| 249 |
+
|
| 250 |
+
# Normalize the attention scores to probabilities.
|
| 251 |
+
attention_probs = stable_softmax(attention_scores, axis=-1)
|
| 252 |
+
|
| 253 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 254 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 255 |
+
attention_probs_dropped = self.dropout(attention_probs, training=training)
|
| 256 |
+
|
| 257 |
+
# Mask heads if we want to
|
| 258 |
+
if head_mask is not None:
|
| 259 |
+
attention_probs_dropped = attention_probs_dropped * head_mask
|
| 260 |
+
|
| 261 |
+
context_layer = attention_probs_dropped @ value_layer
|
| 262 |
+
|
| 263 |
+
context_layer = tf.transpose(context_layer, perm=(0, 2, 1, 3))
|
| 264 |
+
new_context_layer_shape = shape_list(context_layer)[:-2] + [self.all_head_size]
|
| 265 |
+
context_layer = tf.reshape(context_layer, new_context_layer_shape)
|
| 266 |
+
|
| 267 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 268 |
+
|
| 269 |
+
outputs = outputs + (past_key_value,)
|
| 270 |
+
return outputs
|
| 271 |
+
|
| 272 |
+
def build(self, input_shape=None):
|
| 273 |
+
if self.built:
|
| 274 |
+
return
|
| 275 |
+
self.built = True
|
| 276 |
+
if getattr(self, "query", None) is not None:
|
| 277 |
+
with tf.name_scope(self.query.name):
|
| 278 |
+
self.query.build([None, None, self.config.hidden_size])
|
| 279 |
+
if self.is_cross_attention:
|
| 280 |
+
if getattr(self, "key", None) is not None:
|
| 281 |
+
with tf.name_scope(self.key.name):
|
| 282 |
+
self.key.build([None, None, self.config.encoder_hidden_size])
|
| 283 |
+
if getattr(self, "value", None) is not None:
|
| 284 |
+
with tf.name_scope(self.value.name):
|
| 285 |
+
self.value.build([None, None, self.config.encoder_hidden_size])
|
| 286 |
+
else:
|
| 287 |
+
if getattr(self, "key", None) is not None:
|
| 288 |
+
with tf.name_scope(self.key.name):
|
| 289 |
+
self.key.build([None, None, self.config.hidden_size])
|
| 290 |
+
if getattr(self, "value", None) is not None:
|
| 291 |
+
with tf.name_scope(self.value.name):
|
| 292 |
+
self.value.build([None, None, self.config.hidden_size])
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class TFBlipTextSelfOutput(keras.layers.Layer):
|
| 296 |
+
def __init__(self, config: BlipTextConfig, **kwargs):
|
| 297 |
+
super().__init__(**kwargs)
|
| 298 |
+
|
| 299 |
+
self.dense = keras.layers.Dense(
|
| 300 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 301 |
+
)
|
| 302 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 303 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 304 |
+
self.config = config
|
| 305 |
+
|
| 306 |
+
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: Optional[bool] = None) -> tf.Tensor:
|
| 307 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 308 |
+
hidden_states = self.dropout(inputs=hidden_states, training=training)
|
| 309 |
+
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 310 |
+
|
| 311 |
+
return hidden_states
|
| 312 |
+
|
| 313 |
+
def build(self, input_shape=None):
|
| 314 |
+
if self.built:
|
| 315 |
+
return
|
| 316 |
+
self.built = True
|
| 317 |
+
if getattr(self, "dense", None) is not None:
|
| 318 |
+
with tf.name_scope(self.dense.name):
|
| 319 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 320 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 321 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 322 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
|
| 326 |
+
class TFBlipTextAttention(keras.layers.Layer):
|
| 327 |
+
def __init__(self, config, is_cross_attention=False, **kwargs):
|
| 328 |
+
super().__init__(**kwargs)
|
| 329 |
+
self.self = TFBlipTextSelfAttention(config, is_cross_attention, name="self")
|
| 330 |
+
# "output" is a protected attribute on TF models
|
| 331 |
+
self.self_output = TFBlipTextSelfOutput(config, name="output")
|
| 332 |
+
|
| 333 |
+
def call(
|
| 334 |
+
self,
|
| 335 |
+
hidden_states: tf.Tensor,
|
| 336 |
+
attention_mask: tf.Tensor | None = None,
|
| 337 |
+
head_mask: tf.Tensor | None = None,
|
| 338 |
+
encoder_hidden_states: tf.Tensor | None = None,
|
| 339 |
+
encoder_attention_mask: tf.Tensor | None = None,
|
| 340 |
+
past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
|
| 341 |
+
output_attentions: Optional[bool] = False,
|
| 342 |
+
training: Optional[bool] = None,
|
| 343 |
+
):
|
| 344 |
+
self_outputs = self.self(
|
| 345 |
+
hidden_states,
|
| 346 |
+
attention_mask,
|
| 347 |
+
head_mask,
|
| 348 |
+
encoder_hidden_states,
|
| 349 |
+
encoder_attention_mask,
|
| 350 |
+
past_key_value,
|
| 351 |
+
output_attentions,
|
| 352 |
+
training=training,
|
| 353 |
+
)
|
| 354 |
+
attention_output = self.self_output(self_outputs[0], hidden_states, training=training)
|
| 355 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 356 |
+
return outputs
|
| 357 |
+
|
| 358 |
+
def build(self, input_shape=None):
|
| 359 |
+
if self.built:
|
| 360 |
+
return
|
| 361 |
+
self.built = True
|
| 362 |
+
if getattr(self, "self", None) is not None:
|
| 363 |
+
with tf.name_scope(self.self.name):
|
| 364 |
+
self.self.build(None)
|
| 365 |
+
if getattr(self, "self_output", None) is not None:
|
| 366 |
+
with tf.name_scope(self.self_output.name):
|
| 367 |
+
self.self_output.build(None)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->BlipText
|
| 371 |
+
class TFBlipTextIntermediate(keras.layers.Layer):
|
| 372 |
+
def __init__(self, config: BlipTextConfig, **kwargs):
|
| 373 |
+
super().__init__(**kwargs)
|
| 374 |
+
|
| 375 |
+
self.dense = keras.layers.Dense(
|
| 376 |
+
units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
if isinstance(config.hidden_act, str):
|
| 380 |
+
self.intermediate_act_fn = get_tf_activation(config.hidden_act)
|
| 381 |
+
else:
|
| 382 |
+
self.intermediate_act_fn = config.hidden_act
|
| 383 |
+
self.config = config
|
| 384 |
+
|
| 385 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 386 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 387 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
| 388 |
+
|
| 389 |
+
return hidden_states
|
| 390 |
+
|
| 391 |
+
def build(self, input_shape=None):
|
| 392 |
+
if self.built:
|
| 393 |
+
return
|
| 394 |
+
self.built = True
|
| 395 |
+
if getattr(self, "dense", None) is not None:
|
| 396 |
+
with tf.name_scope(self.dense.name):
|
| 397 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class TFBlipTextOutput(keras.layers.Layer):
|
| 401 |
+
def __init__(self, config: BlipTextConfig, **kwargs):
|
| 402 |
+
super().__init__(**kwargs)
|
| 403 |
+
|
| 404 |
+
self.dense = keras.layers.Dense(
|
| 405 |
+
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
|
| 406 |
+
)
|
| 407 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 408 |
+
self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
|
| 409 |
+
self.config = config
|
| 410 |
+
|
| 411 |
+
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
|
| 412 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 413 |
+
hidden_states = self.dropout(inputs=hidden_states, training=training)
|
| 414 |
+
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
|
| 415 |
+
|
| 416 |
+
return hidden_states
|
| 417 |
+
|
| 418 |
+
def build(self, input_shape=None):
|
| 419 |
+
if self.built:
|
| 420 |
+
return
|
| 421 |
+
self.built = True
|
| 422 |
+
if getattr(self, "dense", None) is not None:
|
| 423 |
+
with tf.name_scope(self.dense.name):
|
| 424 |
+
self.dense.build([None, None, self.config.intermediate_size])
|
| 425 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 426 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 427 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class TFBlipTextLayer(keras.layers.Layer):
|
| 431 |
+
def __init__(self, config, **kwargs):
|
| 432 |
+
super().__init__(**kwargs)
|
| 433 |
+
self.config = config
|
| 434 |
+
self.attention = TFBlipTextAttention(config, name="attention")
|
| 435 |
+
if self.config.is_decoder:
|
| 436 |
+
self.crossattention = TFBlipTextAttention(
|
| 437 |
+
config, is_cross_attention=self.config.is_decoder, name="crossattention"
|
| 438 |
+
)
|
| 439 |
+
self.intermediate = TFBlipTextIntermediate(config, name="intermediate")
|
| 440 |
+
self.self_output = TFBlipTextOutput(config, name="output")
|
| 441 |
+
|
| 442 |
+
def call(
|
| 443 |
+
self,
|
| 444 |
+
hidden_states,
|
| 445 |
+
attention_mask=None,
|
| 446 |
+
head_mask=None,
|
| 447 |
+
encoder_hidden_states=None,
|
| 448 |
+
encoder_attention_mask=None,
|
| 449 |
+
past_key_value=None,
|
| 450 |
+
output_attentions=False,
|
| 451 |
+
training=None,
|
| 452 |
+
):
|
| 453 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 454 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 455 |
+
self_attention_outputs = self.attention(
|
| 456 |
+
hidden_states,
|
| 457 |
+
attention_mask,
|
| 458 |
+
head_mask,
|
| 459 |
+
output_attentions=output_attentions,
|
| 460 |
+
past_key_value=self_attn_past_key_value,
|
| 461 |
+
training=training,
|
| 462 |
+
)
|
| 463 |
+
attention_output = self_attention_outputs[0]
|
| 464 |
+
|
| 465 |
+
outputs = self_attention_outputs[1:-1]
|
| 466 |
+
present_key_value = self_attention_outputs[-1]
|
| 467 |
+
|
| 468 |
+
if encoder_hidden_states is not None:
|
| 469 |
+
cross_attention_outputs = self.crossattention(
|
| 470 |
+
attention_output,
|
| 471 |
+
attention_mask,
|
| 472 |
+
head_mask,
|
| 473 |
+
encoder_hidden_states,
|
| 474 |
+
encoder_attention_mask,
|
| 475 |
+
output_attentions=output_attentions,
|
| 476 |
+
training=training,
|
| 477 |
+
)
|
| 478 |
+
attention_output = cross_attention_outputs[0]
|
| 479 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
| 480 |
+
intermediate_output = self.intermediate(attention_output)
|
| 481 |
+
layer_output = self.self_output(intermediate_output, attention_output, training=training)
|
| 482 |
+
outputs = (layer_output,) + outputs
|
| 483 |
+
|
| 484 |
+
outputs = outputs + (present_key_value,)
|
| 485 |
+
|
| 486 |
+
return outputs
|
| 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, "intermediate", None) is not None:
|
| 496 |
+
with tf.name_scope(self.intermediate.name):
|
| 497 |
+
self.intermediate.build(None)
|
| 498 |
+
if getattr(self, "self_output", None) is not None:
|
| 499 |
+
with tf.name_scope(self.self_output.name):
|
| 500 |
+
self.self_output.build(None)
|
| 501 |
+
if getattr(self, "crossattention", None) is not None:
|
| 502 |
+
with tf.name_scope(self.crossattention.name):
|
| 503 |
+
self.crossattention.build(None)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
|
| 507 |
+
@keras_serializable
|
| 508 |
+
class TFBlipTextEncoder(keras.layers.Layer):
|
| 509 |
+
config_class = BlipTextConfig
|
| 510 |
+
|
| 511 |
+
def __init__(self, config, name=None, **kwargs):
|
| 512 |
+
super().__init__(name=name, **kwargs)
|
| 513 |
+
self.config = config
|
| 514 |
+
self.layer = [TFBlipTextLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
|
| 515 |
+
|
| 516 |
+
@unpack_inputs
|
| 517 |
+
def call(
|
| 518 |
+
self,
|
| 519 |
+
hidden_states,
|
| 520 |
+
attention_mask=None,
|
| 521 |
+
head_mask=None,
|
| 522 |
+
encoder_hidden_states=None,
|
| 523 |
+
encoder_attention_mask=None,
|
| 524 |
+
past_key_values=None,
|
| 525 |
+
use_cache=None,
|
| 526 |
+
output_attentions=False,
|
| 527 |
+
output_hidden_states=False,
|
| 528 |
+
return_dict=True,
|
| 529 |
+
training=None,
|
| 530 |
+
):
|
| 531 |
+
all_hidden_states = () if output_hidden_states else None
|
| 532 |
+
all_self_attentions = () if output_attentions else None
|
| 533 |
+
all_cross_attentions = () if output_attentions and self.config.is_decoder else None
|
| 534 |
+
|
| 535 |
+
next_decoder_cache = () if use_cache else None
|
| 536 |
+
|
| 537 |
+
for i in range(self.config.num_hidden_layers):
|
| 538 |
+
layer_module = self.layer[i]
|
| 539 |
+
if output_hidden_states:
|
| 540 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 541 |
+
|
| 542 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 543 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 544 |
+
|
| 545 |
+
layer_outputs = layer_module(
|
| 546 |
+
hidden_states,
|
| 547 |
+
attention_mask,
|
| 548 |
+
layer_head_mask,
|
| 549 |
+
encoder_hidden_states,
|
| 550 |
+
encoder_attention_mask,
|
| 551 |
+
past_key_value,
|
| 552 |
+
output_attentions,
|
| 553 |
+
training=training,
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
hidden_states = layer_outputs[0]
|
| 557 |
+
if use_cache:
|
| 558 |
+
next_decoder_cache += (layer_outputs[-1],)
|
| 559 |
+
if output_attentions:
|
| 560 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 561 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
| 562 |
+
|
| 563 |
+
if output_hidden_states:
|
| 564 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 565 |
+
|
| 566 |
+
if not return_dict:
|
| 567 |
+
return tuple(
|
| 568 |
+
v
|
| 569 |
+
for v in [
|
| 570 |
+
hidden_states,
|
| 571 |
+
next_decoder_cache,
|
| 572 |
+
all_hidden_states,
|
| 573 |
+
all_self_attentions,
|
| 574 |
+
all_cross_attentions,
|
| 575 |
+
]
|
| 576 |
+
if v is not None
|
| 577 |
+
)
|
| 578 |
+
return TFBaseModelOutputWithPastAndCrossAttentions(
|
| 579 |
+
last_hidden_state=hidden_states,
|
| 580 |
+
past_key_values=next_decoder_cache,
|
| 581 |
+
hidden_states=all_hidden_states,
|
| 582 |
+
attentions=all_self_attentions,
|
| 583 |
+
cross_attentions=all_cross_attentions,
|
| 584 |
+
)
|
| 585 |
+
|
| 586 |
+
def build(self, input_shape=None):
|
| 587 |
+
if self.built:
|
| 588 |
+
return
|
| 589 |
+
self.built = True
|
| 590 |
+
if getattr(self, "layer", None) is not None:
|
| 591 |
+
for layer in self.layer:
|
| 592 |
+
with tf.name_scope(layer.name):
|
| 593 |
+
layer.build(None)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->BlipText
|
| 597 |
+
class TFBlipTextPooler(keras.layers.Layer):
|
| 598 |
+
def __init__(self, config: BlipTextConfig, **kwargs):
|
| 599 |
+
super().__init__(**kwargs)
|
| 600 |
+
|
| 601 |
+
self.dense = keras.layers.Dense(
|
| 602 |
+
units=config.hidden_size,
|
| 603 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 604 |
+
activation="tanh",
|
| 605 |
+
name="dense",
|
| 606 |
+
)
|
| 607 |
+
self.config = config
|
| 608 |
+
|
| 609 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 610 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
| 611 |
+
# to the first token.
|
| 612 |
+
first_token_tensor = hidden_states[:, 0]
|
| 613 |
+
pooled_output = self.dense(inputs=first_token_tensor)
|
| 614 |
+
|
| 615 |
+
return pooled_output
|
| 616 |
+
|
| 617 |
+
def build(self, input_shape=None):
|
| 618 |
+
if self.built:
|
| 619 |
+
return
|
| 620 |
+
self.built = True
|
| 621 |
+
if getattr(self, "dense", None) is not None:
|
| 622 |
+
with tf.name_scope(self.dense.name):
|
| 623 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
# Copied from transformers.models.bert.modeling_tf_bert.TFBertPredictionHeadTransform with Bert->BlipText
|
| 627 |
+
class TFBlipTextPredictionHeadTransform(keras.layers.Layer):
|
| 628 |
+
def __init__(self, config: BlipTextConfig, **kwargs):
|
| 629 |
+
super().__init__(**kwargs)
|
| 630 |
+
|
| 631 |
+
self.dense = keras.layers.Dense(
|
| 632 |
+
units=config.hidden_size,
|
| 633 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 634 |
+
name="dense",
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
if isinstance(config.hidden_act, str):
|
| 638 |
+
self.transform_act_fn = get_tf_activation(config.hidden_act)
|
| 639 |
+
else:
|
| 640 |
+
self.transform_act_fn = config.hidden_act
|
| 641 |
+
|
| 642 |
+
self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
|
| 643 |
+
self.config = config
|
| 644 |
+
|
| 645 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 646 |
+
hidden_states = self.dense(inputs=hidden_states)
|
| 647 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
| 648 |
+
hidden_states = self.LayerNorm(inputs=hidden_states)
|
| 649 |
+
|
| 650 |
+
return hidden_states
|
| 651 |
+
|
| 652 |
+
def build(self, input_shape=None):
|
| 653 |
+
if self.built:
|
| 654 |
+
return
|
| 655 |
+
self.built = True
|
| 656 |
+
if getattr(self, "dense", None) is not None:
|
| 657 |
+
with tf.name_scope(self.dense.name):
|
| 658 |
+
self.dense.build([None, None, self.config.hidden_size])
|
| 659 |
+
if getattr(self, "LayerNorm", None) is not None:
|
| 660 |
+
with tf.name_scope(self.LayerNorm.name):
|
| 661 |
+
self.LayerNorm.build([None, None, self.config.hidden_size])
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class TFBlipTextLMPredictionHead(keras.layers.Layer):
|
| 665 |
+
def __init__(self, config, **kwargs):
|
| 666 |
+
super().__init__(**kwargs)
|
| 667 |
+
self.transform = TFBlipTextPredictionHeadTransform(config, name="transform")
|
| 668 |
+
|
| 669 |
+
# The output weights are the same as the input embeddings, but there is
|
| 670 |
+
# an output-only bias for each token.
|
| 671 |
+
self.decoder = keras.layers.Dense(
|
| 672 |
+
config.vocab_size,
|
| 673 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 674 |
+
name="decoder",
|
| 675 |
+
use_bias=False,
|
| 676 |
+
)
|
| 677 |
+
self.config = config
|
| 678 |
+
|
| 679 |
+
def build(self, input_shape=None):
|
| 680 |
+
self.bias = self.add_weight(name="bias", shape=(self.config.vocab_size,), initializer="zeros", trainable=True)
|
| 681 |
+
|
| 682 |
+
if self.built:
|
| 683 |
+
return
|
| 684 |
+
self.built = True
|
| 685 |
+
if getattr(self, "transform", None) is not None:
|
| 686 |
+
with tf.name_scope(self.transform.name):
|
| 687 |
+
self.transform.build(None)
|
| 688 |
+
if getattr(self, "decoder", None) is not None:
|
| 689 |
+
with tf.name_scope(self.decoder.name):
|
| 690 |
+
self.decoder.build([None, None, self.config.hidden_size])
|
| 691 |
+
|
| 692 |
+
def call(self, hidden_states):
|
| 693 |
+
hidden_states = self.transform(hidden_states)
|
| 694 |
+
hidden_states = self.decoder(hidden_states) + self.bias
|
| 695 |
+
return hidden_states
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
class TFBlipTextOnlyMLMHead(keras.layers.Layer):
|
| 699 |
+
def __init__(self, config, **kwargs):
|
| 700 |
+
super().__init__(**kwargs)
|
| 701 |
+
self.predictions = TFBlipTextLMPredictionHead(config, name="predictions")
|
| 702 |
+
|
| 703 |
+
def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
|
| 704 |
+
prediction_scores = self.predictions(sequence_output)
|
| 705 |
+
return prediction_scores
|
| 706 |
+
|
| 707 |
+
def build(self, input_shape=None):
|
| 708 |
+
if self.built:
|
| 709 |
+
return
|
| 710 |
+
self.built = True
|
| 711 |
+
if getattr(self, "predictions", None) is not None:
|
| 712 |
+
with tf.name_scope(self.predictions.name):
|
| 713 |
+
self.predictions.build(None)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
|
| 717 |
+
class TFBlipTextPreTrainedModel(TFPreTrainedModel):
|
| 718 |
+
"""
|
| 719 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 720 |
+
models.
|
| 721 |
+
"""
|
| 722 |
+
|
| 723 |
+
config_class = BlipTextConfig
|
| 724 |
+
base_model_prefix = "bert"
|
| 725 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
|
| 729 |
+
class TFBlipTextModel(TFBlipTextPreTrainedModel):
|
| 730 |
+
"""
|
| 731 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
| 732 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
| 733 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
| 734 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
|
| 735 |
+
`encoder_hidden_states` is then expected as an input to the forward pass.
|
| 736 |
+
"""
|
| 737 |
+
|
| 738 |
+
def __init__(self, config, add_pooling_layer=True, name=None, **kwargs):
|
| 739 |
+
super().__init__(config, name=name, **kwargs)
|
| 740 |
+
self.config = config
|
| 741 |
+
|
| 742 |
+
self.embeddings = TFBlipTextEmbeddings(config, name="embeddings")
|
| 743 |
+
self.encoder = TFBlipTextEncoder(config, name="encoder")
|
| 744 |
+
self.pooler = TFBlipTextPooler(config, name="pooler") if add_pooling_layer else None
|
| 745 |
+
|
| 746 |
+
def get_input_embeddings(self):
|
| 747 |
+
return self.embeddings.word_embeddings
|
| 748 |
+
|
| 749 |
+
def set_input_embeddings(self, value):
|
| 750 |
+
self.embeddings.word_embeddings = value
|
| 751 |
+
|
| 752 |
+
@tf.function
|
| 753 |
+
def get_extended_attention_mask(
|
| 754 |
+
self, attention_mask: tf.Tensor, input_shape: Tuple[int], is_decoder: bool
|
| 755 |
+
) -> tf.Tensor:
|
| 756 |
+
"""
|
| 757 |
+
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
|
| 758 |
+
|
| 759 |
+
Arguments:
|
| 760 |
+
attention_mask (`tf.Tensor`):
|
| 761 |
+
Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
|
| 762 |
+
input_shape (`Tuple[int]`):
|
| 763 |
+
The shape of the input to the model.
|
| 764 |
+
is_decoder (`bool`):
|
| 765 |
+
Whether the model is used as a decoder.
|
| 766 |
+
|
| 767 |
+
Returns:
|
| 768 |
+
`tf.Tensor` The extended attention mask, with the same dtype as `attention_mask.dtype`.
|
| 769 |
+
"""
|
| 770 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 771 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 772 |
+
if not isinstance(attention_mask, tf.Tensor):
|
| 773 |
+
attention_mask = tf.convert_to_tensor(attention_mask) # Catches NumPy inputs that haven't been cast yet
|
| 774 |
+
if attention_mask.shape.rank == 3:
|
| 775 |
+
extended_attention_mask = attention_mask[:, None, :, :]
|
| 776 |
+
elif attention_mask.shape.rank == 2:
|
| 777 |
+
# Provided a padding mask of dimensions [batch_size, seq_length]
|
| 778 |
+
# - if the model is a decoder, apply a causal mask in addition to the padding mask
|
| 779 |
+
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 780 |
+
if is_decoder:
|
| 781 |
+
batch_size, seq_length = input_shape
|
| 782 |
+
|
| 783 |
+
seq_ids = tf.range(seq_length, dtype=attention_mask.dtype)
|
| 784 |
+
causal_mask = tf.broadcast_to(seq_ids, (batch_size, seq_length, seq_length)) <= seq_ids[None, :, None]
|
| 785 |
+
# in case past_key_values are used we need to add a prefix ones mask to the causal mask
|
| 786 |
+
|
| 787 |
+
if shape_list(causal_mask)[1] < shape_list(attention_mask)[1]:
|
| 788 |
+
prefix_seq_len = tf.shape(attention_mask)[1] - tf.shape(causal_mask)[1]
|
| 789 |
+
causal_mask = tf.concat(
|
| 790 |
+
[
|
| 791 |
+
tf.ones((batch_size, seq_length, prefix_seq_len), dtype=causal_mask.dtype),
|
| 792 |
+
causal_mask,
|
| 793 |
+
],
|
| 794 |
+
axis=-1,
|
| 795 |
+
)
|
| 796 |
+
extended_attention_mask = (
|
| 797 |
+
tf.cast(causal_mask[:, None, :, :], attention_mask.dtype) * attention_mask[:, None, None, :]
|
| 798 |
+
)
|
| 799 |
+
else:
|
| 800 |
+
extended_attention_mask = attention_mask[:, None, None, :]
|
| 801 |
+
else:
|
| 802 |
+
raise ValueError(
|
| 803 |
+
"Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
|
| 804 |
+
input_shape, attention_mask.shape
|
| 805 |
+
)
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 809 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 810 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 811 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 812 |
+
# effectively the same as removing these entirely.
|
| 813 |
+
extended_attention_mask = tf.cast(extended_attention_mask, self.dtype) # fp16 compatibility
|
| 814 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
| 815 |
+
return extended_attention_mask
|
| 816 |
+
|
| 817 |
+
@add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
|
| 818 |
+
@unpack_inputs
|
| 819 |
+
def call(
|
| 820 |
+
self,
|
| 821 |
+
input_ids: TFModelInputType | None = None,
|
| 822 |
+
attention_mask: tf.Tensor | None = None,
|
| 823 |
+
position_ids: tf.Tensor | None = None,
|
| 824 |
+
head_mask: tf.Tensor | None = None,
|
| 825 |
+
inputs_embeds: tf.Tensor | None = None,
|
| 826 |
+
encoder_embeds: tf.Tensor | None = None,
|
| 827 |
+
encoder_hidden_states: tf.Tensor | None = None,
|
| 828 |
+
encoder_attention_mask: tf.Tensor | None = None,
|
| 829 |
+
past_key_values: Tuple[Tuple[tf.Tensor]] | None = None,
|
| 830 |
+
use_cache: bool | None = None,
|
| 831 |
+
output_attentions: bool | None = None,
|
| 832 |
+
output_hidden_states: bool | None = None,
|
| 833 |
+
return_dict: bool | None = None,
|
| 834 |
+
is_decoder: bool = False,
|
| 835 |
+
training: bool = False,
|
| 836 |
+
) -> Tuple[tf.Tensor] | TFBaseModelOutputWithPoolingAndCrossAttentions:
|
| 837 |
+
r"""
|
| 838 |
+
encoder_hidden_states (`tf.Tensor`, *optional*):
|
| 839 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
| 840 |
+
the model is configured as a decoder.
|
| 841 |
+
encoder_attention_mask (`tf.Tensor`, *optional*):
|
| 842 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 843 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 844 |
+
- 1 for tokens that are **not masked**,
|
| 845 |
+
- 0 for tokens that are **masked**.
|
| 846 |
+
past_key_values (`tuple(tuple(tf.Tensor))`, *optional*):
|
| 847 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 848 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 849 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 850 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 851 |
+
use_cache (`bool`, *optional*):
|
| 852 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 853 |
+
`past_key_values`).
|
| 854 |
+
"""
|
| 855 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 856 |
+
output_hidden_states = (
|
| 857 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 858 |
+
)
|
| 859 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 860 |
+
|
| 861 |
+
if is_decoder:
|
| 862 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 863 |
+
else:
|
| 864 |
+
use_cache = False
|
| 865 |
+
|
| 866 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 867 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 868 |
+
elif input_ids is not None:
|
| 869 |
+
input_shape = shape_list(input_ids)
|
| 870 |
+
batch_size, seq_length = input_shape
|
| 871 |
+
elif inputs_embeds is not None:
|
| 872 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 873 |
+
batch_size, seq_length = input_shape
|
| 874 |
+
elif encoder_embeds is not None:
|
| 875 |
+
input_shape = shape_list(encoder_embeds)[:-1]
|
| 876 |
+
batch_size, seq_length = input_shape
|
| 877 |
+
else:
|
| 878 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
|
| 879 |
+
|
| 880 |
+
# past_key_values_length
|
| 881 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 882 |
+
|
| 883 |
+
if attention_mask is None:
|
| 884 |
+
attention_mask = tf.ones(((batch_size, seq_length + past_key_values_length)))
|
| 885 |
+
|
| 886 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
| 887 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
| 888 |
+
extended_attention_mask: tf.Tensor = self.get_extended_attention_mask(attention_mask, input_shape, is_decoder)
|
| 889 |
+
|
| 890 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
| 891 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
| 892 |
+
if encoder_hidden_states is not None:
|
| 893 |
+
if isinstance(encoder_hidden_states, list):
|
| 894 |
+
encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states[0])
|
| 895 |
+
else:
|
| 896 |
+
encoder_batch_size, encoder_sequence_length, _ = shape_list(encoder_hidden_states)
|
| 897 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
| 898 |
+
|
| 899 |
+
if isinstance(encoder_attention_mask, list):
|
| 900 |
+
encoder_extended_attention_mask = [invert_attention_mask(mask) for mask in encoder_attention_mask]
|
| 901 |
+
elif encoder_attention_mask is None:
|
| 902 |
+
encoder_attention_mask = tf.ones(encoder_hidden_shape)
|
| 903 |
+
encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)
|
| 904 |
+
else:
|
| 905 |
+
encoder_extended_attention_mask = invert_attention_mask(encoder_attention_mask)
|
| 906 |
+
else:
|
| 907 |
+
encoder_extended_attention_mask = None
|
| 908 |
+
|
| 909 |
+
# Prepare head mask if needed
|
| 910 |
+
# 1.0 in head_mask indicate we keep the head
|
| 911 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 912 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 913 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 914 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 915 |
+
|
| 916 |
+
if encoder_embeds is None:
|
| 917 |
+
embedding_output = self.embeddings(
|
| 918 |
+
input_ids=input_ids,
|
| 919 |
+
position_ids=position_ids,
|
| 920 |
+
inputs_embeds=inputs_embeds,
|
| 921 |
+
past_key_values_length=past_key_values_length,
|
| 922 |
+
)
|
| 923 |
+
else:
|
| 924 |
+
embedding_output = encoder_embeds
|
| 925 |
+
|
| 926 |
+
encoder_outputs = self.encoder(
|
| 927 |
+
embedding_output,
|
| 928 |
+
attention_mask=extended_attention_mask,
|
| 929 |
+
head_mask=head_mask,
|
| 930 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 931 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
| 932 |
+
past_key_values=past_key_values,
|
| 933 |
+
use_cache=use_cache,
|
| 934 |
+
output_attentions=output_attentions,
|
| 935 |
+
output_hidden_states=output_hidden_states,
|
| 936 |
+
return_dict=return_dict,
|
| 937 |
+
training=training,
|
| 938 |
+
)
|
| 939 |
+
sequence_output = encoder_outputs[0]
|
| 940 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
| 941 |
+
|
| 942 |
+
if not return_dict:
|
| 943 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
| 944 |
+
|
| 945 |
+
return TFBaseModelOutputWithPoolingAndCrossAttentions(
|
| 946 |
+
last_hidden_state=sequence_output,
|
| 947 |
+
pooler_output=pooled_output,
|
| 948 |
+
past_key_values=encoder_outputs.past_key_values,
|
| 949 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 950 |
+
attentions=encoder_outputs.attentions,
|
| 951 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
| 952 |
+
)
|
| 953 |
+
|
| 954 |
+
def build(self, input_shape=None):
|
| 955 |
+
if self.built:
|
| 956 |
+
return
|
| 957 |
+
self.built = True
|
| 958 |
+
if getattr(self, "embeddings", None) is not None:
|
| 959 |
+
with tf.name_scope(self.embeddings.name):
|
| 960 |
+
self.embeddings.build(None)
|
| 961 |
+
if getattr(self, "encoder", None) is not None:
|
| 962 |
+
with tf.name_scope(self.encoder.name):
|
| 963 |
+
self.encoder.build(None)
|
| 964 |
+
if getattr(self, "pooler", None) is not None:
|
| 965 |
+
with tf.name_scope(self.pooler.name):
|
| 966 |
+
self.pooler.build(None)
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
|
| 970 |
+
class TFBlipTextLMHeadModel(TFBlipTextPreTrainedModel):
|
| 971 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
| 972 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
|
| 973 |
+
|
| 974 |
+
def __init__(self, config, **kwargs):
|
| 975 |
+
super().__init__(config, **kwargs)
|
| 976 |
+
|
| 977 |
+
self.bert = TFBlipTextModel(config, add_pooling_layer=False, name="bert")
|
| 978 |
+
self.cls = TFBlipTextOnlyMLMHead(config, name="cls")
|
| 979 |
+
self.label_smoothing = config.label_smoothing
|
| 980 |
+
|
| 981 |
+
def get_output_embeddings(self):
|
| 982 |
+
return self.cls.predictions.decoder
|
| 983 |
+
|
| 984 |
+
def set_output_embeddings(self, new_embeddings):
|
| 985 |
+
self.cls.predictions.decoder = new_embeddings
|
| 986 |
+
|
| 987 |
+
@add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
|
| 988 |
+
@unpack_inputs
|
| 989 |
+
def call(
|
| 990 |
+
self,
|
| 991 |
+
input_ids=None,
|
| 992 |
+
attention_mask=None,
|
| 993 |
+
position_ids=None,
|
| 994 |
+
head_mask=None,
|
| 995 |
+
inputs_embeds=None,
|
| 996 |
+
encoder_hidden_states=None,
|
| 997 |
+
encoder_attention_mask=None,
|
| 998 |
+
labels=None,
|
| 999 |
+
past_key_values=None,
|
| 1000 |
+
use_cache=None,
|
| 1001 |
+
output_attentions=None,
|
| 1002 |
+
output_hidden_states=None,
|
| 1003 |
+
return_dict=None,
|
| 1004 |
+
return_logits=False,
|
| 1005 |
+
is_decoder=True,
|
| 1006 |
+
training=None,
|
| 1007 |
+
):
|
| 1008 |
+
r"""
|
| 1009 |
+
encoder_hidden_states (`tf.Tensor`, *optional*): Sequence of
|
| 1010 |
+
hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
|
| 1011 |
+
configured as a decoder.
|
| 1012 |
+
encoder_attention_mask (`tf.Tensor`, *optional*):
|
| 1013 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
| 1014 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
| 1015 |
+
- 1 for tokens that are **not masked**,
|
| 1016 |
+
- 0 for tokens that are **masked**.
|
| 1017 |
+
labels (`tf.Tensor`, *optional*):
|
| 1018 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
| 1019 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
| 1020 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
|
| 1021 |
+
past_key_values (`tuple(tuple(tf.Tensor))`, *optional*):
|
| 1022 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
| 1023 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1024 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1025 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1026 |
+
use_cache (`bool`, *optional*):
|
| 1027 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1028 |
+
`past_key_values`).
|
| 1029 |
+
"""
|
| 1030 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1031 |
+
if labels is not None:
|
| 1032 |
+
use_cache = False
|
| 1033 |
+
|
| 1034 |
+
outputs = self.bert(
|
| 1035 |
+
input_ids,
|
| 1036 |
+
attention_mask=attention_mask,
|
| 1037 |
+
position_ids=position_ids,
|
| 1038 |
+
head_mask=head_mask,
|
| 1039 |
+
inputs_embeds=inputs_embeds,
|
| 1040 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1041 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1042 |
+
past_key_values=past_key_values,
|
| 1043 |
+
use_cache=use_cache,
|
| 1044 |
+
output_attentions=output_attentions,
|
| 1045 |
+
output_hidden_states=output_hidden_states,
|
| 1046 |
+
return_dict=return_dict,
|
| 1047 |
+
is_decoder=is_decoder,
|
| 1048 |
+
training=training,
|
| 1049 |
+
)
|
| 1050 |
+
|
| 1051 |
+
sequence_output = outputs[0]
|
| 1052 |
+
prediction_scores = self.cls(sequence_output)
|
| 1053 |
+
|
| 1054 |
+
if return_logits:
|
| 1055 |
+
return prediction_scores[:, :-1, :]
|
| 1056 |
+
|
| 1057 |
+
lm_loss = None
|
| 1058 |
+
if labels is not None:
|
| 1059 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
| 1060 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :]
|
| 1061 |
+
shifted_prediction_scores = tf.reshape(shifted_prediction_scores, (-1, self.config.vocab_size))
|
| 1062 |
+
labels = labels[:, 1:]
|
| 1063 |
+
labels = tf.reshape(labels, (-1,))
|
| 1064 |
+
# Keras won't give us label smoothing for sparse CE, so we de-sparsify things here
|
| 1065 |
+
# Use relu to clamp masked labels at 0 to avoid NaN (we will be zeroing those out later anyway)
|
| 1066 |
+
one_hot_labels = tf.one_hot(tf.nn.relu(labels), depth=self.config.vocab_size, dtype=tf.float32)
|
| 1067 |
+
loss_fct = keras.losses.CategoricalCrossentropy(
|
| 1068 |
+
from_logits=True, label_smoothing=self.label_smoothing, reduction="none"
|
| 1069 |
+
)
|
| 1070 |
+
masked_positions = tf.cast(tf.not_equal(labels, -100), dtype=tf.float32)
|
| 1071 |
+
lm_loss = loss_fct(one_hot_labels, shifted_prediction_scores)
|
| 1072 |
+
lm_loss *= masked_positions
|
| 1073 |
+
lm_loss = tf.reduce_sum(lm_loss, axis=0) / tf.math.count_nonzero(masked_positions, dtype=tf.float32)
|
| 1074 |
+
|
| 1075 |
+
if not return_dict:
|
| 1076 |
+
output = (prediction_scores,) + outputs[2:]
|
| 1077 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
| 1078 |
+
|
| 1079 |
+
return TFCausalLMOutputWithCrossAttentions(
|
| 1080 |
+
loss=lm_loss,
|
| 1081 |
+
logits=prediction_scores,
|
| 1082 |
+
past_key_values=outputs.past_key_values,
|
| 1083 |
+
hidden_states=outputs.hidden_states,
|
| 1084 |
+
attentions=outputs.attentions,
|
| 1085 |
+
cross_attentions=outputs.cross_attentions,
|
| 1086 |
+
)
|
| 1087 |
+
|
| 1088 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
| 1089 |
+
input_shape = input_ids.shape
|
| 1090 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 1091 |
+
if attention_mask is None:
|
| 1092 |
+
attention_mask = input_ids.new_ones(input_shape)
|
| 1093 |
+
|
| 1094 |
+
# cut decoder_input_ids if past_key_values is used
|
| 1095 |
+
if past_key_values is not None:
|
| 1096 |
+
input_ids = input_ids[:, -1:]
|
| 1097 |
+
|
| 1098 |
+
return {
|
| 1099 |
+
"input_ids": input_ids,
|
| 1100 |
+
"attention_mask": attention_mask,
|
| 1101 |
+
"past_key_values": past_key_values,
|
| 1102 |
+
"encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
|
| 1103 |
+
"encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
|
| 1104 |
+
"is_decoder": True,
|
| 1105 |
+
}
|
| 1106 |
+
|
| 1107 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 1108 |
+
reordered_past = ()
|
| 1109 |
+
for layer_past in past_key_values:
|
| 1110 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
| 1111 |
+
return reordered_past
|
| 1112 |
+
|
| 1113 |
+
def build(self, input_shape=None):
|
| 1114 |
+
if self.built:
|
| 1115 |
+
return
|
| 1116 |
+
self.built = True
|
| 1117 |
+
if getattr(self, "bert", None) is not None:
|
| 1118 |
+
with tf.name_scope(self.bert.name):
|
| 1119 |
+
self.bert.build(None)
|
| 1120 |
+
if getattr(self, "cls", None) is not None:
|
| 1121 |
+
with tf.name_scope(self.cls.name):
|
| 1122 |
+
self.cls.build(None)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/blip/processing_blip.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Processor class for Blip.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import List, Optional, 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 |
+
|
| 25 |
+
|
| 26 |
+
class BlipProcessorKwargs(ProcessingKwargs, total=False):
|
| 27 |
+
_defaults = {
|
| 28 |
+
"text_kwargs": {
|
| 29 |
+
"add_special_tokens": True,
|
| 30 |
+
"padding": False,
|
| 31 |
+
"stride": 0,
|
| 32 |
+
"return_overflowing_tokens": False,
|
| 33 |
+
"return_special_tokens_mask": False,
|
| 34 |
+
"return_offsets_mapping": False,
|
| 35 |
+
"return_token_type_ids": False,
|
| 36 |
+
"return_length": False,
|
| 37 |
+
"verbose": True,
|
| 38 |
+
},
|
| 39 |
+
"images_kwargs": {},
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BlipProcessor(ProcessorMixin):
|
| 44 |
+
r"""
|
| 45 |
+
Constructs a BLIP processor which wraps a BERT tokenizer and BLIP image processor into a single processor.
|
| 46 |
+
|
| 47 |
+
[`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`BertTokenizerFast`]. See the
|
| 48 |
+
docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
image_processor (`BlipImageProcessor`):
|
| 52 |
+
An instance of [`BlipImageProcessor`]. The image processor is a required input.
|
| 53 |
+
tokenizer (`BertTokenizerFast`):
|
| 54 |
+
An instance of ['BertTokenizerFast`]. The tokenizer is a required input.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
attributes = ["image_processor", "tokenizer"]
|
| 58 |
+
valid_kwargs = []
|
| 59 |
+
image_processor_class = "BlipImageProcessor"
|
| 60 |
+
tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
|
| 61 |
+
|
| 62 |
+
def __init__(self, image_processor, tokenizer, **kwargs):
|
| 63 |
+
tokenizer.return_token_type_ids = False
|
| 64 |
+
super().__init__(image_processor, tokenizer)
|
| 65 |
+
self.current_processor = self.image_processor
|
| 66 |
+
|
| 67 |
+
def __call__(
|
| 68 |
+
self,
|
| 69 |
+
images: ImageInput = None,
|
| 70 |
+
text: Optional[Union[str, List[str], TextInput, PreTokenizedInput]] = None,
|
| 71 |
+
audio=None,
|
| 72 |
+
videos=None,
|
| 73 |
+
**kwargs: Unpack[BlipProcessorKwargs],
|
| 74 |
+
) -> BatchEncoding:
|
| 75 |
+
"""
|
| 76 |
+
This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
|
| 77 |
+
[`BertTokenizerFast.__call__`] to prepare text for the model.
|
| 78 |
+
|
| 79 |
+
Please refer to the docstring of the above two methods for more information.
|
| 80 |
+
Args:
|
| 81 |
+
images (`ImageInput`):
|
| 82 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 83 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 84 |
+
text (`TextInput`, `PreTokenizedInput`, `List[TextInput]`, `List[PreTokenizedInput]`):
|
| 85 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 86 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 87 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 88 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 89 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 90 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 91 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 92 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 93 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 94 |
+
"""
|
| 95 |
+
if images is None and text is None:
|
| 96 |
+
raise ValueError("You have to specify either images or text.")
|
| 97 |
+
|
| 98 |
+
text_encoding = None
|
| 99 |
+
|
| 100 |
+
# add pixel_values encoding. If we also have text_encoding, update image encoding and return it.
|
| 101 |
+
# else, return the text encoding.
|
| 102 |
+
output_kwargs = self._merge_kwargs(
|
| 103 |
+
BlipProcessorKwargs,
|
| 104 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 105 |
+
**kwargs,
|
| 106 |
+
)
|
| 107 |
+
if text is not None:
|
| 108 |
+
text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 109 |
+
if images is not None:
|
| 110 |
+
encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
|
| 111 |
+
|
| 112 |
+
if text_encoding is not None:
|
| 113 |
+
encoding_image_processor.update(text_encoding)
|
| 114 |
+
return encoding_image_processor
|
| 115 |
+
|
| 116 |
+
return text_encoding
|
| 117 |
+
|
| 118 |
+
def batch_decode(self, *args, **kwargs):
|
| 119 |
+
"""
|
| 120 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 121 |
+
refer to the docstring of this method for more information.
|
| 122 |
+
"""
|
| 123 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 124 |
+
|
| 125 |
+
def decode(self, *args, **kwargs):
|
| 126 |
+
"""
|
| 127 |
+
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 128 |
+
the docstring of this method for more information.
|
| 129 |
+
"""
|
| 130 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 131 |
+
|
| 132 |
+
@property
|
| 133 |
+
def model_input_names(self):
|
| 134 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 135 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 136 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
__all__ = ["BlipProcessor"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_hiera import *
|
| 22 |
+
from .modeling_hiera import *
|
| 23 |
+
else:
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
_file = globals()["__file__"]
|
| 27 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (537 Bytes). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/configuration_hiera.cpython-310.pyc
ADDED
|
Binary file (7.89 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/convert_hiera_to_hf.cpython-310.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/__pycache__/modeling_hiera.cpython-310.pyc
ADDED
|
Binary file (51.3 kB). View file
|
|
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/configuration_hiera.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 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 |
+
"""Hiera model configuration"""
|
| 16 |
+
|
| 17 |
+
from ...configuration_utils import PretrainedConfig
|
| 18 |
+
from ...utils import logging
|
| 19 |
+
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.get_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class HieraConfig(BackboneConfigMixin, PretrainedConfig):
|
| 26 |
+
r"""
|
| 27 |
+
This is the configuration class to store the configuration of a [`HieraModel`]. It is used to instantiate a Hiera
|
| 28 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 29 |
+
defaults will yield a similar configuration to that of the Hiera
|
| 30 |
+
[facebook/hiera-base-224](https://huggingface.co/facebook/hiera-base-224) architecture.
|
| 31 |
+
|
| 32 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 33 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
embed_dim (`int`, *optional*, defaults to 96):
|
| 37 |
+
Dimensionality of patch embedding.
|
| 38 |
+
image_size (`list(int)`, *optional*, defaults to `[224, 224]`):
|
| 39 |
+
The size (resolution) of input in the format (height, width) for images
|
| 40 |
+
and (frames, height, width) for videos.
|
| 41 |
+
patch_size (`list(int)`, *optional*, defaults to `[7, 7]`):
|
| 42 |
+
The size (resolution) of each patch.
|
| 43 |
+
patch_stride (`list(int)`, *optional*, defaults to `[4, 4]`):
|
| 44 |
+
The stride of the patch.
|
| 45 |
+
patch_padding (`list(int)`, *optional*, defaults to `[3, 3]`):
|
| 46 |
+
The padding of the patch.
|
| 47 |
+
mlp_ratio (`float`, *optional*, defaults to 4.0):
|
| 48 |
+
The ratio of mlp hidden dim to embedding dim.
|
| 49 |
+
depths (`list(int)`, *optional*, defaults to `[2, 3, 16, 3]`):
|
| 50 |
+
Depth of each layer in the Transformer encoder.
|
| 51 |
+
num_heads (`list(int)`, *optional*, defaults to `[1, 2, 4, 8]`):
|
| 52 |
+
Number of attention heads in each layer of the Transformer encoder.
|
| 53 |
+
embed_dim_multiplier (`float`, *optional*, defaults to 2.0):
|
| 54 |
+
The multiplier to the dimensionality of patch embedding in each layer of the Transformer encoder.
|
| 55 |
+
num_query_pool (`int`, *optional*, defaults to 3):
|
| 56 |
+
The number of query pool stages.
|
| 57 |
+
query_stride (`list(int)`, *optional*, defaults to `[2, 2]`):
|
| 58 |
+
The stride of the query pool.
|
| 59 |
+
masked_unit_size (`list(int)`, *optional*, defaults to `[8, 8]`):
|
| 60 |
+
The size of the masked unit.
|
| 61 |
+
masked_unit_attention (`list(bool)`, *optional*, defaults to `[True, True, False, False]`):
|
| 62 |
+
Whether to use masked unit attention in each layer of the Transformer encoder.
|
| 63 |
+
drop_path_rate (`float`, *optional*, defaults to 0.0):
|
| 64 |
+
The drop path rate.
|
| 65 |
+
num_channels (`int`, *optional*, defaults to 3):
|
| 66 |
+
The number of input channels.
|
| 67 |
+
hidden_act (`str`, *optional*, defaults to `"gelu"`):
|
| 68 |
+
The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
|
| 69 |
+
`"selu"` and `"gelu_new"` are supported.
|
| 70 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 71 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices and
|
| 72 |
+
the zero_initializer for initializing all bias vectors.
|
| 73 |
+
layer_norm_init (`float`, *optional*, defaults to 1.0):
|
| 74 |
+
The initial weight value for layer normalization layers.
|
| 75 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
|
| 76 |
+
The epsilon used by the layer normalization layers.
|
| 77 |
+
decoder_hidden_size (`int`, *optional*):
|
| 78 |
+
Dimensionality of decoder embeddings for MAE pretraining.
|
| 79 |
+
decoder_depth (`int`, *optional*):
|
| 80 |
+
Depth of the decoder for MAE pretraining.
|
| 81 |
+
decoder_num_heads (`int`, *optional*):
|
| 82 |
+
Number of attention heads in each layer of the decoder for MAE pretraining.
|
| 83 |
+
normalize_pixel_loss (`bool`, *optional*, defaults to `True`):
|
| 84 |
+
Whether to normalize the pixel loss by the number of pixels.
|
| 85 |
+
mask_ratio (`float`, *optional*, defaults to 0.6):
|
| 86 |
+
The ratio of masked tokens in the input.
|
| 87 |
+
out_features (`List[str]`, *optional*):
|
| 88 |
+
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
|
| 89 |
+
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
|
| 90 |
+
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
|
| 91 |
+
same order as defined in the `stage_names` attribute.
|
| 92 |
+
out_indices (`List[int]`, *optional*):
|
| 93 |
+
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
|
| 94 |
+
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
|
| 95 |
+
If unset and `out_features` is unset, will default to the last stage. Must be in the
|
| 96 |
+
same order as defined in the `stage_names` attribute.
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
Example:
|
| 100 |
+
|
| 101 |
+
```python
|
| 102 |
+
>>> from transformers import HieraConfig, HieraModel
|
| 103 |
+
|
| 104 |
+
>>> # Initializing a Hiera hiera-base-patch16-224 style configuration
|
| 105 |
+
>>> configuration = HieraConfig()
|
| 106 |
+
|
| 107 |
+
>>> # Initializing a model (with random weights) from the hiera-base-patch16-224 style configuration
|
| 108 |
+
>>> model = HieraModel(configuration)
|
| 109 |
+
|
| 110 |
+
>>> # Accessing the model configuration
|
| 111 |
+
>>> configuration = model.config
|
| 112 |
+
```"""
|
| 113 |
+
|
| 114 |
+
model_type = "hiera"
|
| 115 |
+
|
| 116 |
+
attribute_map = {"num_hidden_layers": "num_layers"}
|
| 117 |
+
|
| 118 |
+
def __init__(
|
| 119 |
+
self,
|
| 120 |
+
embed_dim=96,
|
| 121 |
+
image_size=[224, 224],
|
| 122 |
+
patch_size=[7, 7],
|
| 123 |
+
patch_stride=[4, 4],
|
| 124 |
+
patch_padding=[3, 3],
|
| 125 |
+
mlp_ratio=4.0,
|
| 126 |
+
depths=[2, 3, 16, 3],
|
| 127 |
+
num_heads=[1, 2, 4, 8],
|
| 128 |
+
embed_dim_multiplier=2.0,
|
| 129 |
+
num_query_pool=3,
|
| 130 |
+
query_stride=[2, 2],
|
| 131 |
+
masked_unit_size=[8, 8],
|
| 132 |
+
masked_unit_attention=[True, True, False, False],
|
| 133 |
+
drop_path_rate=0.0,
|
| 134 |
+
num_channels=3,
|
| 135 |
+
hidden_act="gelu",
|
| 136 |
+
initializer_range=0.02,
|
| 137 |
+
layer_norm_init=1.0,
|
| 138 |
+
layer_norm_eps=1e-6,
|
| 139 |
+
decoder_hidden_size=None,
|
| 140 |
+
decoder_depth=None,
|
| 141 |
+
decoder_num_heads=None,
|
| 142 |
+
normalize_pixel_loss=True,
|
| 143 |
+
mask_ratio=0.6,
|
| 144 |
+
out_features=None,
|
| 145 |
+
out_indices=None,
|
| 146 |
+
**kwargs,
|
| 147 |
+
):
|
| 148 |
+
super().__init__(**kwargs)
|
| 149 |
+
if masked_unit_size[0] % query_stride[0] ** (len(depths) - 1) != 0:
|
| 150 |
+
raise ValueError(
|
| 151 |
+
f"masked_unit_size[0] ({masked_unit_size[0]}) must be divisible by query_stride[0] ({query_stride[0]}) "
|
| 152 |
+
f"raised to the power of the number of layers ({len(depths) - 1})"
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
if num_query_pool >= len(depths):
|
| 156 |
+
raise ValueError(
|
| 157 |
+
f"num_query_pool ({num_query_pool}) must be less than the number of layers ({len(depths)})"
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
self.embed_dim = embed_dim
|
| 161 |
+
self.image_size = image_size
|
| 162 |
+
self.patch_size = patch_size
|
| 163 |
+
self.patch_stride = patch_stride
|
| 164 |
+
self.patch_padding = patch_padding
|
| 165 |
+
self.mlp_ratio = mlp_ratio
|
| 166 |
+
self.depths = depths
|
| 167 |
+
self.num_heads = num_heads
|
| 168 |
+
self.num_layers = len(depths)
|
| 169 |
+
self.embed_dim_multiplier = embed_dim_multiplier
|
| 170 |
+
self.num_query_pool = num_query_pool
|
| 171 |
+
self.query_stride = query_stride
|
| 172 |
+
self.masked_unit_size = masked_unit_size
|
| 173 |
+
self.masked_unit_attention = masked_unit_attention
|
| 174 |
+
self.drop_path_rate = drop_path_rate
|
| 175 |
+
self.num_channels = num_channels
|
| 176 |
+
self.hidden_act = hidden_act
|
| 177 |
+
self.initializer_range = initializer_range
|
| 178 |
+
self.layer_norm_init = layer_norm_init
|
| 179 |
+
self.layer_norm_eps = layer_norm_eps
|
| 180 |
+
self.decoder_hidden_size = decoder_hidden_size
|
| 181 |
+
self.decoder_depth = decoder_depth
|
| 182 |
+
self.decoder_num_heads = decoder_num_heads
|
| 183 |
+
self.normalize_pixel_loss = normalize_pixel_loss
|
| 184 |
+
self.mask_ratio = mask_ratio
|
| 185 |
+
# we set the hidden_size attribute in order to make Hiera work with VisionEncoderDecoderModel
|
| 186 |
+
# this indicates the channel dimension after the last stage of the model
|
| 187 |
+
self.hidden_size = int(embed_dim * embed_dim_multiplier ** (len(depths) - 1))
|
| 188 |
+
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
|
| 189 |
+
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
|
| 190 |
+
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
__all__ = ["HieraConfig"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 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 |
+
"""Convert Hiera checkpoints from the original repository.
|
| 16 |
+
|
| 17 |
+
URL: https://github.com/facebookresearch/hiera
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import math
|
| 23 |
+
from typing import Dict, Tuple
|
| 24 |
+
|
| 25 |
+
import requests
|
| 26 |
+
import torch
|
| 27 |
+
from huggingface_hub import hf_hub_download
|
| 28 |
+
from PIL import Image
|
| 29 |
+
from torchvision import transforms
|
| 30 |
+
|
| 31 |
+
from transformers import BitImageProcessor, HieraConfig, HieraForImageClassification, HieraForPreTraining, HieraModel
|
| 32 |
+
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
|
| 33 |
+
from transformers.utils import logging
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logging.set_verbosity_info()
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# here we list all keys to be renamed (original name on the left, our name on the right)
|
| 41 |
+
def create_rename_keys(config: HieraConfig, base_model: bool, mae_model: bool):
|
| 42 |
+
rename_keys = []
|
| 43 |
+
# fmt: off
|
| 44 |
+
num_stages = len(config.depths)
|
| 45 |
+
# embedding dimensions for input and stages
|
| 46 |
+
dims = [config.embed_dim] + [int(config.embed_dim * config.embed_dim_multiplier**i) for i in range(num_stages)]
|
| 47 |
+
|
| 48 |
+
global_layer_idx = 0
|
| 49 |
+
for stage_idx in range(num_stages):
|
| 50 |
+
dim_in = dims[stage_idx]
|
| 51 |
+
dim_out = dims[stage_idx + 1]
|
| 52 |
+
for layer_idx in range(config.depths[stage_idx]):
|
| 53 |
+
rename_keys.append((f"blocks.{global_layer_idx}.norm1.weight", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.layernorm_before.weight"))
|
| 54 |
+
rename_keys.append((f"blocks.{global_layer_idx}.norm1.bias", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.layernorm_before.bias"))
|
| 55 |
+
rename_keys.append((f"blocks.{global_layer_idx}.attn.qkv.weight", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.attn.qkv.weight"))
|
| 56 |
+
rename_keys.append((f"blocks.{global_layer_idx}.attn.qkv.bias", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.attn.qkv.bias"))
|
| 57 |
+
rename_keys.append((f"blocks.{global_layer_idx}.attn.proj.weight", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.attn.proj.weight"))
|
| 58 |
+
rename_keys.append((f"blocks.{global_layer_idx}.attn.proj.bias", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.attn.proj.bias"))
|
| 59 |
+
rename_keys.append((f"blocks.{global_layer_idx}.norm2.weight", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.layernorm_after.weight"))
|
| 60 |
+
rename_keys.append((f"blocks.{global_layer_idx}.norm2.bias", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.layernorm_after.bias"))
|
| 61 |
+
rename_keys.append((f"blocks.{global_layer_idx}.mlp.fc1.weight", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.mlp.fc1.weight"))
|
| 62 |
+
rename_keys.append((f"blocks.{global_layer_idx}.mlp.fc1.bias", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.mlp.fc1.bias"))
|
| 63 |
+
rename_keys.append((f"blocks.{global_layer_idx}.mlp.fc2.weight", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.mlp.fc2.weight"))
|
| 64 |
+
rename_keys.append((f"blocks.{global_layer_idx}.mlp.fc2.bias", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.mlp.fc2.bias"))
|
| 65 |
+
|
| 66 |
+
# projection layer only for the first layer of each stage boundary (except the first stage)
|
| 67 |
+
if dim_out != dim_in and layer_idx == 0:
|
| 68 |
+
rename_keys.append((f"blocks.{global_layer_idx}.proj.weight", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.proj.weight"))
|
| 69 |
+
rename_keys.append((f"blocks.{global_layer_idx}.proj.bias", f"hiera.encoder.stages.{stage_idx}.layers.{layer_idx}.proj.bias"))
|
| 70 |
+
|
| 71 |
+
global_layer_idx += 1
|
| 72 |
+
|
| 73 |
+
# projection layer + position embeddings
|
| 74 |
+
rename_keys.extend(
|
| 75 |
+
[
|
| 76 |
+
("patch_embed.proj.weight", "hiera.embeddings.patch_embeddings.projection.weight"),
|
| 77 |
+
("patch_embed.proj.bias", "hiera.embeddings.patch_embeddings.projection.bias")
|
| 78 |
+
]
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
rename_keys.append(("pos_embed", "hiera.embeddings.position_embeddings"))
|
| 82 |
+
|
| 83 |
+
if base_model:
|
| 84 |
+
# layernorm + pooler
|
| 85 |
+
rename_keys.extend([("norm.weight", "pooler.layernorm.weight"), ("norm.bias", "pooler.layernorm.bias")])
|
| 86 |
+
# if just the base model, we should remove "hiera" from all keys that start with "hiera"
|
| 87 |
+
rename_keys = [(pair[0], pair[1][6:]) if pair[1].startswith("hiera") else pair for pair in rename_keys]
|
| 88 |
+
elif mae_model:
|
| 89 |
+
rename_keys.extend(
|
| 90 |
+
[
|
| 91 |
+
("encoder_norm.weight", "encoder_norm.weight"),
|
| 92 |
+
("encoder_norm.bias", "encoder_norm.bias"),
|
| 93 |
+
("mask_token", "decoder.mask_token"),
|
| 94 |
+
("decoder_pos_embed", "decoder.decoder_position_embeddings"),
|
| 95 |
+
("decoder_norm.weight", "decoder.decoder_norm.weight"),
|
| 96 |
+
("decoder_norm.bias", "decoder.decoder_norm.bias"),
|
| 97 |
+
("decoder_pred.weight", "decoder.decoder_pred.weight"),
|
| 98 |
+
("decoder_pred.bias", "decoder.decoder_pred.bias"),
|
| 99 |
+
("decoder_embed.weight", "decoder.decoder_embeddings.weight"),
|
| 100 |
+
("decoder_embed.bias", "decoder.decoder_embeddings.bias")
|
| 101 |
+
]
|
| 102 |
+
)
|
| 103 |
+
for i in range(config.decoder_depth):
|
| 104 |
+
rename_keys.extend(
|
| 105 |
+
[
|
| 106 |
+
(f"decoder_blocks.{i}.norm1.weight", f"decoder.decoder_block.layers.{i}.layernorm_before.weight"),
|
| 107 |
+
(f"decoder_blocks.{i}.norm1.bias", f"decoder.decoder_block.layers.{i}.layernorm_before.bias"),
|
| 108 |
+
(f"decoder_blocks.{i}.attn.qkv.weight", f"decoder.decoder_block.layers.{i}.attn.qkv.weight"),
|
| 109 |
+
(f"decoder_blocks.{i}.attn.qkv.bias", f"decoder.decoder_block.layers.{i}.attn.qkv.bias"),
|
| 110 |
+
(f"decoder_blocks.{i}.attn.proj.weight", f"decoder.decoder_block.layers.{i}.attn.proj.weight"),
|
| 111 |
+
(f"decoder_blocks.{i}.attn.proj.bias", f"decoder.decoder_block.layers.{i}.attn.proj.bias"),
|
| 112 |
+
(f"decoder_blocks.{i}.norm2.weight", f"decoder.decoder_block.layers.{i}.layernorm_after.weight"),
|
| 113 |
+
(f"decoder_blocks.{i}.norm2.bias", f"decoder.decoder_block.layers.{i}.layernorm_after.bias"),
|
| 114 |
+
(f"decoder_blocks.{i}.mlp.fc1.weight", f"decoder.decoder_block.layers.{i}.mlp.fc1.weight"),
|
| 115 |
+
(f"decoder_blocks.{i}.mlp.fc1.bias", f"decoder.decoder_block.layers.{i}.mlp.fc1.bias"),
|
| 116 |
+
(f"decoder_blocks.{i}.mlp.fc2.weight", f"decoder.decoder_block.layers.{i}.mlp.fc2.weight"),
|
| 117 |
+
(f"decoder_blocks.{i}.mlp.fc2.bias", f"decoder.decoder_block.layers.{i}.mlp.fc2.bias"),
|
| 118 |
+
]
|
| 119 |
+
)
|
| 120 |
+
for i in range(config.num_query_pool):
|
| 121 |
+
rename_keys.extend(
|
| 122 |
+
[
|
| 123 |
+
(f"multi_scale_fusion_heads.{i}.weight", f"multiscale_fusion.multi_scale_fusion_heads.{i}.weight"),
|
| 124 |
+
(f"multi_scale_fusion_heads.{i}.bias", f"multiscale_fusion.multi_scale_fusion_heads.{i}.bias")
|
| 125 |
+
]
|
| 126 |
+
)
|
| 127 |
+
else:
|
| 128 |
+
# layernorm + classification head
|
| 129 |
+
rename_keys.extend(
|
| 130 |
+
[
|
| 131 |
+
("norm.weight", "hiera.pooler.layernorm.weight"),
|
| 132 |
+
("norm.bias", "hiera.pooler.layernorm.bias"),
|
| 133 |
+
("head.projection.weight", "classifier.weight"),
|
| 134 |
+
("head.projection.bias", "classifier.bias"),
|
| 135 |
+
]
|
| 136 |
+
)
|
| 137 |
+
# fmt: on
|
| 138 |
+
return rename_keys
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def remove_classification_head_(state_dict):
|
| 142 |
+
ignore_keys = ["head.projection.weight", "head.projection.bias"]
|
| 143 |
+
for k in ignore_keys:
|
| 144 |
+
state_dict.pop(k, None)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def rename_key(dct, old, new):
|
| 148 |
+
val = dct.pop(old)
|
| 149 |
+
dct[new] = val
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# We will verify our results on an image of cute cats
|
| 153 |
+
def prepare_img():
|
| 154 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 155 |
+
im = Image.open(requests.get(url, stream=True).raw)
|
| 156 |
+
return im
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def get_labels_for_classifier(model_name: str) -> Tuple[Dict[int, str], Dict[str, int], int]:
|
| 160 |
+
repo_id = "huggingface/label-files"
|
| 161 |
+
|
| 162 |
+
filename = "imagenet-1k-id2label.json"
|
| 163 |
+
|
| 164 |
+
id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
|
| 165 |
+
id2label = {int(k): v for k, v in id2label.items()}
|
| 166 |
+
label2id = {v: k for k, v in id2label.items()}
|
| 167 |
+
num_labels = len(id2label)
|
| 168 |
+
|
| 169 |
+
return id2label, label2id, num_labels
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def get_hiera_config(model_name: str, base_model: bool, mae_model: bool) -> HieraConfig:
|
| 173 |
+
if model_name == "hiera-tiny-224":
|
| 174 |
+
config = HieraConfig(depths=[1, 2, 7, 2])
|
| 175 |
+
elif model_name == "hiera-small-224":
|
| 176 |
+
config = HieraConfig(depths=[1, 2, 11, 2])
|
| 177 |
+
elif model_name == "hiera-base-224":
|
| 178 |
+
config = HieraConfig()
|
| 179 |
+
elif model_name == "hiera-base-plus-224":
|
| 180 |
+
config = HieraConfig(embed_dim=112, num_heads=[2, 4, 8, 16])
|
| 181 |
+
elif model_name == "hiera-large-224":
|
| 182 |
+
config = HieraConfig(embed_dim=144, num_heads=[2, 4, 8, 16], depths=[2, 6, 36, 4])
|
| 183 |
+
elif model_name == "hiera-huge-224":
|
| 184 |
+
config = HieraConfig(embed_dim=256, num_heads=[4, 8, 16, 32], depths=[2, 6, 36, 4])
|
| 185 |
+
else:
|
| 186 |
+
raise ValueError(f"Unrecognized model name: {model_name}")
|
| 187 |
+
|
| 188 |
+
if base_model:
|
| 189 |
+
pass
|
| 190 |
+
elif mae_model:
|
| 191 |
+
config.num_query_pool = 2
|
| 192 |
+
config.decoder_hidden_size = 512
|
| 193 |
+
config.decoder_depth = 8
|
| 194 |
+
config.decoder_num_heads = 16
|
| 195 |
+
# Table 3b from Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles
|
| 196 |
+
config.mask_ratio = 0.6
|
| 197 |
+
else:
|
| 198 |
+
id2label, label2id, num_labels = get_labels_for_classifier(model_name)
|
| 199 |
+
config.id2label = id2label
|
| 200 |
+
config.label2id = label2id
|
| 201 |
+
config.num_labels = num_labels
|
| 202 |
+
|
| 203 |
+
return config
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
@torch.no_grad()
|
| 207 |
+
def convert_hiera_checkpoint(args):
|
| 208 |
+
model_name = args.model_name
|
| 209 |
+
base_model = args.base_model
|
| 210 |
+
pytorch_dump_folder_path = args.pytorch_dump_folder_path
|
| 211 |
+
push_to_hub = args.push_to_hub
|
| 212 |
+
mae_model = args.mae_model
|
| 213 |
+
|
| 214 |
+
config = get_hiera_config(model_name, base_model, mae_model)
|
| 215 |
+
|
| 216 |
+
# Load original hiera model
|
| 217 |
+
original_model_name = model_name.replace("-", "_")
|
| 218 |
+
original_model_name = f"mae_{original_model_name}" if mae_model else original_model_name
|
| 219 |
+
|
| 220 |
+
original_checkpoint_name = "mae_in1k_ft_in1k" if not (base_model or mae_model) else "mae_in1k"
|
| 221 |
+
|
| 222 |
+
original_model = torch.hub.load(
|
| 223 |
+
"facebookresearch/hiera",
|
| 224 |
+
model=original_model_name,
|
| 225 |
+
pretrained=True,
|
| 226 |
+
checkpoint=original_checkpoint_name,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
original_model.eval()
|
| 230 |
+
original_state_dict = original_model.state_dict()
|
| 231 |
+
# Don't need to remove head for MAE because original implementation doesn't have it on MAE
|
| 232 |
+
if base_model:
|
| 233 |
+
remove_classification_head_(original_state_dict)
|
| 234 |
+
|
| 235 |
+
# # Rename keys
|
| 236 |
+
new_state_dict = original_state_dict.copy()
|
| 237 |
+
rename_keys = create_rename_keys(config, base_model, mae_model)
|
| 238 |
+
|
| 239 |
+
for src, dest in rename_keys:
|
| 240 |
+
rename_key(new_state_dict, src, dest)
|
| 241 |
+
|
| 242 |
+
# Load HF hiera model
|
| 243 |
+
if base_model:
|
| 244 |
+
model = HieraModel(config)
|
| 245 |
+
elif mae_model:
|
| 246 |
+
model = HieraForPreTraining(config)
|
| 247 |
+
else:
|
| 248 |
+
model = HieraForImageClassification(config)
|
| 249 |
+
|
| 250 |
+
model.eval()
|
| 251 |
+
|
| 252 |
+
missing_keys, unexpected_keys = model.load_state_dict(new_state_dict, strict=False)
|
| 253 |
+
print("Missing keys:", missing_keys)
|
| 254 |
+
print("Unexpected keys:", unexpected_keys)
|
| 255 |
+
|
| 256 |
+
input_image = prepare_img()
|
| 257 |
+
|
| 258 |
+
original_image_preprocessor = transforms.Compose(
|
| 259 |
+
[
|
| 260 |
+
transforms.Resize(int((256 / 224) * 224), interpolation=transforms.functional.InterpolationMode.BICUBIC),
|
| 261 |
+
transforms.CenterCrop(224),
|
| 262 |
+
transforms.ToTensor(),
|
| 263 |
+
transforms.Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD),
|
| 264 |
+
]
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
image_processor = BitImageProcessor(
|
| 268 |
+
image_mean=IMAGENET_DEFAULT_MEAN, image_std=IMAGENET_DEFAULT_STD, size={"shortest_edge": 256}
|
| 269 |
+
)
|
| 270 |
+
inputs = image_processor(images=input_image, return_tensors="pt")
|
| 271 |
+
|
| 272 |
+
expected_pixel_values = original_image_preprocessor(input_image).unsqueeze(0)
|
| 273 |
+
|
| 274 |
+
input_image = prepare_img()
|
| 275 |
+
|
| 276 |
+
inputs = image_processor(images=input_image, return_tensors="pt")
|
| 277 |
+
expected_pixel_values = original_image_preprocessor(input_image).unsqueeze(0)
|
| 278 |
+
assert torch.allclose(inputs.pixel_values, expected_pixel_values, atol=1e-4)
|
| 279 |
+
print("Pixel values look good!")
|
| 280 |
+
print(f"{inputs.pixel_values[0, :3, :3, :3]=}")
|
| 281 |
+
|
| 282 |
+
# If is MAE we pass a noise to generate a random mask
|
| 283 |
+
mask_spatial_shape = [
|
| 284 |
+
i // s // ms for i, s, ms in zip(config.image_size, config.patch_stride, config.masked_unit_size)
|
| 285 |
+
]
|
| 286 |
+
num_windows = math.prod(mask_spatial_shape)
|
| 287 |
+
torch.manual_seed(2)
|
| 288 |
+
noise = torch.rand(1, num_windows)
|
| 289 |
+
outputs = model(**inputs) if not mae_model else model(noise=noise, **inputs)
|
| 290 |
+
# original implementation returns logits.softmax(dim=-1)
|
| 291 |
+
|
| 292 |
+
if base_model:
|
| 293 |
+
expected_prob, expected_intermediates = original_model(expected_pixel_values, return_intermediates=True)
|
| 294 |
+
expected_last_hidden = expected_intermediates[-1]
|
| 295 |
+
batch_size, _, _, hidden_dim = expected_last_hidden.shape
|
| 296 |
+
expected_last_hidden = expected_last_hidden.reshape(batch_size, -1, hidden_dim)
|
| 297 |
+
assert torch.allclose(outputs.last_hidden_state, expected_last_hidden, atol=1e-3)
|
| 298 |
+
print("Base Model looks good as hidden states match original implementation!")
|
| 299 |
+
print(f"{outputs.last_hidden_state[0, :3, :3]=}")
|
| 300 |
+
elif mae_model:
|
| 301 |
+
# get mask from noise to be able to compare outputs
|
| 302 |
+
mask, _ = model.hiera.embeddings.patch_embeddings.random_masking(expected_pixel_values, noise)
|
| 303 |
+
expected_loss, _, _, _ = original_model(expected_pixel_values, mask=mask.bool())
|
| 304 |
+
assert torch.allclose(outputs.loss, expected_loss, atol=1e-3)
|
| 305 |
+
print("MAE Model looks good as loss matches original implementation!")
|
| 306 |
+
else:
|
| 307 |
+
expected_prob = original_model(expected_pixel_values)
|
| 308 |
+
assert torch.allclose(outputs.logits.softmax(dim=-1), expected_prob, atol=1e-3)
|
| 309 |
+
print("Classifier looks good as probs match original implementation")
|
| 310 |
+
print(f"{outputs.logits[:, :5]=}")
|
| 311 |
+
|
| 312 |
+
if pytorch_dump_folder_path is not None:
|
| 313 |
+
print(f"Saving model and processor for {model_name} to {pytorch_dump_folder_path}")
|
| 314 |
+
model.save_pretrained(pytorch_dump_folder_path)
|
| 315 |
+
image_processor.save_pretrained(pytorch_dump_folder_path)
|
| 316 |
+
|
| 317 |
+
if push_to_hub:
|
| 318 |
+
hub_name = model_name
|
| 319 |
+
if base_model:
|
| 320 |
+
hub_name = model_name
|
| 321 |
+
elif mae_model:
|
| 322 |
+
hub_name = f"{model_name}-mae"
|
| 323 |
+
else:
|
| 324 |
+
hub_name = f"{model_name}-in1k"
|
| 325 |
+
repo_id = f"EduardoPacheco/{hub_name}"
|
| 326 |
+
print(f"Pushing model and processor for {model_name} to hub at {repo_id}")
|
| 327 |
+
model.push_to_hub(repo_id)
|
| 328 |
+
image_processor.push_to_hub(repo_id)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
if __name__ == "__main__":
|
| 332 |
+
parser = argparse.ArgumentParser()
|
| 333 |
+
# Required parameters
|
| 334 |
+
parser.add_argument(
|
| 335 |
+
"--model-name",
|
| 336 |
+
default="hiera-tiny-224",
|
| 337 |
+
type=str,
|
| 338 |
+
choices=[
|
| 339 |
+
"hiera-tiny-224",
|
| 340 |
+
"hiera-small-224",
|
| 341 |
+
"hiera-base-224",
|
| 342 |
+
"hiera-base-plus-224",
|
| 343 |
+
"hiera-large-224",
|
| 344 |
+
"hiera-huge-224",
|
| 345 |
+
],
|
| 346 |
+
help="Name of the Hiera model you'd like to convert.",
|
| 347 |
+
)
|
| 348 |
+
parser.add_argument(
|
| 349 |
+
"--pytorch-dump-folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
|
| 350 |
+
)
|
| 351 |
+
parser.add_argument(
|
| 352 |
+
"--verify-logits",
|
| 353 |
+
action="store_true",
|
| 354 |
+
help="Whether or not to verify the logits against the original implementation.",
|
| 355 |
+
)
|
| 356 |
+
parser.add_argument(
|
| 357 |
+
"--push-to-hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
|
| 358 |
+
)
|
| 359 |
+
parser.add_argument(
|
| 360 |
+
"--base-model",
|
| 361 |
+
action="store_true",
|
| 362 |
+
help="Whether to only convert the base model (no projection head weights).",
|
| 363 |
+
)
|
| 364 |
+
parser.add_argument(
|
| 365 |
+
"--mae-model", action="store_true", help="Whether to convert to MAE checkpoint to HieraForPreTraining."
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
args = parser.parse_args()
|
| 369 |
+
convert_hiera_checkpoint(args)
|
vlmpy310/lib/python3.10/site-packages/transformers/models/hiera/modeling_hiera.py
ADDED
|
@@ -0,0 +1,1573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 Meta and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""PyTorch Hiera model."""
|
| 16 |
+
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Dict, List, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 25 |
+
|
| 26 |
+
from ...activations import ACT2FN
|
| 27 |
+
from ...modeling_outputs import (
|
| 28 |
+
BackboneOutput,
|
| 29 |
+
BaseModelOutput,
|
| 30 |
+
BaseModelOutputWithPooling,
|
| 31 |
+
ImageClassifierOutput,
|
| 32 |
+
ModelOutput,
|
| 33 |
+
)
|
| 34 |
+
from ...modeling_utils import PreTrainedModel
|
| 35 |
+
from ...utils import (
|
| 36 |
+
add_code_sample_docstrings,
|
| 37 |
+
add_start_docstrings,
|
| 38 |
+
add_start_docstrings_to_model_forward,
|
| 39 |
+
logging,
|
| 40 |
+
replace_return_docstrings,
|
| 41 |
+
torch_int,
|
| 42 |
+
)
|
| 43 |
+
from ...utils.backbone_utils import BackboneMixin
|
| 44 |
+
from .configuration_hiera import HieraConfig
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
# General docstring
|
| 50 |
+
_CONFIG_FOR_DOC = "HieraConfig"
|
| 51 |
+
|
| 52 |
+
# Base docstring
|
| 53 |
+
_CHECKPOINT_FOR_DOC = "facebook/hiera-tiny-224-hf"
|
| 54 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 49, 768]
|
| 55 |
+
|
| 56 |
+
# Image classification docstring
|
| 57 |
+
_IMAGE_CLASS_CHECKPOINT = "facebook/hiera-tiny-224-in1k-hf"
|
| 58 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
class HieraEncoderOutput(ModelOutput):
|
| 63 |
+
"""
|
| 64 |
+
Hiera encoder's outputs, with potential hidden states and attentions.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 68 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 69 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 70 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 71 |
+
shape `(batch_size, sequence_length, hidden_size)`. Thesre are the unrolled hidden states of the model.
|
| 72 |
+
|
| 73 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 74 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 75 |
+
Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
|
| 76 |
+
sequence_length)`.
|
| 77 |
+
|
| 78 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 79 |
+
heads.
|
| 80 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 81 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 82 |
+
shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
|
| 83 |
+
|
| 84 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 85 |
+
include the spatial dimensions.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
last_hidden_state: torch.FloatTensor = None
|
| 89 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 90 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 91 |
+
reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@dataclass
|
| 95 |
+
class HieraModelOutput(ModelOutput):
|
| 96 |
+
"""
|
| 97 |
+
Hiera model's outputs that also contains a pooling of the last hidden states.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 101 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 102 |
+
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
|
| 103 |
+
Average pooling of the last layer hidden-state.
|
| 104 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 105 |
+
Tensor indicating which patches are masked (0) and which are not (1).
|
| 106 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 107 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 108 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 109 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 110 |
+
shape `(batch_size, sequence_length, hidden_size)`. These are the unrolled hidden states of the model.
|
| 111 |
+
|
| 112 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 113 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 114 |
+
Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
|
| 115 |
+
sequence_length)`.
|
| 116 |
+
|
| 117 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 118 |
+
heads.
|
| 119 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 120 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 121 |
+
shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
|
| 122 |
+
|
| 123 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 124 |
+
include the spatial dimensions.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
last_hidden_state: torch.FloatTensor = None
|
| 128 |
+
pooler_output: Optional[torch.FloatTensor] = None
|
| 129 |
+
bool_masked_pos: torch.BoolTensor = None
|
| 130 |
+
ids_restore: torch.LongTensor = None
|
| 131 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 132 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 133 |
+
reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@dataclass
|
| 137 |
+
class HieraForImageClassificationOutput(ImageClassifierOutput):
|
| 138 |
+
"""
|
| 139 |
+
Hiera image classification outputs.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
loss (`torch.FloatTensor` of shape `(1,)`, `optional`):
|
| 143 |
+
Loss value for the training task.
|
| 144 |
+
logits (`torch.FloatTensor` of shape `(batch_size, num_labels)`):
|
| 145 |
+
Prediction scores of the classification head (logits of the output layer).
|
| 146 |
+
hidden_states (`tuple(torch.FloatTensor)`, `optional`):
|
| 147 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 148 |
+
shape `(batch_size, sequence_length, hidden_size)`. These are the unrolled hidden states of the model.
|
| 149 |
+
|
| 150 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
| 151 |
+
attentions (`tuple(torch.FloatTensor)`, `optional`):
|
| 152 |
+
Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
|
| 153 |
+
sequence_length)`.
|
| 154 |
+
|
| 155 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 156 |
+
heads.
|
| 157 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, `optional`):
|
| 158 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
|
| 159 |
+
shape `(batch_size, height, width, hidden_size)`. These are the reshaped and re-rolled hidden states of the model.
|
| 160 |
+
|
| 161 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
|
| 162 |
+
include the spatial dimensions.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
loss: Optional[torch.FloatTensor] = None
|
| 166 |
+
logits: torch.FloatTensor = None
|
| 167 |
+
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 168 |
+
attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 169 |
+
reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@dataclass
|
| 173 |
+
class HieraForPreTrainingOutput(ModelOutput):
|
| 174 |
+
"""
|
| 175 |
+
Class for HieraForPreTraining's outputs, with potential hidden states and attentions.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
loss (`torch.FloatTensor` of shape `(1,)`):
|
| 179 |
+
Pixel reconstruction loss.
|
| 180 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, patch_size ** 2 * num_channels)`):
|
| 181 |
+
Pixel reconstruction logits.
|
| 182 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 183 |
+
Tensor indicating which patches are masked (0) and which are not (1).
|
| 184 |
+
ids_restore (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 185 |
+
Tensor containing the original index of the (shuffled) masked patches.
|
| 186 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 187 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 188 |
+
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 189 |
+
plus the initial embedding outputs.
|
| 190 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 191 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 192 |
+
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
|
| 193 |
+
the self-attention heads.
|
| 194 |
+
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 195 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
| 196 |
+
shape `(batch_size, height, width, hidden_size)`. Hidden-states of the model at the output of each layer
|
| 197 |
+
plus the initial embedding outputs reshaped to include the spatial dimensions.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
loss: Optional[torch.FloatTensor] = None
|
| 201 |
+
logits: torch.FloatTensor = None
|
| 202 |
+
bool_masked_pos: torch.BoolTensor = None
|
| 203 |
+
ids_restore: torch.LongTensor = None
|
| 204 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 205 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 206 |
+
reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class HieraPatchEmbeddings(nn.Module):
|
| 210 |
+
"""
|
| 211 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 212 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 213 |
+
Transformer.
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
def __init__(self, config, is_mae: bool = False):
|
| 217 |
+
super().__init__()
|
| 218 |
+
|
| 219 |
+
# Support any number of spatial dimensions
|
| 220 |
+
self.spatial_dims = len(config.patch_size)
|
| 221 |
+
if self.spatial_dims != 2:
|
| 222 |
+
raise ValueError(f"The number of dimensions of the input image should be 2, but got {self.spatial_dims}.")
|
| 223 |
+
self.num_channels = config.num_channels
|
| 224 |
+
self.image_size = config.image_size[-2:]
|
| 225 |
+
self.tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
|
| 226 |
+
self.mask_spatial_shape = [i // s for i, s in zip(self.tokens_spatial_shape, config.masked_unit_size)]
|
| 227 |
+
self.mask_ratio = config.mask_ratio
|
| 228 |
+
self.is_mae = is_mae
|
| 229 |
+
self.projection = nn.Conv2d(
|
| 230 |
+
self.num_channels,
|
| 231 |
+
config.embed_dim,
|
| 232 |
+
kernel_size=config.patch_size,
|
| 233 |
+
stride=config.patch_stride,
|
| 234 |
+
padding=config.patch_padding,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
def masked_conv(
|
| 238 |
+
self, pixel_values: torch.FloatTensor, bool_masked_pos: Optional[torch.BoolTensor] = None
|
| 239 |
+
) -> torch.Tensor:
|
| 240 |
+
"""Zero-out the masked regions of the input before conv.
|
| 241 |
+
Prevents leakage of masked regions when using overlapping kernels.
|
| 242 |
+
"""
|
| 243 |
+
if bool_masked_pos is None:
|
| 244 |
+
return self.projection(pixel_values)
|
| 245 |
+
|
| 246 |
+
target_size = pixel_values.shape[2:]
|
| 247 |
+
# Reshape bool_masked_pos to (batch_size, 1, mask_unit_height, mask_unit_width)
|
| 248 |
+
bool_masked_pos = bool_masked_pos.view(pixel_values.shape[0], 1, *self.mask_spatial_shape)
|
| 249 |
+
|
| 250 |
+
bool_masked_pos = nn.functional.interpolate(bool_masked_pos.float(), size=target_size)
|
| 251 |
+
|
| 252 |
+
return self.projection(pixel_values * bool_masked_pos)
|
| 253 |
+
|
| 254 |
+
def random_masking(
|
| 255 |
+
self, pixel_values: torch.FloatTensor, noise: Optional[torch.FloatTensor] = None
|
| 256 |
+
) -> Tuple[torch.BoolTensor, torch.LongTensor]:
|
| 257 |
+
"""
|
| 258 |
+
Perform per-sample random masking by per-sample shuffling. Per-sample shuffling is done by argsort random
|
| 259 |
+
noise.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`)
|
| 263 |
+
noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*) which is
|
| 264 |
+
mainly used for testing purposes to control randomness and maintain the reproducibility
|
| 265 |
+
"""
|
| 266 |
+
batch_size = pixel_values.shape[0]
|
| 267 |
+
# Tokens selected for masking at mask unit level
|
| 268 |
+
num_windows = math.prod(self.mask_spatial_shape)
|
| 269 |
+
len_keep = int(num_windows * (1 - self.mask_ratio))
|
| 270 |
+
|
| 271 |
+
if noise is None:
|
| 272 |
+
noise = torch.rand(batch_size, num_windows, device=pixel_values.device)
|
| 273 |
+
|
| 274 |
+
# Sort noise for each sample
|
| 275 |
+
ids_shuffle = torch.argsort(noise, dim=1)
|
| 276 |
+
# ascend: small is keep, large is remove
|
| 277 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1).to(pixel_values.device)
|
| 278 |
+
|
| 279 |
+
# Generate the binary bool_masked_pos: 1 is *keep*, 0 is *remove*
|
| 280 |
+
# Note this is opposite to original MAE
|
| 281 |
+
bool_masked_pos = torch.zeros([batch_size, num_windows], device=pixel_values.device)
|
| 282 |
+
bool_masked_pos[:, :len_keep] = 1
|
| 283 |
+
# Unshuffle to get the binary bool_masked_pos
|
| 284 |
+
bool_masked_pos = torch.gather(bool_masked_pos, dim=1, index=ids_restore).bool()
|
| 285 |
+
|
| 286 |
+
return bool_masked_pos, ids_restore
|
| 287 |
+
|
| 288 |
+
def forward(
|
| 289 |
+
self,
|
| 290 |
+
pixel_values: torch.FloatTensor,
|
| 291 |
+
noise: Optional[torch.FloatTensor] = None,
|
| 292 |
+
) -> Tuple[torch.Tensor, Optional[torch.BoolTensor], Optional[torch.LongTensor]]:
|
| 293 |
+
(bool_masked_pos, ids_restore) = (
|
| 294 |
+
self.random_masking(pixel_values, noise=noise) if self.is_mae else (None, None)
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
embeddings = self.masked_conv(pixel_values, bool_masked_pos)
|
| 298 |
+
embeddings = embeddings.flatten(2).transpose(2, 1)
|
| 299 |
+
|
| 300 |
+
return embeddings, bool_masked_pos, ids_restore
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class HieraEmbeddings(nn.Module):
|
| 304 |
+
"""
|
| 305 |
+
Construct position and patch embeddings.
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
def __init__(self, config: HieraConfig, is_mae: bool = False) -> None:
|
| 309 |
+
super().__init__()
|
| 310 |
+
self.patch_stride = config.patch_stride
|
| 311 |
+
tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
|
| 312 |
+
self.mask_spatial_shape = [i // s for i, s in zip(tokens_spatial_shape, config.masked_unit_size)]
|
| 313 |
+
self.num_tokens = math.prod(tokens_spatial_shape)
|
| 314 |
+
self.is_mae = is_mae
|
| 315 |
+
|
| 316 |
+
self.patch_embeddings = HieraPatchEmbeddings(config, is_mae=is_mae)
|
| 317 |
+
|
| 318 |
+
self.position_embeddings = nn.Parameter(torch.zeros(1, self.num_tokens, config.embed_dim))
|
| 319 |
+
|
| 320 |
+
def interpolate_pos_encoding(
|
| 321 |
+
self, embeddings: torch.Tensor, pos_embeds: torch.Tensor, height: int, width: int
|
| 322 |
+
) -> torch.Tensor:
|
| 323 |
+
"""
|
| 324 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
|
| 325 |
+
images. This method is also adapted to support torch.jit tracing, no class embeddings, and different patch strides.
|
| 326 |
+
|
| 327 |
+
Adapted from:
|
| 328 |
+
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
|
| 329 |
+
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
|
| 330 |
+
"""
|
| 331 |
+
|
| 332 |
+
num_patches = embeddings.shape[1]
|
| 333 |
+
num_positions = pos_embeds.shape[1]
|
| 334 |
+
|
| 335 |
+
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
|
| 336 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
| 337 |
+
return pos_embeds
|
| 338 |
+
|
| 339 |
+
dim = embeddings.shape[-1]
|
| 340 |
+
|
| 341 |
+
new_height = height // self.patch_stride[0]
|
| 342 |
+
new_width = width // self.patch_stride[1]
|
| 343 |
+
|
| 344 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
| 345 |
+
pos_embeds = pos_embeds.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
| 346 |
+
pos_embeds = pos_embeds.permute(0, 3, 1, 2)
|
| 347 |
+
|
| 348 |
+
pos_embeds = nn.functional.interpolate(
|
| 349 |
+
pos_embeds,
|
| 350 |
+
size=(new_height, new_width),
|
| 351 |
+
mode="bicubic",
|
| 352 |
+
align_corners=False,
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
pos_embeds = pos_embeds.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 356 |
+
return pos_embeds
|
| 357 |
+
|
| 358 |
+
def get_position_embedding(
|
| 359 |
+
self, embeddings: torch.Tensor, height: int, width: int, interpolate_pos_encoding: bool
|
| 360 |
+
) -> torch.FloatTensor:
|
| 361 |
+
return (
|
| 362 |
+
self.interpolate_pos_encoding(embeddings, self.position_embeddings, height, width)
|
| 363 |
+
if interpolate_pos_encoding
|
| 364 |
+
else self.position_embeddings
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
def forward(
|
| 368 |
+
self,
|
| 369 |
+
pixel_values: torch.FloatTensor,
|
| 370 |
+
noise: Optional[torch.FloatTensor] = None,
|
| 371 |
+
interpolate_pos_encoding: bool = False,
|
| 372 |
+
) -> Tuple[torch.Tensor, Optional[torch.BoolTensor], Optional[torch.LongTensor]]:
|
| 373 |
+
height, width = pixel_values.shape[-2:]
|
| 374 |
+
embeddings, bool_masked_pos, ids_restore = self.patch_embeddings(pixel_values, noise=noise)
|
| 375 |
+
embeddings = embeddings + self.get_position_embedding(embeddings, height, width, interpolate_pos_encoding)
|
| 376 |
+
return embeddings, bool_masked_pos, ids_restore
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class HieraMaskUnitAttention(nn.Module):
|
| 380 |
+
"""
|
| 381 |
+
Computes either Mask Unit or Global Attention. Also is able to perform query pooling.
|
| 382 |
+
|
| 383 |
+
Note: this assumes the tokens have already been flattened and unrolled into mask units.
|
| 384 |
+
"""
|
| 385 |
+
|
| 386 |
+
def __init__(
|
| 387 |
+
self,
|
| 388 |
+
hidden_size: int,
|
| 389 |
+
hidden_size_output: int,
|
| 390 |
+
num_heads: int,
|
| 391 |
+
query_stride: int = 1,
|
| 392 |
+
window_size: int = 0,
|
| 393 |
+
use_mask_unit_attn: bool = False,
|
| 394 |
+
) -> None:
|
| 395 |
+
super().__init__()
|
| 396 |
+
self.num_heads = num_heads
|
| 397 |
+
self.query_stride = query_stride
|
| 398 |
+
self.hidden_size_output = hidden_size_output
|
| 399 |
+
|
| 400 |
+
self.head_dim = hidden_size_output // num_heads
|
| 401 |
+
self.scale = (self.head_dim) ** -0.5
|
| 402 |
+
|
| 403 |
+
self.qkv = nn.Linear(hidden_size, 3 * hidden_size_output)
|
| 404 |
+
self.proj = nn.Linear(hidden_size_output, hidden_size_output)
|
| 405 |
+
|
| 406 |
+
self.window_size = window_size
|
| 407 |
+
self.use_mask_unit_attn = use_mask_unit_attn
|
| 408 |
+
|
| 409 |
+
def forward(
|
| 410 |
+
self,
|
| 411 |
+
hidden_states: torch.Tensor,
|
| 412 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 413 |
+
output_attentions: bool = False,
|
| 414 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 415 |
+
"""Input should be of shape [batch, tokens, channels]."""
|
| 416 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 417 |
+
|
| 418 |
+
num_windows = 1
|
| 419 |
+
if self.use_mask_unit_attn:
|
| 420 |
+
num_windows = seq_len // (self.query_stride * self.window_size)
|
| 421 |
+
|
| 422 |
+
qkv = self.qkv(hidden_states)
|
| 423 |
+
qkv = qkv.reshape(batch_size, -1, num_windows, 3, self.num_heads, self.head_dim)
|
| 424 |
+
qkv = qkv.permute(3, 0, 4, 2, 1, 5)
|
| 425 |
+
|
| 426 |
+
query, key, value = qkv.unbind(0)
|
| 427 |
+
|
| 428 |
+
if self.query_stride > 1:
|
| 429 |
+
# Refer to unroll to see how this performs a maxpool-Nd
|
| 430 |
+
query = query.view(batch_size, self.num_heads, num_windows, self.query_stride, -1, self.head_dim)
|
| 431 |
+
query = query.max(dim=3).values
|
| 432 |
+
|
| 433 |
+
attn_weights = (query * self.scale) @ key.transpose(-1, -2)
|
| 434 |
+
attn_weights = attn_weights.softmax(dim=-1)
|
| 435 |
+
|
| 436 |
+
# Mask heads if we want to
|
| 437 |
+
if head_mask is not None:
|
| 438 |
+
attn_weights = attn_weights * head_mask
|
| 439 |
+
|
| 440 |
+
attn_output = attn_weights @ value
|
| 441 |
+
attn_output = attn_output.transpose(1, 3).reshape(batch_size, -1, self.hidden_size_output)
|
| 442 |
+
attn_output = self.proj(attn_output)
|
| 443 |
+
|
| 444 |
+
return (attn_output, attn_weights) if output_attentions else (attn_output, None)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 448 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 449 |
+
"""
|
| 450 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 451 |
+
|
| 452 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 453 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 454 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 455 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 456 |
+
argument.
|
| 457 |
+
"""
|
| 458 |
+
if drop_prob == 0.0 or not training:
|
| 459 |
+
return input
|
| 460 |
+
keep_prob = 1 - drop_prob
|
| 461 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 462 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 463 |
+
random_tensor.floor_() # binarize
|
| 464 |
+
output = input.div(keep_prob) * random_tensor
|
| 465 |
+
return output
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
# Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->Hiera
|
| 469 |
+
class HieraDropPath(nn.Module):
|
| 470 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 471 |
+
|
| 472 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 473 |
+
super().__init__()
|
| 474 |
+
self.drop_prob = drop_prob
|
| 475 |
+
|
| 476 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 477 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 478 |
+
|
| 479 |
+
def extra_repr(self) -> str:
|
| 480 |
+
return "p={}".format(self.drop_prob)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
class HieraMlp(nn.Module):
|
| 484 |
+
def __init__(self, config, dim: int) -> None:
|
| 485 |
+
super().__init__()
|
| 486 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 487 |
+
self.fc1 = nn.Linear(dim, int(dim * config.mlp_ratio))
|
| 488 |
+
self.fc2 = nn.Linear(int(dim * config.mlp_ratio), dim)
|
| 489 |
+
|
| 490 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 491 |
+
hidden_states = self.fc1(hidden_states)
|
| 492 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 493 |
+
hidden_states = self.fc2(hidden_states)
|
| 494 |
+
return hidden_states
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
class HieraLayer(nn.Module):
|
| 498 |
+
def __init__(
|
| 499 |
+
self,
|
| 500 |
+
config,
|
| 501 |
+
hidden_size: int,
|
| 502 |
+
hidden_size_output: int,
|
| 503 |
+
num_heads: int,
|
| 504 |
+
drop_path: float = 0.0,
|
| 505 |
+
query_stride: int = 1,
|
| 506 |
+
window_size: int = 0,
|
| 507 |
+
use_mask_unit_attn: bool = False,
|
| 508 |
+
) -> None:
|
| 509 |
+
super().__init__()
|
| 510 |
+
|
| 511 |
+
self.hidden_size = hidden_size
|
| 512 |
+
self.hidden_size_output = hidden_size_output
|
| 513 |
+
self.query_stride = query_stride
|
| 514 |
+
|
| 515 |
+
self.layernorm_before = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
|
| 516 |
+
self.attn = HieraMaskUnitAttention(
|
| 517 |
+
hidden_size=hidden_size,
|
| 518 |
+
hidden_size_output=hidden_size_output,
|
| 519 |
+
num_heads=num_heads,
|
| 520 |
+
query_stride=query_stride,
|
| 521 |
+
window_size=window_size,
|
| 522 |
+
use_mask_unit_attn=use_mask_unit_attn,
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
self.layernorm_after = nn.LayerNorm(hidden_size_output, eps=config.layer_norm_eps)
|
| 526 |
+
self.mlp = HieraMlp(config, hidden_size_output)
|
| 527 |
+
|
| 528 |
+
self.drop_path = HieraDropPath(drop_path) if drop_path > 0 else nn.Identity()
|
| 529 |
+
if hidden_size != hidden_size_output:
|
| 530 |
+
self.proj = nn.Linear(hidden_size, hidden_size_output)
|
| 531 |
+
|
| 532 |
+
def forward(
|
| 533 |
+
self,
|
| 534 |
+
hidden_states: torch.Tensor,
|
| 535 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 536 |
+
output_attentions: bool = False,
|
| 537 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 538 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 539 |
+
# Attention + Q Pooling
|
| 540 |
+
hidden_states_norm = self.layernorm_before(hidden_states)
|
| 541 |
+
if self.hidden_size != self.hidden_size_output:
|
| 542 |
+
hidden_states = self.proj(hidden_states_norm)
|
| 543 |
+
# Refer to unroll to see how this performs a maxpool-Nd
|
| 544 |
+
hidden_states = (
|
| 545 |
+
hidden_states.view(batch_size, self.query_stride, -1, self.hidden_size_output).max(dim=1).values
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
(hidden_states_norm, attn_weights) = self.attn(
|
| 549 |
+
hidden_states_norm, head_mask, output_attentions=output_attentions
|
| 550 |
+
)
|
| 551 |
+
hidden_states = hidden_states + self.drop_path(hidden_states_norm)
|
| 552 |
+
|
| 553 |
+
residual = hidden_states
|
| 554 |
+
hidden_states = self.layernorm_after(hidden_states)
|
| 555 |
+
hidden_states = self.mlp(hidden_states)
|
| 556 |
+
hidden_states = residual + self.drop_path(hidden_states)
|
| 557 |
+
|
| 558 |
+
return (hidden_states, attn_weights)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
class HieraStage(nn.Module):
|
| 562 |
+
def __init__(
|
| 563 |
+
self,
|
| 564 |
+
config,
|
| 565 |
+
depth: int,
|
| 566 |
+
hidden_size: int,
|
| 567 |
+
hidden_size_output: int,
|
| 568 |
+
num_heads: int,
|
| 569 |
+
drop_path: List[float],
|
| 570 |
+
query_stride: List[int],
|
| 571 |
+
window_size: int,
|
| 572 |
+
use_mask_unit_attn: bool,
|
| 573 |
+
stage_num: Optional[int] = None,
|
| 574 |
+
) -> None:
|
| 575 |
+
super().__init__()
|
| 576 |
+
# we need to know if the previous stage used masked attention
|
| 577 |
+
# mask unit or global attention.
|
| 578 |
+
# lag by 1 layer, so that global attention,
|
| 579 |
+
# applied post pooling on lower resolution
|
| 580 |
+
previous_stage_used_masked_attention = False
|
| 581 |
+
if stage_num is not None:
|
| 582 |
+
previous_stage_used_masked_attention = config.masked_unit_attention[stage_num - 1 if stage_num > 0 else 0]
|
| 583 |
+
self.layers = nn.ModuleList(
|
| 584 |
+
[
|
| 585 |
+
HieraLayer(
|
| 586 |
+
config=config,
|
| 587 |
+
hidden_size=hidden_size if i == 0 else hidden_size_output,
|
| 588 |
+
hidden_size_output=hidden_size_output,
|
| 589 |
+
num_heads=num_heads,
|
| 590 |
+
drop_path=drop_path[i],
|
| 591 |
+
query_stride=query_stride[i],
|
| 592 |
+
window_size=window_size,
|
| 593 |
+
use_mask_unit_attn=use_mask_unit_attn or (previous_stage_used_masked_attention and i == 0),
|
| 594 |
+
)
|
| 595 |
+
for i in range(depth)
|
| 596 |
+
]
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
def forward(
|
| 600 |
+
self, hidden_states: torch.Tensor, head_mask: Optional[torch.FloatTensor], output_attentions: bool = False
|
| 601 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 602 |
+
for i, layer_module in enumerate(self.layers):
|
| 603 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 604 |
+
(hidden_states, attn_weights) = layer_module(
|
| 605 |
+
hidden_states, layer_head_mask, output_attentions=output_attentions
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
return hidden_states, attn_weights
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def undo_windowing(hidden_states: torch.Tensor, shape: List[int], mask_unit_shape: List[int]) -> torch.Tensor:
|
| 612 |
+
"""
|
| 613 |
+
Restore spatial organization by undoing windowed organization of mask units.
|
| 614 |
+
|
| 615 |
+
Args:
|
| 616 |
+
hidden_states (`torch.Tensor`): The hidden states tensor of shape `[batch_size, num_mask_unit_height*num_mask_unit_width, hidden_size]`.
|
| 617 |
+
shape (`List[int]`): The original shape of the hidden states tensor before windowing.
|
| 618 |
+
mask_unit_shape (`List[int]`): The shape of the mask units used for windowing.
|
| 619 |
+
|
| 620 |
+
Returns:
|
| 621 |
+
torch.Tensor: The restored hidden states tensor of shape [batch_size, num_mask_unit_height*mask_unit_height, num_mask_unit_width*mask_unit_width, hidden_size].
|
| 622 |
+
"""
|
| 623 |
+
batch_size, hidden_size = hidden_states.shape[0], hidden_states.shape[-1]
|
| 624 |
+
# From: [batch_size, num_mask_unit_height*num_mask_unit_width, hidden_size]
|
| 625 |
+
# To: [batch_size, num_mask_unit_height, num_mask_unit_width, mask_unit_height, mask_unit_width, hidden_size]
|
| 626 |
+
num_mask_units = [s // mu for s, mu in zip(shape, mask_unit_shape)]
|
| 627 |
+
hidden_states = hidden_states.view(batch_size, *num_mask_units, *mask_unit_shape, hidden_size)
|
| 628 |
+
|
| 629 |
+
# From: [batch_size, num_mask_unit_height, num_mask_unit_width, mask_unit_height, mask_unit_width, hidden_size]
|
| 630 |
+
# To: [batch_size, num_mask_unit_height*mask_unit_height, num_mask_unit_width*mask_unit_width, hidden_size]
|
| 631 |
+
hidden_states = hidden_states.permute(0, 1, 3, 2, 4, 5)
|
| 632 |
+
hidden_states = hidden_states.reshape(batch_size, *shape, hidden_size)
|
| 633 |
+
|
| 634 |
+
return hidden_states
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
class HieraEncoder(nn.Module):
|
| 638 |
+
def __init__(self, config: HieraConfig) -> None:
|
| 639 |
+
super().__init__()
|
| 640 |
+
total_depth = sum(config.depths)
|
| 641 |
+
# stochastic depth decay rule
|
| 642 |
+
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, total_depth)]
|
| 643 |
+
# query strides rule
|
| 644 |
+
cumulative_depths = torch.tensor(config.depths).cumsum(0).tolist()
|
| 645 |
+
query_pool_layer = cumulative_depths[: config.num_query_pool]
|
| 646 |
+
query_strides = [math.prod(config.query_stride) if i in query_pool_layer else 1 for i in range(total_depth)]
|
| 647 |
+
|
| 648 |
+
# Transformer blocks
|
| 649 |
+
self.stages = nn.ModuleList()
|
| 650 |
+
hidden_size = config.embed_dim
|
| 651 |
+
stage_ends = [0] + cumulative_depths
|
| 652 |
+
masked_unit_area = math.prod(config.masked_unit_size)
|
| 653 |
+
query_stride_area = math.prod(config.query_stride)
|
| 654 |
+
for idx_stage, depth in enumerate(config.depths):
|
| 655 |
+
hidden_size_output = int(config.embed_dim * config.embed_dim_multiplier**idx_stage)
|
| 656 |
+
|
| 657 |
+
stage = HieraStage(
|
| 658 |
+
config=config,
|
| 659 |
+
depth=depth,
|
| 660 |
+
hidden_size=hidden_size,
|
| 661 |
+
hidden_size_output=hidden_size_output,
|
| 662 |
+
num_heads=config.num_heads[idx_stage],
|
| 663 |
+
drop_path=dpr[stage_ends[idx_stage] : stage_ends[idx_stage + 1]],
|
| 664 |
+
query_stride=query_strides[stage_ends[idx_stage] : stage_ends[idx_stage + 1]],
|
| 665 |
+
window_size=int(masked_unit_area * query_stride_area**-idx_stage),
|
| 666 |
+
use_mask_unit_attn=config.masked_unit_attention[idx_stage],
|
| 667 |
+
stage_num=idx_stage,
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
hidden_size = hidden_size_output
|
| 671 |
+
self.stages.append(stage)
|
| 672 |
+
|
| 673 |
+
# Setting reroll schedule
|
| 674 |
+
# The first stage has to reverse everything
|
| 675 |
+
# The next stage has to reverse all but the first unroll, etc.
|
| 676 |
+
stage_size = [i // s for i, s in zip(config.image_size, config.patch_stride)]
|
| 677 |
+
unroll_schedule = [config.query_stride] * len(config.depths[:-1])
|
| 678 |
+
|
| 679 |
+
self.schedule = {}
|
| 680 |
+
for idx_stage in range(len(config.depths)):
|
| 681 |
+
self.schedule[idx_stage] = unroll_schedule, stage_size
|
| 682 |
+
if idx_stage < config.num_query_pool:
|
| 683 |
+
stage_size = [i // s for i, s in zip(stage_size, config.query_stride)]
|
| 684 |
+
unroll_schedule = unroll_schedule[1:]
|
| 685 |
+
|
| 686 |
+
self.gradient_checkpointing = False
|
| 687 |
+
|
| 688 |
+
def reroll(
|
| 689 |
+
self, hidden_states: torch.Tensor, stage_idx: int, bool_masked_pos: Optional[torch.BoolTensor] = None
|
| 690 |
+
) -> torch.Tensor:
|
| 691 |
+
"""
|
| 692 |
+
Roll the given tensor back up to spatial order assuming it's from the given block.
|
| 693 |
+
|
| 694 |
+
If no bool_masked_pos is provided returns:
|
| 695 |
+
- [batch_size, height, width, hidden_size]
|
| 696 |
+
If a bool_masked_pos is provided returns:
|
| 697 |
+
- [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
|
| 698 |
+
"""
|
| 699 |
+
schedule, size = self.schedule[stage_idx]
|
| 700 |
+
batch_size, seq_len, hidden_size = hidden_states.shape
|
| 701 |
+
|
| 702 |
+
num_dim = len(size)
|
| 703 |
+
mask_unit_shape = [1] * num_dim
|
| 704 |
+
|
| 705 |
+
for strides in schedule:
|
| 706 |
+
# Extract the current patch from seq_len
|
| 707 |
+
hidden_states = hidden_states.view(
|
| 708 |
+
batch_size, *strides, seq_len // math.prod(strides), *mask_unit_shape, hidden_size
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# Move that patch into the current MU
|
| 712 |
+
# Input: [batch_size, stride, stride, seq_len//(stride*stride), mask_unit_height, mask_unit_width, hidden_size]
|
| 713 |
+
# Output: [batch_size, seq_len//(stride*stride), stride, mask_unit_height, stride, mask_unit_width, hidden_size]
|
| 714 |
+
hidden_states = hidden_states.permute(0, 3, 1, 4, 2, 5, 6)
|
| 715 |
+
|
| 716 |
+
# Reshape to [batch_size, seq_len//(stride*stride), *mask_units, hidden_size]
|
| 717 |
+
for i in range(num_dim):
|
| 718 |
+
mask_unit_shape[i] *= strides[i]
|
| 719 |
+
hidden_states = hidden_states.reshape(batch_size, -1, *mask_unit_shape, hidden_size)
|
| 720 |
+
seq_len = hidden_states.shape[1]
|
| 721 |
+
|
| 722 |
+
# Current shape (e.g., 2d: [batch_size, #num_mask_units_height*#num_mask_units_width, mask_unit_height, mask_unit_width, hidden_size])
|
| 723 |
+
hidden_states = hidden_states.view(batch_size, seq_len, *mask_unit_shape, hidden_size)
|
| 724 |
+
|
| 725 |
+
# If masked, return [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
|
| 726 |
+
if bool_masked_pos is not None:
|
| 727 |
+
return hidden_states
|
| 728 |
+
|
| 729 |
+
# If not masked, we can return [batch_size, height, width, hidden_size]
|
| 730 |
+
hidden_states = undo_windowing(hidden_states, size, mask_unit_shape)
|
| 731 |
+
|
| 732 |
+
return hidden_states
|
| 733 |
+
|
| 734 |
+
def forward(
|
| 735 |
+
self,
|
| 736 |
+
hidden_states: torch.Tensor,
|
| 737 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
| 738 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 739 |
+
output_attentions: bool = False,
|
| 740 |
+
output_hidden_states: bool = False,
|
| 741 |
+
return_dict: bool = True,
|
| 742 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 743 |
+
all_hidden_states = () if output_hidden_states else None
|
| 744 |
+
all_reshaped_hidden_states = () if output_hidden_states else None
|
| 745 |
+
all_self_attentions = () if output_attentions else None
|
| 746 |
+
|
| 747 |
+
if output_hidden_states:
|
| 748 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 749 |
+
reshaped_hidden_states = self.reroll(hidden_states, stage_idx=0, bool_masked_pos=bool_masked_pos)
|
| 750 |
+
all_reshaped_hidden_states = all_reshaped_hidden_states + (reshaped_hidden_states,)
|
| 751 |
+
|
| 752 |
+
for i, stage_module in enumerate(self.stages):
|
| 753 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 754 |
+
|
| 755 |
+
if self.gradient_checkpointing and self.training:
|
| 756 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 757 |
+
stage_module.__call__, hidden_states, layer_head_mask, output_attentions
|
| 758 |
+
)
|
| 759 |
+
else:
|
| 760 |
+
layer_outputs = stage_module(hidden_states, layer_head_mask, output_attentions)
|
| 761 |
+
|
| 762 |
+
hidden_states = layer_outputs[0]
|
| 763 |
+
|
| 764 |
+
if output_attentions:
|
| 765 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 766 |
+
|
| 767 |
+
if output_hidden_states:
|
| 768 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 769 |
+
reshaped_hidden_states = self.reroll(hidden_states, stage_idx=i, bool_masked_pos=bool_masked_pos)
|
| 770 |
+
all_reshaped_hidden_states = all_reshaped_hidden_states + (reshaped_hidden_states,)
|
| 771 |
+
|
| 772 |
+
if not return_dict:
|
| 773 |
+
return tuple(
|
| 774 |
+
v
|
| 775 |
+
for v in [hidden_states, all_hidden_states, all_self_attentions, all_reshaped_hidden_states]
|
| 776 |
+
if v is not None
|
| 777 |
+
)
|
| 778 |
+
return HieraEncoderOutput(
|
| 779 |
+
last_hidden_state=hidden_states,
|
| 780 |
+
hidden_states=all_hidden_states,
|
| 781 |
+
attentions=all_self_attentions,
|
| 782 |
+
reshaped_hidden_states=all_reshaped_hidden_states,
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def unroll(
|
| 787 |
+
hidden_states: torch.Tensor, image_shape: Tuple[int, int], patch_stride: Tuple[int, int], schedule: List[List[int]]
|
| 788 |
+
) -> torch.Tensor:
|
| 789 |
+
"""
|
| 790 |
+
Reorders the tokens such that patches are contiguous in memory.
|
| 791 |
+
E.g., given [batch_size, (height, width), hidden_size] and stride of (stride, stride), this will re-order the tokens as
|
| 792 |
+
[batch_size, (stride, stride, height // stride, width // stride), hidden_size]
|
| 793 |
+
|
| 794 |
+
This allows operations like Max2d to be computed as x.view(batch_size, stride*stride, -1, hidden_size).max(dim=1).
|
| 795 |
+
Not only is this faster, but it also makes it easy to support inputs of arbitrary
|
| 796 |
+
dimensions in addition to patch-wise sparsity.
|
| 797 |
+
|
| 798 |
+
Performing this operation multiple times in sequence puts entire windows as contiguous
|
| 799 |
+
in memory. For instance, if you applied the stride (2, 2) 3 times, entire windows of
|
| 800 |
+
size 8x8 would be contiguous in memory, allowing operations like mask unit attention
|
| 801 |
+
computed easily and efficiently, while also allowing max to be applied sequentially.
|
| 802 |
+
|
| 803 |
+
Note: This means that intermediate values of the model are not in height x width order, so they
|
| 804 |
+
need to be re-rolled if you want to use the intermediate values as a height x width feature map.
|
| 805 |
+
The last block of the network is fine though, since by then the strides are all consumed.
|
| 806 |
+
"""
|
| 807 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 808 |
+
|
| 809 |
+
size = [i // s for i, s in zip(image_shape, patch_stride)]
|
| 810 |
+
|
| 811 |
+
current_size = size
|
| 812 |
+
hidden_states = hidden_states.view(*([batch_size] + current_size + [hidden_size]))
|
| 813 |
+
|
| 814 |
+
for strides in schedule:
|
| 815 |
+
# Move patches with the given strides to the batch dimension
|
| 816 |
+
|
| 817 |
+
# Create a view of the tensor with the patch stride as separate dims
|
| 818 |
+
# For example in 2d: [batch_size, height // stride, stride, width // stride, stride, C]
|
| 819 |
+
current_size = [i // s for i, s in zip(current_size, strides)]
|
| 820 |
+
# initialize new_shape with [height // stride, stride, width // stride, stride]
|
| 821 |
+
new_shape = [item for pair in zip(current_size, strides) for item in pair]
|
| 822 |
+
# add batch_size and hidden_size to new_shape
|
| 823 |
+
new_shape = [batch_size] + new_shape + [hidden_size]
|
| 824 |
+
hidden_states = hidden_states.view(new_shape)
|
| 825 |
+
|
| 826 |
+
# Move the patch stride into the batch dimension
|
| 827 |
+
# For example in 2d: [batch_size, stride, stride, height // stride, width // stride, hidden_size]
|
| 828 |
+
num_dims = len(new_shape)
|
| 829 |
+
permute = [0] + list(range(2, num_dims - 1, 2)) + list(range(1, num_dims - 1, 2)) + [num_dims - 1]
|
| 830 |
+
hidden_states = hidden_states.permute(permute)
|
| 831 |
+
|
| 832 |
+
# Now finally flatten the relevant dims into the batch dimension
|
| 833 |
+
hidden_states = hidden_states.flatten(0, len(strides))
|
| 834 |
+
batch_size *= math.prod(strides)
|
| 835 |
+
|
| 836 |
+
hidden_states = hidden_states.reshape(-1, math.prod(size), hidden_size)
|
| 837 |
+
return hidden_states
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
class HieraPreTrainedModel(PreTrainedModel):
|
| 841 |
+
"""
|
| 842 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 843 |
+
models.
|
| 844 |
+
"""
|
| 845 |
+
|
| 846 |
+
config_class = HieraConfig
|
| 847 |
+
base_model_prefix = "hiera"
|
| 848 |
+
main_input_name = "pixel_values"
|
| 849 |
+
supports_gradient_checkpointing = True
|
| 850 |
+
|
| 851 |
+
def _init_weights(self, module) -> None:
|
| 852 |
+
"""Initialize the weights"""
|
| 853 |
+
std = self.config.initializer_range
|
| 854 |
+
|
| 855 |
+
if isinstance(module, HieraEmbeddings):
|
| 856 |
+
nn.init.trunc_normal_(module.position_embeddings, std=std)
|
| 857 |
+
|
| 858 |
+
elif isinstance(module, HieraDecoder):
|
| 859 |
+
nn.init.trunc_normal_(module.mask_token, std=std)
|
| 860 |
+
nn.init.trunc_normal_(module.decoder_position_embeddings, std=std)
|
| 861 |
+
|
| 862 |
+
elif isinstance(module, (nn.Linear, nn.Conv1d, nn.Conv2d)):
|
| 863 |
+
nn.init.trunc_normal_(module.weight, std=std)
|
| 864 |
+
if module.bias is not None:
|
| 865 |
+
nn.init.constant_(module.bias, std)
|
| 866 |
+
|
| 867 |
+
elif isinstance(module, nn.LayerNorm):
|
| 868 |
+
nn.init.constant_(module.bias, std)
|
| 869 |
+
nn.init.constant_(module.weight, self.config.layer_norm_init)
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
HIERA_START_DOCSTRING = r"""
|
| 873 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 874 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 875 |
+
behavior.
|
| 876 |
+
|
| 877 |
+
Parameters:
|
| 878 |
+
config ([`HieraConfig`]): Model configuration class with all the parameters of the model.
|
| 879 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 880 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 881 |
+
"""
|
| 882 |
+
|
| 883 |
+
HIERA_INPUTS_DOCSTRING = r"""
|
| 884 |
+
Args:
|
| 885 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 886 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`BitImageProcessor.__call__`]
|
| 887 |
+
for details.
|
| 888 |
+
|
| 889 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 890 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 891 |
+
|
| 892 |
+
- 1 indicates the head is **not masked**,
|
| 893 |
+
- 0 indicates the head is **masked**.
|
| 894 |
+
|
| 895 |
+
output_attentions (`bool`, *optional*):
|
| 896 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 897 |
+
tensors for more detail.
|
| 898 |
+
output_hidden_states (`bool`, *optional*):
|
| 899 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 900 |
+
more detail.
|
| 901 |
+
interpolate_pos_encoding (`bool`, *optional*):
|
| 902 |
+
Whether to interpolate the pre-trained position encodings.
|
| 903 |
+
return_dict (`bool`, *optional*):
|
| 904 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 905 |
+
"""
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
class HieraPooler(nn.Module):
|
| 909 |
+
def __init__(self, config: HieraConfig):
|
| 910 |
+
super().__init__()
|
| 911 |
+
num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
|
| 912 |
+
self.layernorm = nn.LayerNorm(num_features, eps=config.layer_norm_eps)
|
| 913 |
+
self.pooler = nn.AdaptiveAvgPool1d(1)
|
| 914 |
+
|
| 915 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 916 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 917 |
+
pooled_output = self.pooler(hidden_states)
|
| 918 |
+
pooled_output = torch.flatten(pooled_output, 1)
|
| 919 |
+
pooled_output = self.layernorm(pooled_output)
|
| 920 |
+
return pooled_output
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
@add_start_docstrings(
|
| 924 |
+
"The bare Hiera Model transformer outputting raw hidden-states without any specific head on top.",
|
| 925 |
+
HIERA_START_DOCSTRING,
|
| 926 |
+
"""
|
| 927 |
+
add_pooling_layer (`bool`, *optional*, defaults to `True`):
|
| 928 |
+
Whether or not to apply pooling layer.
|
| 929 |
+
is_mae (`bool`, *optional*, defaults to `False`):
|
| 930 |
+
Whether or not to run the model on MAE mode.
|
| 931 |
+
""",
|
| 932 |
+
)
|
| 933 |
+
class HieraModel(HieraPreTrainedModel):
|
| 934 |
+
def __init__(self, config: HieraConfig, add_pooling_layer: bool = True, is_mae: bool = False):
|
| 935 |
+
super().__init__(config)
|
| 936 |
+
self.num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
|
| 937 |
+
|
| 938 |
+
self.embeddings = HieraEmbeddings(config, is_mae=is_mae)
|
| 939 |
+
self.encoder = HieraEncoder(config)
|
| 940 |
+
|
| 941 |
+
self.unroll_schedule = [config.query_stride] * len(config.depths[:-1])
|
| 942 |
+
|
| 943 |
+
self.pooler = HieraPooler(config) if add_pooling_layer else None
|
| 944 |
+
|
| 945 |
+
# Initialize weights and apply final processing
|
| 946 |
+
self.post_init()
|
| 947 |
+
|
| 948 |
+
def get_input_embeddings(self) -> HieraPatchEmbeddings:
|
| 949 |
+
return self.embeddings.patch_embeddings
|
| 950 |
+
|
| 951 |
+
def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
|
| 952 |
+
"""
|
| 953 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 954 |
+
class PreTrainedModel
|
| 955 |
+
"""
|
| 956 |
+
for layer, heads in heads_to_prune.items():
|
| 957 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 958 |
+
|
| 959 |
+
@add_start_docstrings_to_model_forward(HIERA_INPUTS_DOCSTRING)
|
| 960 |
+
@add_code_sample_docstrings(
|
| 961 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 962 |
+
output_type=HieraModelOutput,
|
| 963 |
+
config_class=_CONFIG_FOR_DOC,
|
| 964 |
+
modality="vision",
|
| 965 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 966 |
+
)
|
| 967 |
+
def forward(
|
| 968 |
+
self,
|
| 969 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 970 |
+
noise: Optional[torch.FloatTensor] = None,
|
| 971 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 972 |
+
output_attentions: Optional[bool] = None,
|
| 973 |
+
output_hidden_states: Optional[bool] = None,
|
| 974 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 975 |
+
return_dict: Optional[bool] = None,
|
| 976 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 977 |
+
r"""
|
| 978 |
+
noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*) which is
|
| 979 |
+
mainly used for testing purposes to control randomness and maintain the reproducibility
|
| 980 |
+
when is_mae is set to True.
|
| 981 |
+
"""
|
| 982 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 983 |
+
output_hidden_states = (
|
| 984 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 985 |
+
)
|
| 986 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 987 |
+
|
| 988 |
+
if pixel_values is None:
|
| 989 |
+
raise ValueError("You have to specify pixel_values")
|
| 990 |
+
|
| 991 |
+
# Prepare head mask if needed
|
| 992 |
+
# 1.0 in head_mask indicate we keep the head
|
| 993 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 994 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 995 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 996 |
+
head_mask = self.get_head_mask(head_mask, len(self.config.depths))
|
| 997 |
+
|
| 998 |
+
embedding_output, bool_masked_pos, ids_restore = self.embeddings(
|
| 999 |
+
pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, noise=noise
|
| 1000 |
+
)
|
| 1001 |
+
|
| 1002 |
+
image_shape = (pixel_values.shape[-2], pixel_values.shape[-1])
|
| 1003 |
+
hidden_states = unroll(
|
| 1004 |
+
embedding_output,
|
| 1005 |
+
image_shape=image_shape,
|
| 1006 |
+
patch_stride=self.config.patch_stride,
|
| 1007 |
+
schedule=self.unroll_schedule,
|
| 1008 |
+
)
|
| 1009 |
+
|
| 1010 |
+
# Discard masked tokens if bool_masked_pos is provided
|
| 1011 |
+
if bool_masked_pos is not None:
|
| 1012 |
+
mask_unit_area = math.prod(self.config.masked_unit_size)
|
| 1013 |
+
batch_size, _, hidden_size = hidden_states.shape
|
| 1014 |
+
positions = bool_masked_pos.unsqueeze(-1).tile(1, mask_unit_area, hidden_size)
|
| 1015 |
+
hidden_states = hidden_states[positions]
|
| 1016 |
+
hidden_states = hidden_states.view(batch_size, -1, hidden_size)
|
| 1017 |
+
|
| 1018 |
+
encoder_outputs = self.encoder(
|
| 1019 |
+
hidden_states,
|
| 1020 |
+
bool_masked_pos=bool_masked_pos,
|
| 1021 |
+
head_mask=head_mask,
|
| 1022 |
+
output_attentions=output_attentions,
|
| 1023 |
+
output_hidden_states=output_hidden_states,
|
| 1024 |
+
return_dict=return_dict,
|
| 1025 |
+
)
|
| 1026 |
+
sequence_output = encoder_outputs[0]
|
| 1027 |
+
pooled_output = None
|
| 1028 |
+
if self.pooler is not None:
|
| 1029 |
+
pooled_output = self.pooler(sequence_output)
|
| 1030 |
+
|
| 1031 |
+
if not return_dict:
|
| 1032 |
+
head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
|
| 1033 |
+
head_outputs = (
|
| 1034 |
+
head_outputs + (bool_masked_pos, ids_restore) if bool_masked_pos is not None else head_outputs
|
| 1035 |
+
)
|
| 1036 |
+
return head_outputs + encoder_outputs[1:]
|
| 1037 |
+
|
| 1038 |
+
return HieraModelOutput(
|
| 1039 |
+
last_hidden_state=sequence_output,
|
| 1040 |
+
pooler_output=pooled_output,
|
| 1041 |
+
bool_masked_pos=bool_masked_pos,
|
| 1042 |
+
ids_restore=ids_restore,
|
| 1043 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 1044 |
+
attentions=encoder_outputs.attentions,
|
| 1045 |
+
reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
|
| 1046 |
+
)
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
class HieraDecoder(nn.Module):
|
| 1050 |
+
def __init__(self, config: HieraConfig):
|
| 1051 |
+
super().__init__()
|
| 1052 |
+
num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
|
| 1053 |
+
tokens_spatial_shape = [i // s for i, s in zip(config.image_size, config.patch_stride)]
|
| 1054 |
+
self.tokens_spatial_shape_final = [
|
| 1055 |
+
i // s ** (config.num_query_pool) for i, s in zip(tokens_spatial_shape, config.query_stride)
|
| 1056 |
+
]
|
| 1057 |
+
self.mask_unit_spatial_shape_final = [
|
| 1058 |
+
i // s ** (config.num_query_pool) for i, s in zip(config.masked_unit_size, config.query_stride)
|
| 1059 |
+
]
|
| 1060 |
+
|
| 1061 |
+
self.decoder_embeddings = nn.Linear(num_features, config.decoder_hidden_size)
|
| 1062 |
+
|
| 1063 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
|
| 1064 |
+
|
| 1065 |
+
self.decoder_position_embeddings = nn.Parameter(
|
| 1066 |
+
torch.zeros(1, math.prod(self.tokens_spatial_shape_final), config.decoder_hidden_size)
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
self.decoder_block = HieraStage(
|
| 1070 |
+
config=config,
|
| 1071 |
+
hidden_size=config.decoder_hidden_size,
|
| 1072 |
+
hidden_size_output=config.decoder_hidden_size,
|
| 1073 |
+
num_heads=config.decoder_num_heads,
|
| 1074 |
+
depth=config.decoder_depth,
|
| 1075 |
+
use_mask_unit_attn=False,
|
| 1076 |
+
drop_path=[0.0] * config.decoder_depth,
|
| 1077 |
+
query_stride=[1] * config.decoder_depth,
|
| 1078 |
+
window_size=0,
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
self.decoder_norm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
|
| 1082 |
+
|
| 1083 |
+
# patch stride of prediction
|
| 1084 |
+
self.pred_stride = config.patch_stride[-1] * (config.query_stride[-1] ** config.num_query_pool)
|
| 1085 |
+
pred_dim = (self.pred_stride ** len(config.query_stride)) * config.num_channels
|
| 1086 |
+
|
| 1087 |
+
self.decoder_pred = nn.Linear(config.decoder_hidden_size, pred_dim)
|
| 1088 |
+
|
| 1089 |
+
def forward(
|
| 1090 |
+
self,
|
| 1091 |
+
encoder_hidden_states: torch.Tensor,
|
| 1092 |
+
bool_masked_pos: torch.BoolTensor,
|
| 1093 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1094 |
+
output_attentions: bool = False,
|
| 1095 |
+
) -> Tuple[torch.Tensor, torch.BoolTensor]:
|
| 1096 |
+
# Embed tokens
|
| 1097 |
+
hidden_states = self.decoder_embeddings(encoder_hidden_states)
|
| 1098 |
+
|
| 1099 |
+
# Combine visible and bool_masked_pos tokens
|
| 1100 |
+
|
| 1101 |
+
# hidden_states : [batch_size, num_mask_units_visible, *mask_unit_spatial_shape_final, decoder_hidden_size]
|
| 1102 |
+
# bool_masked_pos: [batch_size, num_mask_units]
|
| 1103 |
+
mask_unit_height, mask_unit_width, decoder_hidden_size = hidden_states.shape[2:]
|
| 1104 |
+
batch_size, num_mask_units = bool_masked_pos.shape
|
| 1105 |
+
|
| 1106 |
+
decoder_hidden_states = torch.zeros(
|
| 1107 |
+
batch_size,
|
| 1108 |
+
num_mask_units,
|
| 1109 |
+
mask_unit_height,
|
| 1110 |
+
mask_unit_width,
|
| 1111 |
+
decoder_hidden_size,
|
| 1112 |
+
device=hidden_states.device,
|
| 1113 |
+
dtype=hidden_states.dtype,
|
| 1114 |
+
)
|
| 1115 |
+
mask_tokens = self.mask_token.view(1, 1, 1, 1, -1)
|
| 1116 |
+
bool_masked_pos = bool_masked_pos.reshape(batch_size, num_mask_units, 1, 1, 1)
|
| 1117 |
+
bool_masked_pos = bool_masked_pos.expand(-1, -1, mask_unit_height, mask_unit_width, decoder_hidden_size)
|
| 1118 |
+
decoder_hidden_states[bool_masked_pos] = hidden_states.flatten()
|
| 1119 |
+
decoder_hidden_states = (
|
| 1120 |
+
1 - bool_masked_pos.float()
|
| 1121 |
+
) * mask_tokens + bool_masked_pos.float() * decoder_hidden_states
|
| 1122 |
+
|
| 1123 |
+
# Get back spatial order
|
| 1124 |
+
hidden_states = undo_windowing(
|
| 1125 |
+
decoder_hidden_states,
|
| 1126 |
+
self.tokens_spatial_shape_final,
|
| 1127 |
+
self.mask_unit_spatial_shape_final,
|
| 1128 |
+
)
|
| 1129 |
+
bool_masked_pos = undo_windowing(
|
| 1130 |
+
bool_masked_pos[..., 0:1],
|
| 1131 |
+
self.tokens_spatial_shape_final,
|
| 1132 |
+
self.mask_unit_spatial_shape_final,
|
| 1133 |
+
)
|
| 1134 |
+
|
| 1135 |
+
# Flatten
|
| 1136 |
+
hidden_states = hidden_states.reshape(hidden_states.shape[0], -1, hidden_states.shape[-1])
|
| 1137 |
+
bool_masked_pos = bool_masked_pos.view(hidden_states.shape[0], -1)
|
| 1138 |
+
|
| 1139 |
+
# Add pos embed
|
| 1140 |
+
hidden_states = hidden_states + self.decoder_position_embeddings
|
| 1141 |
+
|
| 1142 |
+
# Apply decoder blocks
|
| 1143 |
+
hidden_states, attn_weights = self.decoder_block(
|
| 1144 |
+
hidden_states, head_mask=head_mask, output_attentions=output_attentions
|
| 1145 |
+
)
|
| 1146 |
+
hidden_states = self.decoder_norm(hidden_states)
|
| 1147 |
+
|
| 1148 |
+
# Predictor projection
|
| 1149 |
+
hidden_states = self.decoder_pred(hidden_states)
|
| 1150 |
+
|
| 1151 |
+
return hidden_states, bool_masked_pos
|
| 1152 |
+
|
| 1153 |
+
|
| 1154 |
+
class HieraMultiScaleHead(nn.Module):
|
| 1155 |
+
def __init__(self, config: HieraConfig):
|
| 1156 |
+
super().__init__()
|
| 1157 |
+
self.mask_unit_spatial_shape_final = [
|
| 1158 |
+
i // s ** (config.num_query_pool) for i, s in zip(config.masked_unit_size, config.query_stride)
|
| 1159 |
+
]
|
| 1160 |
+
self.stage_dimensions = [
|
| 1161 |
+
int(config.embed_dim * config.embed_dim_multiplier**i) for i in range(len(config.depths))
|
| 1162 |
+
]
|
| 1163 |
+
current_masked_unit_size = config.masked_unit_size
|
| 1164 |
+
self.multi_scale_fusion_heads = nn.ModuleList()
|
| 1165 |
+
|
| 1166 |
+
for idx in range(config.num_query_pool):
|
| 1167 |
+
kernel = [i // s for i, s in zip(current_masked_unit_size, self.mask_unit_spatial_shape_final)]
|
| 1168 |
+
current_masked_unit_size = [i // s for i, s in zip(current_masked_unit_size, config.query_stride)]
|
| 1169 |
+
self.multi_scale_fusion_heads.append(
|
| 1170 |
+
nn.Conv2d(
|
| 1171 |
+
self.stage_dimensions[idx],
|
| 1172 |
+
self.stage_dimensions[-1],
|
| 1173 |
+
kernel_size=kernel,
|
| 1174 |
+
stride=kernel,
|
| 1175 |
+
)
|
| 1176 |
+
)
|
| 1177 |
+
self.multi_scale_fusion_heads.append(nn.Identity())
|
| 1178 |
+
|
| 1179 |
+
def apply_fusion_head(self, head: nn.Module, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 1180 |
+
if isinstance(head, nn.Identity):
|
| 1181 |
+
return hidden_states
|
| 1182 |
+
|
| 1183 |
+
# Doing explicit to avoid problems with torch.fx
|
| 1184 |
+
batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size = hidden_states.shape
|
| 1185 |
+
# From: [batch_size, num_mask_units, mask_unit_height, mask_unit_width, hidden_size]
|
| 1186 |
+
# To: head([batch_size * num_mask_units, hidden_size, mask_unit_height, mask_unit_width])
|
| 1187 |
+
hidden_states = hidden_states.reshape(
|
| 1188 |
+
batch_size * num_mask_units, mask_unit_height, mask_unit_width, hidden_size
|
| 1189 |
+
)
|
| 1190 |
+
hidden_states = hidden_states.permute(0, 3, 1, 2)
|
| 1191 |
+
hidden_states = head(hidden_states)
|
| 1192 |
+
|
| 1193 |
+
# Restore original layout
|
| 1194 |
+
hidden_states = hidden_states.permute(0, 2, 3, 1)
|
| 1195 |
+
mask_unit_height_final, mask_unit_width_final, hidden_size = hidden_states.shape[1:]
|
| 1196 |
+
hidden_states = hidden_states.reshape(
|
| 1197 |
+
batch_size, num_mask_units, mask_unit_height_final, mask_unit_width_final, hidden_size
|
| 1198 |
+
)
|
| 1199 |
+
|
| 1200 |
+
return hidden_states
|
| 1201 |
+
|
| 1202 |
+
def forward(self, feature_maps: List[torch.Tensor]) -> torch.Tensor:
|
| 1203 |
+
# Multi-scale fusion
|
| 1204 |
+
hidden_states = 0.0
|
| 1205 |
+
for head, feature_map in zip(self.multi_scale_fusion_heads, feature_maps):
|
| 1206 |
+
hidden_states = hidden_states + self.apply_fusion_head(head, feature_map)
|
| 1207 |
+
|
| 1208 |
+
return hidden_states
|
| 1209 |
+
|
| 1210 |
+
|
| 1211 |
+
@add_start_docstrings(
|
| 1212 |
+
"""The Hiera Model transformer with the decoder on top for self-supervised pre-training.
|
| 1213 |
+
|
| 1214 |
+
<Tip>
|
| 1215 |
+
|
| 1216 |
+
Note that we provide a script to pre-train this model on custom data in our [examples
|
| 1217 |
+
directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
|
| 1218 |
+
|
| 1219 |
+
</Tip>
|
| 1220 |
+
""",
|
| 1221 |
+
HIERA_START_DOCSTRING,
|
| 1222 |
+
)
|
| 1223 |
+
class HieraForPreTraining(HieraPreTrainedModel):
|
| 1224 |
+
def __init__(self, config: HieraConfig) -> None:
|
| 1225 |
+
super().__init__(config)
|
| 1226 |
+
# Encoder
|
| 1227 |
+
self.hiera = HieraModel(config, add_pooling_layer=False, is_mae=True)
|
| 1228 |
+
self.encoder_norm = nn.LayerNorm(self.hiera.num_features, eps=config.layer_norm_eps)
|
| 1229 |
+
# Multi-scale fusion heads
|
| 1230 |
+
self.multiscale_fusion = HieraMultiScaleHead(config)
|
| 1231 |
+
# Decoder
|
| 1232 |
+
self.decoder = HieraDecoder(config)
|
| 1233 |
+
self.pred_stride = self.decoder.pred_stride
|
| 1234 |
+
|
| 1235 |
+
# Initialize weights and apply final processing
|
| 1236 |
+
self.post_init()
|
| 1237 |
+
|
| 1238 |
+
def get_pixel_label_2d(self, pixel_values: torch.Tensor, bool_masked_pos: torch.BoolTensor) -> torch.Tensor:
|
| 1239 |
+
# bool_masked_pos (boolean tensor): True means *masked*
|
| 1240 |
+
pixel_values = pixel_values.permute(0, 2, 3, 1)
|
| 1241 |
+
|
| 1242 |
+
size = self.pred_stride
|
| 1243 |
+
label = pixel_values.unfold(1, size, size).unfold(2, size, size)
|
| 1244 |
+
label = label.flatten(1, 2).flatten(2)
|
| 1245 |
+
label = label[bool_masked_pos]
|
| 1246 |
+
if self.config.normalize_pixel_loss:
|
| 1247 |
+
mean = label.mean(dim=-1, keepdim=True)
|
| 1248 |
+
var = label.var(dim=-1, keepdim=True)
|
| 1249 |
+
label = (label - mean) / (var + 1.0e-6) ** 0.5
|
| 1250 |
+
|
| 1251 |
+
return label
|
| 1252 |
+
|
| 1253 |
+
def forward_loss(self, pixel_values: torch.Tensor, logits: torch.Tensor, bool_masked_pos: torch.BoolTensor):
|
| 1254 |
+
# We invert the bool_masked_pos such that 1.0 is *masked*
|
| 1255 |
+
bool_masked_pos = ~bool_masked_pos
|
| 1256 |
+
label = self.get_pixel_label_2d(pixel_values, bool_masked_pos)
|
| 1257 |
+
|
| 1258 |
+
logits = logits[bool_masked_pos]
|
| 1259 |
+
loss = (logits - label) ** 2
|
| 1260 |
+
loss = loss.mean()
|
| 1261 |
+
|
| 1262 |
+
return loss
|
| 1263 |
+
|
| 1264 |
+
@add_start_docstrings_to_model_forward(HIERA_INPUTS_DOCSTRING)
|
| 1265 |
+
@replace_return_docstrings(output_type=HieraForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
| 1266 |
+
def forward(
|
| 1267 |
+
self,
|
| 1268 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1269 |
+
noise: Optional[torch.FloatTensor] = None,
|
| 1270 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1271 |
+
output_attentions: Optional[bool] = None,
|
| 1272 |
+
output_hidden_states: Optional[bool] = None,
|
| 1273 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 1274 |
+
return_dict: Optional[bool] = None,
|
| 1275 |
+
) -> Union[tuple, HieraForPreTrainingOutput]:
|
| 1276 |
+
r"""
|
| 1277 |
+
noise (`torch.FloatTensor` of shape `(batch_size, num_mask_units)`, *optional*) which is
|
| 1278 |
+
mainly used for testing purposes to control randomness and maintain the reproducibility
|
| 1279 |
+
when is_mae is set to True.
|
| 1280 |
+
|
| 1281 |
+
Returns:
|
| 1282 |
+
|
| 1283 |
+
Examples:
|
| 1284 |
+
```python
|
| 1285 |
+
>>> from transformers import AutoImageProcessor, HieraForPreTraining
|
| 1286 |
+
>>> import torch
|
| 1287 |
+
>>> from PIL import Image
|
| 1288 |
+
>>> import requests
|
| 1289 |
+
|
| 1290 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1291 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1292 |
+
|
| 1293 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/hiera-tiny-224-mae-hf")
|
| 1294 |
+
>>> model = HieraForPreTraining.from_pretrained("facebook/hiera-tiny-224-mae-hf")
|
| 1295 |
+
|
| 1296 |
+
>>> inputs = image_processor(images=image, return_tensors="pt")
|
| 1297 |
+
|
| 1298 |
+
>>> outputs = model(**inputs)
|
| 1299 |
+
>>> logits = outputs.logits
|
| 1300 |
+
>>> loss = outputs.loss
|
| 1301 |
+
>>> print(list(logits.shape))
|
| 1302 |
+
[1, 196, 768]
|
| 1303 |
+
```"""
|
| 1304 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1305 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1306 |
+
output_hidden_states = (
|
| 1307 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1308 |
+
)
|
| 1309 |
+
|
| 1310 |
+
outputs = self.hiera(
|
| 1311 |
+
pixel_values,
|
| 1312 |
+
noise=noise,
|
| 1313 |
+
head_mask=head_mask,
|
| 1314 |
+
output_attentions=output_attentions,
|
| 1315 |
+
output_hidden_states=True,
|
| 1316 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1317 |
+
return_dict=return_dict,
|
| 1318 |
+
)
|
| 1319 |
+
|
| 1320 |
+
feature_maps = outputs[-1]
|
| 1321 |
+
bool_masked_pos = outputs[1]
|
| 1322 |
+
ids_to_restore = outputs[2]
|
| 1323 |
+
# Take only the query pooled and last hidden states
|
| 1324 |
+
feature_maps = feature_maps[1 : self.hiera.config.num_query_pool + 1] + (feature_maps[-1],)
|
| 1325 |
+
fused_hidden_states = self.multiscale_fusion(feature_maps)
|
| 1326 |
+
fused_hidden_states = self.encoder_norm(fused_hidden_states)
|
| 1327 |
+
|
| 1328 |
+
# Reconstruct pixel values
|
| 1329 |
+
logits, bool_masked_pos = self.decoder(
|
| 1330 |
+
fused_hidden_states,
|
| 1331 |
+
bool_masked_pos=bool_masked_pos,
|
| 1332 |
+
head_mask=head_mask,
|
| 1333 |
+
output_attentions=output_attentions,
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
loss = self.forward_loss(pixel_values, logits, bool_masked_pos)
|
| 1337 |
+
|
| 1338 |
+
if not return_dict:
|
| 1339 |
+
output = (logits, bool_masked_pos, ids_to_restore)
|
| 1340 |
+
if output_hidden_states:
|
| 1341 |
+
output = output + (outputs[3],)
|
| 1342 |
+
if output_attentions:
|
| 1343 |
+
output = output + (outputs[4],)
|
| 1344 |
+
if output_hidden_states:
|
| 1345 |
+
output = output + (outputs[-1],)
|
| 1346 |
+
return ((loss,) + output) if loss is not None else output
|
| 1347 |
+
|
| 1348 |
+
return HieraForPreTrainingOutput(
|
| 1349 |
+
loss=loss,
|
| 1350 |
+
logits=logits,
|
| 1351 |
+
bool_masked_pos=bool_masked_pos,
|
| 1352 |
+
ids_restore=ids_to_restore,
|
| 1353 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 1354 |
+
attentions=outputs.attentions,
|
| 1355 |
+
reshaped_hidden_states=outputs.reshaped_hidden_states if output_hidden_states else None,
|
| 1356 |
+
)
|
| 1357 |
+
|
| 1358 |
+
|
| 1359 |
+
@add_start_docstrings(
|
| 1360 |
+
"""
|
| 1361 |
+
Hiera Model transformer with an image classification head on top (a linear layer on top of the final hidden state with
|
| 1362 |
+
average pooling) e.g. for ImageNet.
|
| 1363 |
+
|
| 1364 |
+
<Tip>
|
| 1365 |
+
|
| 1366 |
+
Note that it's possible to fine-tune Hiera on higher resolution images than the ones it has been trained on, by
|
| 1367 |
+
setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
|
| 1368 |
+
position embeddings to the higher resolution.
|
| 1369 |
+
|
| 1370 |
+
</Tip>
|
| 1371 |
+
""",
|
| 1372 |
+
HIERA_START_DOCSTRING,
|
| 1373 |
+
)
|
| 1374 |
+
class HieraForImageClassification(HieraPreTrainedModel):
|
| 1375 |
+
def __init__(self, config: HieraConfig) -> None:
|
| 1376 |
+
super().__init__(config)
|
| 1377 |
+
|
| 1378 |
+
self.num_labels = config.num_labels
|
| 1379 |
+
self.hiera = HieraModel(config, add_pooling_layer=True, is_mae=False)
|
| 1380 |
+
|
| 1381 |
+
# Classifier head
|
| 1382 |
+
self.classifier = (
|
| 1383 |
+
nn.Linear(self.hiera.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 1384 |
+
)
|
| 1385 |
+
|
| 1386 |
+
# Initialize weights and apply final processing
|
| 1387 |
+
self.post_init()
|
| 1388 |
+
|
| 1389 |
+
@add_start_docstrings_to_model_forward(HIERA_INPUTS_DOCSTRING)
|
| 1390 |
+
@add_code_sample_docstrings(
|
| 1391 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 1392 |
+
output_type=HieraForImageClassificationOutput,
|
| 1393 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1394 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 1395 |
+
)
|
| 1396 |
+
def forward(
|
| 1397 |
+
self,
|
| 1398 |
+
pixel_values,
|
| 1399 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 1400 |
+
labels: Optional[torch.Tensor] = None,
|
| 1401 |
+
output_attentions: Optional[bool] = None,
|
| 1402 |
+
output_hidden_states: Optional[bool] = None,
|
| 1403 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
| 1404 |
+
return_dict: Optional[bool] = None,
|
| 1405 |
+
) -> Union[tuple, HieraForImageClassificationOutput]:
|
| 1406 |
+
r"""
|
| 1407 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1408 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 1409 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1410 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1411 |
+
"""
|
| 1412 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1413 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1414 |
+
output_hidden_states = (
|
| 1415 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1416 |
+
)
|
| 1417 |
+
|
| 1418 |
+
outputs = self.hiera(
|
| 1419 |
+
pixel_values,
|
| 1420 |
+
head_mask=head_mask,
|
| 1421 |
+
output_attentions=output_attentions,
|
| 1422 |
+
output_hidden_states=output_hidden_states,
|
| 1423 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
| 1424 |
+
return_dict=return_dict,
|
| 1425 |
+
)
|
| 1426 |
+
|
| 1427 |
+
pooled_output = outputs[1]
|
| 1428 |
+
|
| 1429 |
+
logits = self.classifier(pooled_output)
|
| 1430 |
+
|
| 1431 |
+
loss = None
|
| 1432 |
+
if labels is not None:
|
| 1433 |
+
# move labels to correct device to enable model parallelism
|
| 1434 |
+
labels = labels.to(logits.device)
|
| 1435 |
+
if self.config.problem_type is None:
|
| 1436 |
+
if self.num_labels == 1:
|
| 1437 |
+
self.config.problem_type = "regression"
|
| 1438 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1439 |
+
self.config.problem_type = "single_label_classification"
|
| 1440 |
+
else:
|
| 1441 |
+
self.config.problem_type = "multi_label_classification"
|
| 1442 |
+
|
| 1443 |
+
if self.config.problem_type == "regression":
|
| 1444 |
+
loss_fct = MSELoss()
|
| 1445 |
+
if self.num_labels == 1:
|
| 1446 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1447 |
+
else:
|
| 1448 |
+
loss = loss_fct(logits, labels)
|
| 1449 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1450 |
+
loss_fct = CrossEntropyLoss()
|
| 1451 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 1452 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1453 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1454 |
+
loss = loss_fct(logits, labels)
|
| 1455 |
+
|
| 1456 |
+
if not return_dict:
|
| 1457 |
+
output = (logits,) + outputs[2:]
|
| 1458 |
+
return ((loss,) + output) if loss is not None else output
|
| 1459 |
+
|
| 1460 |
+
return HieraForImageClassificationOutput(
|
| 1461 |
+
loss=loss,
|
| 1462 |
+
logits=logits,
|
| 1463 |
+
hidden_states=outputs.hidden_states,
|
| 1464 |
+
attentions=outputs.attentions,
|
| 1465 |
+
reshaped_hidden_states=outputs.reshaped_hidden_states,
|
| 1466 |
+
)
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
@add_start_docstrings(
|
| 1470 |
+
"""
|
| 1471 |
+
Hiera backbone, to be used with frameworks like DETR and MaskFormer.
|
| 1472 |
+
""",
|
| 1473 |
+
HIERA_START_DOCSTRING,
|
| 1474 |
+
)
|
| 1475 |
+
class HieraBackbone(HieraPreTrainedModel, BackboneMixin):
|
| 1476 |
+
def __init__(self, config: HieraConfig):
|
| 1477 |
+
super().__init__(config)
|
| 1478 |
+
super()._init_backbone(config)
|
| 1479 |
+
|
| 1480 |
+
self.num_features = [config.embed_dim] + [
|
| 1481 |
+
int(config.embed_dim * config.embed_dim_multiplier**i) for i in range(len(config.depths))
|
| 1482 |
+
]
|
| 1483 |
+
self.embeddings = HieraEmbeddings(config, is_mae=False)
|
| 1484 |
+
self.encoder = HieraEncoder(config)
|
| 1485 |
+
|
| 1486 |
+
# Add layer norms to hidden states of out_features
|
| 1487 |
+
hidden_states_norms = {}
|
| 1488 |
+
for stage, num_channels in zip(self._out_features, self.channels):
|
| 1489 |
+
hidden_states_norms[stage] = nn.LayerNorm(num_channels)
|
| 1490 |
+
self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
|
| 1491 |
+
|
| 1492 |
+
# Initialize weights and apply final processing
|
| 1493 |
+
self.post_init()
|
| 1494 |
+
|
| 1495 |
+
def get_input_embeddings(self):
|
| 1496 |
+
return self.embeddings.patch_embeddings
|
| 1497 |
+
|
| 1498 |
+
def forward(
|
| 1499 |
+
self,
|
| 1500 |
+
pixel_values: torch.Tensor,
|
| 1501 |
+
output_hidden_states: Optional[bool] = None,
|
| 1502 |
+
output_attentions: Optional[bool] = None,
|
| 1503 |
+
return_dict: Optional[bool] = None,
|
| 1504 |
+
) -> BackboneOutput:
|
| 1505 |
+
"""
|
| 1506 |
+
Returns:
|
| 1507 |
+
|
| 1508 |
+
Examples:
|
| 1509 |
+
|
| 1510 |
+
```python
|
| 1511 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 1512 |
+
>>> import torch
|
| 1513 |
+
>>> from PIL import Image
|
| 1514 |
+
>>> import requests
|
| 1515 |
+
|
| 1516 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1517 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1518 |
+
|
| 1519 |
+
>>> processor = AutoImageProcessor.from_pretrained("facebook/hiera-tiny-224-hf")
|
| 1520 |
+
>>> model = AutoBackbone.from_pretrained(
|
| 1521 |
+
... "facebook/hiera-tiny-224-hf", out_features=["stage1", "stage2", "stage3", "stage4"]
|
| 1522 |
+
... )
|
| 1523 |
+
|
| 1524 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 1525 |
+
>>> outputs = model(**inputs)
|
| 1526 |
+
>>> feature_maps = outputs.feature_maps
|
| 1527 |
+
>>> list(feature_maps[-1].shape)
|
| 1528 |
+
[1, 768, 7, 7]
|
| 1529 |
+
```"""
|
| 1530 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1531 |
+
output_hidden_states = (
|
| 1532 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1533 |
+
)
|
| 1534 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1535 |
+
|
| 1536 |
+
embedding_output, _, _ = self.embeddings(pixel_values)
|
| 1537 |
+
|
| 1538 |
+
outputs = self.encoder(
|
| 1539 |
+
embedding_output,
|
| 1540 |
+
head_mask=None,
|
| 1541 |
+
output_attentions=output_attentions,
|
| 1542 |
+
output_hidden_states=True,
|
| 1543 |
+
return_dict=return_dict,
|
| 1544 |
+
)
|
| 1545 |
+
|
| 1546 |
+
hidden_states = outputs[-1]
|
| 1547 |
+
|
| 1548 |
+
feature_maps = ()
|
| 1549 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 1550 |
+
if stage in self.out_features:
|
| 1551 |
+
batch_size, height, width, num_channels = hidden_state.shape
|
| 1552 |
+
hidden_state = hidden_state.view(batch_size, height * width, num_channels)
|
| 1553 |
+
hidden_state = self.hidden_states_norms[stage](hidden_state)
|
| 1554 |
+
hidden_state = hidden_state.view(batch_size, height, width, num_channels)
|
| 1555 |
+
hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
|
| 1556 |
+
feature_maps += (hidden_state,)
|
| 1557 |
+
|
| 1558 |
+
if not return_dict:
|
| 1559 |
+
output = (feature_maps,)
|
| 1560 |
+
if output_hidden_states:
|
| 1561 |
+
output += (outputs[1],)
|
| 1562 |
+
if output_attentions:
|
| 1563 |
+
output += (outputs[2],)
|
| 1564 |
+
return output
|
| 1565 |
+
|
| 1566 |
+
return BackboneOutput(
|
| 1567 |
+
feature_maps=feature_maps,
|
| 1568 |
+
hidden_states=outputs[1] if output_hidden_states else None,
|
| 1569 |
+
attentions=outputs[2] if output_attentions else None,
|
| 1570 |
+
)
|
| 1571 |
+
|
| 1572 |
+
|
| 1573 |
+
__all__ = ["HieraForImageClassification", "HieraForPreTraining", "HieraBackbone", "HieraModel", "HieraPreTrainedModel"]
|
vlmpy310/lib/python3.10/site-packages/transformers/models/mixtral/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Mixtral AI and The HuggingFace Inc. team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import (
|
| 17 |
+
OptionalDependencyNotAvailable,
|
| 18 |
+
_LazyModule,
|
| 19 |
+
is_torch_available,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_import_structure = {
|
| 24 |
+
"configuration_mixtral": ["MixtralConfig"],
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
if not is_torch_available():
|
| 30 |
+
raise OptionalDependencyNotAvailable()
|
| 31 |
+
except OptionalDependencyNotAvailable:
|
| 32 |
+
pass
|
| 33 |
+
else:
|
| 34 |
+
_import_structure["modeling_mixtral"] = [
|
| 35 |
+
"MixtralForCausalLM",
|
| 36 |
+
"MixtralForQuestionAnswering",
|
| 37 |
+
"MixtralModel",
|
| 38 |
+
"MixtralPreTrainedModel",
|
| 39 |
+
"MixtralForSequenceClassification",
|
| 40 |
+
"MixtralForTokenClassification",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if TYPE_CHECKING:
|
| 45 |
+
from .configuration_mixtral import MixtralConfig
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
if not is_torch_available():
|
| 49 |
+
raise OptionalDependencyNotAvailable()
|
| 50 |
+
except OptionalDependencyNotAvailable:
|
| 51 |
+
pass
|
| 52 |
+
else:
|
| 53 |
+
from .modeling_mixtral import (
|
| 54 |
+
MixtralForCausalLM,
|
| 55 |
+
MixtralForQuestionAnswering,
|
| 56 |
+
MixtralForSequenceClassification,
|
| 57 |
+
MixtralForTokenClassification,
|
| 58 |
+
MixtralModel,
|
| 59 |
+
MixtralPreTrainedModel,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
else:
|
| 64 |
+
import sys
|
| 65 |
+
|
| 66 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|